graphity_core/back_edges.rs
1//! The back edges of a graph: the edges that a depth-first search finds pointing back to a node on
2//! its current path, self-loops included - Java's class `BackEdges`.
3//!
4//! Every cycle contains a back edge, so a graph without back edges is a DAG (directed acyclic graph),
5//! and removing the back edges of a graph leaves a DAG. They form a feedback arc set, though not in
6//! general a smallest one.
7//!
8//! Uses the
9//! [depth-first search](https://en.wikipedia.org/wiki/Depth-first_search#Output_of_a_depth-first_search)
10//! of [`EdgeTypes::of`](crate::EdgeTypes::of), without recursion: [`of`] finds the edges that
11//! `EdgeTypes` classifies as [`EdgeType::Back`](crate::EdgeType::Back), without classifying the
12//! others.
13//!
14//! ```
15//! use graphity_core::{back_edges, GraphBuilder};
16//!
17//! let mut b = GraphBuilder::new();
18//! b.add_nodes(4);
19//! b.add_path(&[0, 1, 2, 3, 0]);
20//! let back = back_edges::of(&b.build());
21//! assert_eq!((back.source_nodes(), back.target_nodes()), (&[3][..], &[0][..]));
22//! ```
23
24use crate::{Edges, Graph, dfs_frames, growth};
25
26const VISITED: u32 = 0b01;
27const ON_STACK: u32 = 0b10;
28
29/// Returns the back edges of `graph`, in the order in which the search finds them.
30///
31/// Unlike the other results that list edges, they do not come in edge index order. For that order,
32/// use [`Edges::of(&EdgeTypes::of(graph), EdgeType::Back)`](crate::Edges::of): the same edges, at
33/// the cost of classifying every edge first.
34///
35/// **Time:** O(node_count + edge_count).
36/// **Memory:** 12 bytes per back edge for the result; while it runs, up to 18 bytes more per back
37/// edge, 2 bits per node and up to 8 x node_count bytes for the stack, which grows with the
38/// deepest path.
39///
40/// # Panics
41/// With an `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
42pub fn of(graph: &Graph) -> Edges {
43 let n = graph.node_count() as usize;
44 let out = graph.out_adjacency_start();
45 let adj = graph.out_adjacency();
46 // Visited and on-stack, 2 bits per node, 16 nodes per word: one load yields both flags.
47 let mut state = vec![0u32; (n >> 4) + 1];
48 let (mut sources, mut targets, mut edge_indices) = (Vec::new(), Vec::new(), Vec::new());
49 let mut frames = dfs_frames::initial(n as u32);
50
51 for root in 0..n {
52 let r_shift = (root & 0xF) << 1;
53 if (state[root >> 4] >> r_shift) & VISITED != 0 {
54 continue;
55 }
56 state[root >> 4] |= (VISITED | ON_STACK) << r_shift;
57 frames[0] = root as u32;
58 frames[1] = out[root];
59 let mut top = 0usize;
60
61 'outer: loop {
62 let u = frames[2 * top] as usize;
63 let end = out[u + 1] as usize;
64 let mut i = frames[2 * top + 1] as usize;
65 while i < end {
66 let v = adj[i] as usize;
67 i += 1;
68 let shift = (v & 0xF) << 1;
69 let flags = state[v >> 4] >> shift;
70 if flags & VISITED == 0 {
71 frames[2 * top + 1] = i as u32;
72 state[v >> 4] |= (VISITED | ON_STACK) << shift;
73 top += 1;
74 if top == frames.len() >> 1 {
75 dfs_frames::grow(&mut frames, n as u32);
76 }
77 frames[2 * top] = v as u32;
78 frames[2 * top + 1] = out[v];
79 continue 'outer;
80 } else if flags & ON_STACK != 0 {
81 growth::push(&mut sources, u as u32);
82 growth::push(&mut targets, v as u32);
83 growth::push(&mut edge_indices, i as u32 - 1);
84 }
85 }
86 state[u >> 4] &= !(ON_STACK << ((u & 0xF) << 1)); // postorder: leave the stack
87 if top == 0 {
88 break;
89 }
90 top -= 1;
91 }
92 }
93 // The search does not know the number of back edges in advance; shrinking copies the lists
94 // to their exact length, as Java trims them.
95 for list in [&mut sources, &mut targets, &mut edge_indices] {
96 list.shrink_to_fit();
97 }
98 Edges::wrap(sources, targets, edge_indices)
99}