graphity_core/components.rs
1//! The algorithms for the components of a graph, and for the edges and nodes whose removal splits
2//! them - Java's class `Components`.
3//!
4//! [`sccs_of`] returns the SCCs (strongly connected components), and [`wccs_of`] the weakly connected
5//! components. [`ccs_of`] returns the weakly connected components under another name: the connected
6//! components of the graph read as undirected. [`biconnectivity_of`] returns the bridges, articulation
7//! points and biconnected components. Bridges and articulation points are the edges and nodes whose
8//! removal splits a connected component. [`strong_connectivity_of`] returns the strong bridges and
9//! strong articulation points, which split an SCC.
10//!
11//! ```
12//! use graphity_core::{components, BiAdjacentGraph, GraphBuilder};
13//!
14//! let mut b = GraphBuilder::new();
15//! b.add_nodes(4);
16//! b.add_edge_pairs(&[0, 1, 1, 0, 1, 2, 2, 3]);
17//! let graph = b.build();
18//!
19//! let sccs = components::sccs_of(&graph);
20//! assert_eq!(sccs.scc_count(), 3);
21//! assert_eq!(components::wccs_of(&graph).group_count(), 1);
22//! let biconnectivity = components::biconnectivity_of(&BiAdjacentGraph::of(&graph));
23//! assert_eq!(biconnectivity.articulation_points(), [1, 2]);
24//! ```
25//!
26//! A graph is always directed, and each function says how it reads the edges. [`sccs_of`] and
27//! [`strong_connectivity_of`] follow them in their direction. [`wccs_of`], [`ccs_of`] and
28//! [`biconnectivity_of`] read the graph as undirected: an edge connects its source and target whether
29//! or not the reverse edge exists, and the edges `a -> b` and `b -> a` count as one undirected edge,
30//! not two. An undirected graph can therefore be stored with one edge per pair of neighbors or with
31//! both directions, and these functions read it the same way. For the bridges this matters: read as
32//! two edges, the two directions would form a cycle, and no edge stored in both directions could be a
33//! bridge.
34
35use crate::{
36 BiAdjacentGraph, Biconnectivity, Graph, NodePartition, Sccs, StrongConnectivity, parent_forest,
37 union_find,
38};
39
40/// Returns the SCCs of `graph`. Uses
41/// [Tarjan's algorithm](https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm),
42/// without recursion.
43///
44/// Every node is in exactly one SCC; a node that lies on no cycle is an SCC of its own. SCC IDs are in
45/// reverse topological order: every edge between two SCCs goes from the higher SCC ID to the lower
46/// one, so SCC 0 has no edges to other SCCs. The nodes of each SCC are in ascending order. Here,
47/// `dependencies` are the dependencies between the packages of a program, and `names` holds the names
48/// of the packages. The example groups the packages by SCC, in the order of the SCC IDs. In this
49/// order, each package comes after the packages it uses, and the packages that use each other come
50/// together:
51///
52/// <!-- example: connectivity.rs#sccsOf -->
53/// ```
54/// # use graphity_core::components;
55/// # let dependencies = graphity_core::Graph::of(
56/// # &[0, 3, 4, 7, 9, 10, 13, 14, 14],
57/// # &[1, 2, 3, 7, 3, 4, 7, 4, 5, 5, 4, 6, 7, 7],
58/// # ).unwrap();
59/// # let names = ["app", "cli", "ui", "service", "model", "storage", "json", "util"];
60/// // The SCCs in reverse topological order, each as the names of its packages.
61/// let sccs = components::sccs_of(&dependencies);
62/// let build_order: Vec<Vec<&str>> = (0..sccs.scc_count())
63/// .map(|scc| {
64/// sccs.nodes_of(scc)
65/// .iter()
66/// .map(|&node| names[node as usize])
67/// .collect()
68/// })
69/// .collect();
70/// // build_order: [["util"], ["cli"], ["json"], ["model", "storage"], ["service"],
71/// // ["ui"], ["app"]]
72/// # assert_eq!(build_order[3], ["model", "storage"]);
73/// # assert_eq!(build_order.concat()[..3], ["util", "cli", "json"]);
74/// ```
75///
76/// **Time:** O(node_count + edge_count), plus sorting the nodes of each SCC: up to
77/// O(node_count log node_count) when one SCC holds most of the nodes.
78/// **Memory:** up to 12 x node_count bytes for the result; while it runs, 24 x node_count bytes
79/// more.
80///
81/// # Panics
82/// With an `invalid argument` message if `graph` has more than `2^30 - 5` nodes.
83pub fn sccs_of(graph: &Graph) -> Sccs {
84 Sccs::of(graph)
85}
86
87/// Returns the weakly connected components of `graph`. These are the components of the graph read as
88/// undirected.
89///
90/// Every node is in exactly one component. Each component is a group of the result. The groups are in
91/// the order of their smallest nodes: group 0 holds node 0, group 1 the smallest node not in group 0,
92/// and so on. Uses [union-find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure), whose cost
93/// grows with alpha(node_count). The inverse Ackermann function alpha is below 5 for any graph.
94///
95/// **Time:** O((node_count + edge_count) x alpha(node_count)).
96/// **Memory:** up to 12 x node_count bytes for the result; while it runs, 9 x node_count bytes more.
97pub fn wccs_of(graph: &Graph) -> NodePartition {
98 let n = graph.node_count() as usize;
99
100 // 1) Union the endpoints of every edge; self-loops are no-ops.
101 let mut parent = union_find::singletons(n);
102 let mut rank = vec![0u8; n];
103 let adjacency = graph.out_adjacency();
104 let adjacency_start = graph.out_adjacency_start();
105 for u in 0..n {
106 for &v in &adjacency[adjacency_start[u] as usize..adjacency_start[u + 1] as usize] {
107 union_find::union(&mut parent, &mut rank, u as u32, v);
108 }
109 }
110
111 // 2) Dense component IDs, in order of each component's smallest node.
112 let mut node_to_group = vec![0u32; n];
113 let mut group_of_root = vec![crate::NONE; n];
114 let mut group_count = 0u32;
115 for (i, slot) in node_to_group.iter_mut().enumerate() {
116 let root = union_find::find(&mut parent, i as u32) as usize;
117 if group_of_root[root] == crate::NONE {
118 group_of_root[root] = group_count;
119 group_count += 1;
120 }
121 *slot = group_of_root[root];
122 }
123
124 // 3) Members as CSR.
125 let groups = parent_forest::group_indices(&node_to_group, group_count);
126 NodePartition::from_parts(graph, node_to_group, groups.members, groups.start)
127}
128
129/// Returns the connected components of `graph` read as undirected. Equivalent to
130/// [`wccs_of(graph)`](wccs_of).
131///
132/// The two names let a call say which reading of the graph it means.
133///
134/// **Time:** O((node_count + edge_count) x alpha(node_count)), as for [`wccs_of`].
135/// **Memory:** up to 12 x node_count bytes for the result; while it runs, 9 x node_count bytes more.
136pub fn ccs_of(graph: &Graph) -> NodePartition {
137 wccs_of(graph)
138}
139
140/// Returns the bridges, articulation points and biconnected components of `graph`, read as
141/// undirected.
142///
143/// All three come from one depth-first search, so there is no cheaper function for one of them alone;
144/// [`Biconnectivity`] describes them. The search follows the edges of every node in both directions,
145/// so it takes a [`BiAdjacentGraph`]. For a plain [`Graph`], call
146/// `components::biconnectivity_of(&BiAdjacentGraph::of(&graph))`. Uses
147/// [the algorithm of Hopcroft and Tarjan](https://en.wikipedia.org/wiki/Biconnected_component),
148/// without recursion.
149///
150/// **Time:** O(node_count + edge_count).
151/// **Memory:** up to 8 x edge_count + 20 x node_count bytes for the result; while it runs,
152/// 8 x edge_count + 63 x node_count bytes more.
153pub fn biconnectivity_of(graph: &BiAdjacentGraph) -> Biconnectivity {
154 Biconnectivity::of(graph)
155}
156
157/// Returns the strong bridges and strong articulation points of `graph`. These are the edges and nodes
158/// whose removal splits an SCC.
159///
160/// The edges are followed in their direction, as by [`sccs_of`]; [`StrongConnectivity`] describes the
161/// results. The computation also follows them against their direction, so it takes a
162/// [`BiAdjacentGraph`]. For a plain [`Graph`], call
163/// `components::strong_connectivity_of(&BiAdjacentGraph::of(&graph))`. Uses the algorithm of Italiano,
164/// Laura and Santaroni, which finds both from the [dominators](crate::Dominators) within each SCC,
165/// without recursion.
166///
167/// **Time:** O((node_count + edge_count) log node_count).
168/// **Memory:** up to 28 x node_count bytes for the result; while it runs, about 80 x node_count
169/// bytes more.
170///
171/// # Panics
172/// With an `invalid argument` message if `graph` has more than `2^30 - 6` nodes.
173pub fn strong_connectivity_of(graph: &BiAdjacentGraph) -> StrongConnectivity {
174 StrongConnectivity::of(graph)
175}