graphity_core/graphs.rs
1//! Operations on graphs, in five families: derived graphs, edge mappings, node sets, shape checks,
2//! and a graph as text, hash or diff - Java's class `Graphs`, with every operation under its Java
3//! name in snake case.
4//!
5//! - **Derived graphs:** [`remapped`] renumbers the nodes of a graph by a [`NodeMapping`], which also
6//! selects subgraphs; [`transitive_closure`] and [`transitive_reduction`] add and drop the edges
7//! that other paths imply; [`dominator_tree`] turns [`Dominators`] into a graph.
8//! - **Edge mappings:** [`edge_mapping`], [`transposed_edge_mapping`] and [`edge_partition`] relate
9//! the edges of a remapped, transposed or condensed graph to the edges of the graph it came from.
10//! - **Node sets:** [`root_nodes`] and [`reachable_from_sources`].
11//! - **Shape checks:** [`is_dag`], [`is_forest`], [`is_tree`], [`is_path`] and
12//! [`is_strongly_connected`] read the graph as directed, and [`find_cycle`] returns a cycle that
13//! makes a graph no DAG (directed acyclic graph); [`is_undirected_forest`], [`is_undirected_tree`],
14//! [`is_bipartite`] and [`is_weakly_connected`] read it as undirected.
15//! - **Text, hash and diff:** [`adjacency_list_of`] writes a whole graph as text, [`topology_hash`]
16//! hashes it into 64 bits to keep, and [`diff`] returns the edges added and removed between two
17//! versions of a graph.
18//!
19//! ```
20//! use graphity_core::{graphs, GraphBuilder, NodeMapping};
21//!
22//! let mut b = GraphBuilder::new();
23//! b.add_nodes(4);
24//! b.add_edge_pairs(&[0, 1, 0, 2, 1, 3]);
25//! let graph = b.build();
26//!
27//! assert!(graphs::is_dag(&graph));
28//! assert!(graphs::is_tree(&graph));
29//! assert!(!graphs::is_path(&graph));
30//! assert!(graphs::is_bipartite(&graph));
31//!
32//! let reached = graphs::reachable_from(&graph, 1);
33//! let sub = graphs::remapped(&graph, &NodeMapping::for_subgraph_sorted(&reached).unwrap());
34//! assert_eq!(graphs::adjacency_list_of(&sub), "0 -> [1]\n1 -> []\n");
35//! ```
36//!
37//! Data on nodes and edges follows a renumbered, transposed or condensed graph through the mappings.
38//! Like the node mappings that the factories of [`NodeMapping`] make, the edge mappings point from new
39//! to old: from the derived graph to the original one. Their `gather` functions carry an array of data
40//! over to the derived graph. An [`EdgePartition`] groups the edges of the original by the condensed
41//! edge they became, and its `reduce` functions combine their data.
42//!
43//! A shape check without a prefix reads the graph as directed. One prefixed `undirected` reads it as
44//! undirected, as [`components::ccs_of`](crate::components::ccs_of) does: each edge connects its
45//! source and target both ways, and the edges `a -> b` and `b -> a` count as one. [`is_bipartite`] and
46//! [`is_weakly_connected`] read it so too, without the prefix, because neither property has a directed
47//! reading. The checks of the undirected reading use
48//! [union-find](https://en.wikipedia.org/wiki/Disjoint-set_data_structure), whose cost grows with
49//! alpha(node_count). The inverse Ackermann function alpha is below 5 for any graph. No shape check
50//! needs memory in proportion to the edge count.
51//!
52//! Every result is computed anew on every call, not cached, and shares no array with the arguments:
53//! keep a result to use it more than once. No function recurses, so deep graphs do not overflow the
54//! call stack.
55
56use std::fmt::Write as _;
57
58use crate::array_limits::{MAX_ARRAY_LENGTH, MAX_NODE_COUNT_TWO_INTS, check_node_count};
59use crate::error::{index_out_of_bounds, invalid_argument};
60use crate::mapping::count_valid;
61use crate::sorted_int_view::{contains_in_range, index_of_in_range};
62use crate::union_find;
63use crate::{
64 BiAdjacentGraph, Dominators, EdgeMapping, EdgePartition, Edges, Graph, GraphDiff, GraphError,
65 NONE, NodeMapping, NodePartition, Sccs, SortedIntView, dfs_frames, growth, parent_forest,
66 top_order,
67};
68
69// The constants of topology_hash. Changing one of them, or a shift or rotation distance in the
70// code, changes the hash of every graph, which a release must announce in its changelog; every
71// Graphity implementation computes the same hash.
72
73/// Seed: the fractional part of the square root of 2, scaled to 64 bits and rounded.
74const HASH_SEED: u64 = 0x6A09E667F3BCC909;
75/// Spreads each input over all 64 bits: 2^64 / golden ratio, rounded down.
76const HASH_GOLDEN_GAMMA: u64 = 0x9E3779B97F4A7C15;
77/// Multiplier of each step: PRIME64_2 of xxHash64.
78const HASH_STEP_PRIME: u64 = 0xC2B2AE3D27D4EB4F;
79/// The two multipliers of the SplitMix64 finalizer, as in Java's `SplittableRandom`.
80const SPLITMIX64_MULTIPLIER_1: u64 = 0xBF58476D1CE4E5B9;
81const SPLITMIX64_MULTIPLIER_2: u64 = 0x94D049BB133111EB;
82
83/// Characters the [`adjacency_list_of`] builder reserves per node: a line without its targets,
84/// `"1234567 -> []\n"`, and some slack. An estimate for the initial capacity; the string grows
85/// past it if needed.
86const LIST_CHARS_PER_NODE: u64 = 16;
87
88/// Characters the same builder reserves per target, `", 123456"`.
89const LIST_CHARS_PER_EDGE: u64 = 8;
90
91const VISITED: u32 = 0b01;
92const ON_STACK: u32 = 0b10;
93
94/// Returns `graph` with its nodes renumbered by `new_to_old`: node `i` of the result is node
95/// `new_to_old.get(i)` of `graph`.
96///
97/// The result has the edges of `graph` between the nodes that `new_to_old` maps to; the other nodes
98/// are left out, with their edges. The factories of [`NodeMapping`] make the mapping:
99/// [`for_subgraph`](NodeMapping::for_subgraph) and its variants select nodes,
100/// [`for_permutation`](NodeMapping::for_permutation) and [`reindex`](NodeMapping::reindex) reorder all
101/// of them. Data on the nodes follows with the `gather` functions of the mapping, data on the edges
102/// with [`edge_mapping`]. Here, `calls` holds the calls between the methods of a program, and the
103/// methods that `load` reaches become a graph of their own, with their names from `names`:
104///
105/// <!-- example: mappings.rs#subgraph -->
106/// ```
107/// # use graphity_core::{NodeMapping, graphs};
108/// # let calls = graphity_core::Graph::of(
109/// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
110/// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
111/// # ).unwrap();
112/// # let names: &[&str] = &[
113/// # "main", "parseArgs", "run", "load", "save", "show", "parse", "format", "read", "write",
114/// # ];
115/// # let load = 3;
116/// let new_to_old =
117/// NodeMapping::for_subgraph_sorted(&graphs::reachable_from(&calls, load))?;
118/// let loading = graphs::remapped(&calls, &new_to_old);
119/// let loading_names = new_to_old.gather(names);
120/// // loading_names: ["load", "parse", "read"]
121/// // loading: load -> parse, load -> read, parse -> parse
122/// # assert_eq!(loading_names, ["load", "parse", "read"]);
123/// # assert_eq!(graphs::adjacency_list_of(&loading), "0 -> [1, 2]\n1 -> [1]\n2 -> []\n");
124/// # Ok::<(), graphity_core::GraphError>(())
125/// ```
126///
127/// To merge nodes into groups instead, use [`NodePartition::condense`].
128///
129/// **Time:** O(node_count + edge_count log max_out_degree).
130/// **Memory:** 4 bytes per node and per edge for the result; while it runs, 4 x node_count bytes
131/// more.
132///
133/// # Panics
134/// With an `invalid argument` message if a node of the result is not mapped, or two map to the same
135/// node; with an `index out of bounds` message if a node of the result maps to an ID that is not a
136/// node of `graph`.
137#[track_caller]
138pub fn remapped(graph: &Graph, new_to_old: &NodeMapping) -> Graph {
139 let new_node_count = new_to_old.index_count() as usize;
140 // The general path gives the same, but allocates the inverse over every old node first.
141 if new_node_count == 0 {
142 return Graph::empty();
143 }
144 // Inverse (old to new) for edge-target translation, built in the same pass that checks every
145 // new node. Not NodeMapping::inverted: remapped rejects an unmapped new node, which an inverse
146 // skips, and names both new nodes of a repeat.
147 let old_of = new_to_old.as_array();
148 let old_node_count = graph.node_count() as usize;
149 let mut new_of = vec![NONE; old_node_count];
150 for (new_node, &old_node) in old_of.iter().enumerate() {
151 if old_node == NONE {
152 invalid_argument!("new node {new_node} is unmapped");
153 }
154 if old_node as usize >= old_node_count {
155 not_a_node(new_node as u32, old_node, old_node_count as u32);
156 }
157 if new_of[old_node as usize] != NONE {
158 invalid_argument!(
159 "new nodes {} and {new_node} both map to node {old_node}",
160 new_of[old_node as usize]
161 );
162 }
163 new_of[old_node as usize] = new_node as u32;
164 }
165
166 let old_targets = graph.out_adjacency();
167 let old_start = graph.out_adjacency_start();
168 // The checks above make the mapping injective into the old nodes, so equal counts make it a
169 // bijection: no edge is dropped, and the degree count becomes offset arithmetic.
170 let total = new_node_count == old_node_count;
171
172 // 1) Out-degree of every new node
173 let mut new_start = vec![0u32; new_node_count + 1];
174 for (new_node, &old_node) in old_of.iter().enumerate() {
175 let (from, to) = (
176 old_start[old_node as usize] as usize,
177 old_start[old_node as usize + 1] as usize,
178 );
179 new_start[new_node + 1] = if total {
180 (to - from) as u32
181 } else {
182 old_targets[from..to]
183 .iter()
184 .filter(|&&t| new_of[t as usize] != NONE)
185 .count() as u32
186 };
187 }
188 // 2) Prefix sum: degrees to start offsets
189 for v in 0..new_node_count {
190 new_start[v + 1] += new_start[v];
191 }
192
193 // 3) Targets, each list sorted
194 let mut new_targets = vec![0u32; new_start[new_node_count] as usize];
195 for (new_node, &old_node) in old_of.iter().enumerate() {
196 let mut write = new_start[new_node] as usize;
197 for &old_target in &old_targets
198 [old_start[old_node as usize] as usize..old_start[old_node as usize + 1] as usize]
199 {
200 let mapped = new_of[old_target as usize];
201 if mapped != NONE {
202 new_targets[write] = mapped;
203 write += 1;
204 }
205 }
206 new_targets[new_start[new_node] as usize..write].sort_unstable();
207 }
208 Graph::from_csr_unchecked(new_start, new_targets)
209}
210
211#[track_caller]
212fn not_a_node(new_node: u32, old_node: u32, old_node_count: u32) -> ! {
213 index_out_of_bounds!(
214 "new node {new_node} maps to {old_node}, which is not a node of the old graph \
215 (node_count={old_node_count})"
216 )
217}
218
219/// Returns the dominator tree of `dominators` as a graph, with an edge `d -> n` for every node `n`
220/// whose immediate dominator is `d`.
221///
222/// The result has the node IDs of the analyzed graph, and its edges point away from the roots of the
223/// tree, for a walk down the tree such as with a [`DfsTraverser`](crate::DfsTraverser). Its root
224/// nodes are the entries, the nodes that only the virtual root above several entries dominates, and
225/// the unreachable nodes. To ask whether one node dominates another, use
226/// [`Ancestry::of_dominators`](crate::Ancestry::of_dominators), which shares the immediate dominators
227/// instead of building this graph.
228///
229/// **Time:** O(node_count).
230/// **Memory:** 4 bytes per node and per edge for the result.
231pub fn dominator_tree(dominators: &Dominators) -> Graph {
232 let children = parent_forest::children_of(&dominators.immediate_dominator);
233 Graph::from_csr_unchecked(children.start, children.members)
234}
235
236/// Returns the transitive closure of `graph`: the same nodes, with an edge `u -> v` wherever a path
237/// of one or more edges leads from `u` to `v`.
238///
239/// A node has a self-loop in the result if and only if it lies on a cycle. The result can have up to
240/// node_count² edges; for the nodes reachable from a few nodes, [`reachable_from_sources`] costs far
241/// less.
242///
243/// The closure is computed on the SCCs (strongly connected components) of `graph`, with a row of bits
244/// per SCC for the SCCs it reaches. The rows take scc_count² / 8 bytes, about 1.25 GB for 100 000
245/// SCCs.
246///
247/// **Time:** O(node_count + edge_count + scc_count x (scc_count + edge_count) / 64 +
248/// result_edge_count log node_count), with scc_count the number of SCCs.
249/// **Memory:** 4 bytes per node and per edge for the result; while it runs, scc_count² / 8 bytes for
250/// the rows, which are held together with the result at the peak, and O(node_count + edge_count)
251/// more.
252///
253/// # Panics
254/// With an `invalid argument` message if the closure has more edges than a graph can have, or `graph`
255/// has more than `2^30 - 5` nodes.
256#[track_caller]
257pub fn transitive_closure(graph: &Graph) -> Graph {
258 let n = graph.node_count() as usize;
259 let sccs = Sccs::of(graph);
260 let k = sccs.scc_count() as usize;
261 let dag = sccs.condense();
262 let dag_start = dag.out_adjacency_start();
263 let dag_targets = dag.out_adjacency();
264 let words = k.div_ceil(64);
265
266 // SCC IDs are in reverse topological order: every successor of c has a smaller ID.
267 let mut reach: Vec<Vec<u64>> = Vec::with_capacity(k);
268 let mut reach_size = vec![0u32; k];
269 let mut total = 0u64;
270 for c in 0..k {
271 let mut row = vec![0u64; words];
272 if sccs.contains_cycle(c as u32) {
273 row[c >> 6] |= 1 << (c & 63);
274 }
275 for &d in &dag_targets[dag_start[c] as usize..dag_start[c + 1] as usize] {
276 let d = d as usize;
277 row[d >> 6] |= 1 << (d & 63);
278 for (w, &below) in row.iter_mut().zip(&reach[d]) {
279 *w |= below;
280 }
281 }
282 let mut size = 0u64;
283 for (w, &word) in row.iter().enumerate() {
284 let mut bits = word;
285 while bits != 0 {
286 size += u64::from(sccs.size_of(((w << 6) + bits.trailing_zeros() as usize) as u32));
287 bits &= bits - 1;
288 }
289 }
290 reach_size[c] = size as u32;
291 total += size * u64::from(sccs.size_of(c as u32));
292 if total > u64::from(MAX_ARRAY_LENGTH) {
293 invalid_argument!(
294 "the transitive closure has more than {MAX_ARRAY_LENGTH} edges, the largest array \
295 length"
296 );
297 }
298 reach.push(row);
299 }
300
301 // Each component's sorted target list is written once, at its first node, and copied from
302 // there to its other nodes; its bit row is dropped as soon as the list exists.
303 let mut start = vec![0u32; n + 1];
304 for v in 0..n {
305 start[v + 1] = start[v] + reach_size[sccs.scc_of(v as u32) as usize];
306 }
307 let mut targets = vec![0u32; total as usize];
308 for (c, slot) in reach.iter_mut().enumerate() {
309 let row = std::mem::take(slot);
310 let nodes = sccs.nodes_of(c as u32);
311 let first = start[nodes[0] as usize] as usize;
312 let mut at = first;
313 for (w, &word) in row.iter().enumerate() {
314 let mut bits = word;
315 while bits != 0 {
316 let members = sccs.nodes_of(((w << 6) + bits.trailing_zeros() as usize) as u32);
317 targets[at..at + members.len()].copy_from_slice(&members);
318 at += members.len();
319 bits &= bits - 1;
320 }
321 }
322 targets[first..at].sort_unstable();
323 for &node in &nodes[1..] {
324 let to = start[node as usize] as usize;
325 targets.copy_within(first..at, to);
326 }
327 }
328 Graph::from_csr_unchecked(start, targets)
329}
330
331/// Returns the transitive reduction of `dag`: the same nodes, keeping each edge `u -> v` unless
332/// another path leads from `u` to `v`.
333///
334/// From each node, the result reaches the same nodes as `dag`, with as few edges as possible; on a
335/// DAG, this result is unique. For a graph with cycles, reduce the DAG of its SCCs, which is
336/// `components::sccs_of(&graph).condense()`.
337///
338/// The reduction is computed with a row of bits per node for the nodes it reaches. The rows take
339/// node_count² / 8 bytes, about 1.25 GB for 100 000 nodes.
340///
341/// **Time:** O(node_count + edge_count log max_out_degree + (node_count + edge_count) x node_count /
342/// 64).
343/// **Memory:** 4 bytes per node and per edge for the result; while it runs, node_count² / 8 bytes for
344/// the rows and O(node_count + edge_count) more.
345///
346/// # Errors
347/// An [`InvalidArgument`](crate::ErrorKind::InvalidArgument) error if `dag` has a cycle, a self-loop
348/// included.
349///
350/// # Panics
351/// With an `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
352pub fn transitive_reduction(dag: &Graph) -> Result<Graph, GraphError> {
353 let n = dag.node_count() as usize;
354 let order = top_order::of(dag)?;
355 let mut position = vec![0u32; n];
356 for (i, &v) in order.iter().enumerate() {
357 position[v as usize] = i as u32;
358 }
359 let start = dag.out_adjacency_start();
360 let targets = dag.out_adjacency();
361 let words = n.div_ceil(64);
362 let mut reach: Vec<Vec<u64>> = vec![Vec::new(); n];
363 let mut keep = vec![false; targets.len()];
364 let mut kept = 0usize;
365 let mut by_position: Vec<u64> = Vec::with_capacity(16);
366
367 for &u in order.iter().rev() {
368 let u = u as usize;
369 let from = start[u] as usize;
370 let degree = start[u + 1] as usize - from;
371 // Sort key: topological position of the target high, edge index low.
372 by_position.clear();
373 by_position.extend(
374 (from..from + degree)
375 .map(|e| (u64::from(position[targets[e] as usize]) << 32) | e as u64),
376 );
377 by_position.sort_unstable();
378 let mut row = vec![0u64; words];
379 for &key in &by_position {
380 let e = key as u32 as usize;
381 let v = targets[e] as usize;
382 if row[v >> 6] & (1 << (v & 63)) != 0 {
383 continue;
384 }
385 keep[e] = true;
386 kept += 1;
387 row[v >> 6] |= 1 << (v & 63);
388 for (w, &below) in row.iter_mut().zip(&reach[v]) {
389 *w |= below;
390 }
391 }
392 reach[u] = row;
393 }
394
395 let mut result_start = vec![0u32; n + 1];
396 let mut result_targets = Vec::with_capacity(kept);
397 for v in 0..n {
398 result_start[v] = result_targets.len() as u32;
399 for e in start[v] as usize..start[v + 1] as usize {
400 if keep[e] {
401 result_targets.push(targets[e]);
402 }
403 }
404 }
405 result_start[n] = result_targets.len() as u32;
406 Ok(Graph::from_csr_unchecked(result_start, result_targets))
407}
408
409/// Returns the edge mapping from `new_graph` to `old_graph` that goes with the node mapping
410/// `new_to_old`.
411///
412/// Edge `s -> t` of `new_graph` maps to the edge `new_to_old.get(s) -> new_to_old.get(t)` of
413/// `old_graph`, or to `None` if `old_graph` has no such edge or `s` or `t` maps to `None`. For a graph
414/// from [`remapped(old_graph, new_to_old)`](remapped), every edge has its counterpart, and the
415/// `gather` functions of the result carry data on the edges over to the new graph. Here, `site_count`
416/// holds the number of call sites of each call by edge index of `calls`, and the subgraph `loading`
417/// from the example at [`remapped`] takes these counts along:
418///
419/// <!-- example: mappings.rs#edgeMapping -->
420/// ```
421/// # use graphity_core::graphs;
422/// # let calls = graphity_core::Graph::of(
423/// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
424/// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
425/// # ).unwrap();
426/// # let site_count = [1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1];
427/// # let new_to_old = graphity_core::NodeMapping::for_subgraph(&[3, 6, 8]).unwrap();
428/// # let loading = graphity_core::graphs::remapped(&calls, &new_to_old);
429/// let loading_site_count =
430/// graphs::edge_mapping(&loading, &calls, &new_to_old).gather(&site_count);
431/// // 1 for load -> parse and for load -> read, 2 for parse -> parse
432/// # assert_eq!(loading_site_count, [1, 1, 2]);
433/// ```
434///
435/// For the opposite direction, from the edges of `old_graph` to those of `new_graph`, invert the
436/// result with [`EdgeMapping::inverted`]. The transposed graph needs [`transposed_edge_mapping`]
437/// instead, as its edges run the other way.
438///
439/// **Time:** O(node_count + edge_count log max_out_degree), with the node and edge count of
440/// `new_graph` and the out-degrees of `old_graph`.
441/// **Memory:** 4 bytes per edge of `new_graph` for the result.
442///
443/// # Panics
444/// With an `invalid argument` message if `new_to_old.index_count() != new_graph.node_count()`; with an
445/// `index out of bounds` message if a node of `new_graph` maps to an ID that is not a node of
446/// `old_graph`.
447#[track_caller]
448pub fn edge_mapping(new_graph: &Graph, old_graph: &Graph, new_to_old: &NodeMapping) -> EdgeMapping {
449 let new_node_count = new_graph.node_count();
450 if new_to_old.index_count() != new_node_count {
451 invalid_argument!(
452 "new_to_old has an index count of {}, but new_graph has {new_node_count} nodes",
453 new_to_old.index_count()
454 );
455 }
456 let old_of = new_to_old.as_array();
457 let old_node_count = old_graph.node_count();
458 let new_targets = new_graph.out_adjacency();
459 let new_start = new_graph.out_adjacency_start();
460 let old_targets = old_graph.out_adjacency();
461 let old_start = old_graph.out_adjacency_start();
462 let mut mapping = vec![NONE; new_targets.len()];
463
464 // Every entry is checked in its own node's iteration before the result is returned, so a
465 // target needs no check: one that is unmapped or beyond the old graph is simply not found.
466 for new_node in 0..new_node_count as usize {
467 let old_node = old_of[new_node];
468 let (new_from, new_end) = (
469 new_start[new_node] as usize,
470 new_start[new_node + 1] as usize,
471 );
472 if old_node == NONE {
473 continue;
474 }
475 if old_node >= old_node_count {
476 not_a_node(new_node as u32, old_node, old_node_count);
477 }
478 let old_from = old_start[old_node as usize] as usize;
479 let old_end = old_start[old_node as usize + 1] as usize;
480 for i in new_from..new_end {
481 let old_target = old_of[new_targets[i] as usize];
482 if old_target != NONE {
483 mapping[i] =
484 index_of_in_range(old_targets, old_from, old_end, old_target).unwrap_or(NONE);
485 }
486 }
487 }
488 let valid = count_valid(&mapping);
489 EdgeMapping::new(mapping, valid)
490}
491
492/// Returns the edge mapping from the transposed graph of `graph` to `graph`.
493///
494/// Edge `e` of `BiAdjacentGraph::of(&graph).transposed()` maps to the edge of `graph` it reverses: the
495/// transposed graph keeps the node IDs, but not the edge indices. The mapping is total, and its
496/// `gather` functions carry data on the edges over to the transposed graph. Here, `site_count` holds
497/// the number of call sites of each call by edge index of `calls`, and the counts follow the calls
498/// to the transposed graph, which lists the callers of `parse`:
499///
500/// <!-- example: mappings.rs#transposedEdges -->
501/// ```
502/// # use std::io::Write;
503/// # use graphity_core::{BiAdjacentGraph, graphs};
504/// # let calls = graphity_core::Graph::of(
505/// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
506/// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
507/// # ).unwrap();
508/// # let names: &[&str] = &[
509/// # "main", "parseArgs", "run", "load", "save", "show", "parse", "format", "read", "write",
510/// # ];
511/// # let site_count = [1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1];
512/// # let parse = 6;
513/// # let mut out = Vec::new();
514/// let called_by = BiAdjacentGraph::of(&calls).transposed();
515/// let called_by_site_count =
516/// graphs::transposed_edge_mapping(&calls).gather(&site_count);
517/// for edge in called_by.out_edge_start(parse)..called_by.out_edge_end(parse) {
518/// writeln!(
519/// out,
520/// "{}: {}",
521/// names[called_by.edge_target(edge) as usize],
522/// called_by_site_count[edge as usize]
523/// )?;
524/// }
525/// // load: 1
526/// // parse: 2
527/// # assert_eq!(String::from_utf8(out).unwrap(), "load: 1\nparse: 2\n");
528/// # Ok::<(), std::io::Error>(())
529/// ```
530///
531/// [`BiAdjacentGraph::transposed_edge_index`] translates a single edge, in the opposite direction.
532///
533/// **Time:** O(node_count + edge_count).
534/// **Memory:** 4 x edge_count bytes for the result; while it runs, 4 x node_count bytes more.
535pub fn transposed_edge_mapping(graph: &Graph) -> EdgeMapping {
536 EdgeMapping::for_transposed(graph)
537}
538
539/// Returns the edge partition that goes with the node partition `partition`, from the edges of the
540/// partitioned graph to the edges of `condensed_graph`.
541///
542/// The edges from group `g` to group `h` all map to the condensed edge `g -> h`, which is edge
543/// `condensed_graph.edge_index_of(g, h)`. [`EdgePartition::edges_of`] lists them, and the `reduce`
544/// functions of the result combine their data. An edge inside a group, or from or to a node in no
545/// group, maps to `None`. Here, `by_package` groups the methods of a program by package. Its condensed
546/// graph `package_calls` holds the calls between packages (see [`NodePartition::of`]).
547/// `by_package_call` tells which calls between methods are behind the call from `service` to `model`:
548///
549/// <!-- example: partitions.rs#edgesOf -->
550/// ```
551/// # use graphity_core::graphs;
552/// # let calls = graphity_core::Graph::of(
553/// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
554/// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
555/// # ).unwrap();
556/// # let package_of = [0, 1, 0, 3, 3, 2, 4, 4, 5, 5];
557/// # let by_package = graphity_core::NodePartition::of(&calls, &package_of, 8).unwrap();
558/// # let package_calls = by_package.condense();
559/// # let (service, model) = (3, 4);
560/// let by_package_call = graphs::edge_partition(&package_calls, &by_package);
561/// let service_to_model = package_calls.edge_index_of(service, model).unwrap();
562/// let behind = by_package_call.edges_of(service_to_model);
563/// // behind: [5, 7] - the calls load -> parse and save -> format
564/// # assert_eq!(behind, [5, 7]);
565/// ```
566///
567/// `condensed_graph` must be `partition.condense()`; only its node count is checked.
568///
569/// **Time:** O(node_count + edge_count log max_out_degree), with the node and edge count of the
570/// partitioned graph and the out-degrees of `condensed_graph`.
571/// **Memory:** up to 12 bytes per edge of the partitioned graph for the result.
572///
573/// # Panics
574/// With an `invalid argument` message if `condensed_graph.node_count()` is not
575/// `partition.group_count()`.
576#[track_caller]
577pub fn edge_partition(condensed_graph: &Graph, partition: &NodePartition) -> EdgePartition {
578 let group_count = partition.group_count();
579 if condensed_graph.node_count() != group_count {
580 invalid_argument!(
581 "condensed_graph has {} nodes, but the partition has {group_count} groups",
582 condensed_graph.node_count()
583 );
584 }
585 let graph = partition.graph();
586 let group_of = partition.group_array();
587 let targets = graph.out_adjacency();
588 let start = graph.out_adjacency_start();
589 let condensed_targets = condensed_graph.out_adjacency();
590 let condensed_start = condensed_graph.out_adjacency_start();
591 let mut mapping = vec![NONE; targets.len()];
592
593 // 1) The condensed edge of every edge between groups.
594 for node in 0..graph.node_count() as usize {
595 let source_group = group_of[node];
596 if source_group == NONE {
597 continue;
598 }
599 for ei in start[node] as usize..start[node + 1] as usize {
600 let target_group = group_of[targets[ei] as usize];
601 if source_group != target_group && target_group != NONE {
602 mapping[ei] = index_of_in_range(
603 condensed_targets,
604 condensed_start[source_group as usize] as usize,
605 condensed_start[source_group as usize + 1] as usize,
606 target_group,
607 )
608 .unwrap_or(NONE);
609 }
610 }
611 }
612 // 2) The original edges of each condensed edge, as CSR.
613 let groups = parent_forest::group_indices(&mapping, condensed_graph.edge_count());
614 EdgePartition::new(mapping, groups.members, groups.start)
615}
616
617/// Returns the root nodes of `graph` in ascending order. A root node has in-degree 0.
618///
619/// A traversal of a DAG or a forest starts from them, as in
620/// `traverser.run_from_nodes(&graphs::root_nodes(&graph), &mut hooks)` with a
621/// [`DfsTraverser`](crate::DfsTraverser). [`BiAdjacentGraph::is_root_node`] checks a single node in
622/// O(1).
623///
624/// **Time:** O(node_count).
625/// **Memory:** 4 bytes per root node for the result.
626pub fn root_nodes(graph: &BiAdjacentGraph) -> SortedIntView<'static> {
627 let in_start = graph.in_adjacency_start();
628 let is_root = |v: &u32| in_start[*v as usize] == in_start[*v as usize + 1];
629 // Counted first, as in Java, so that the result has exactly its length.
630 let mut roots = Vec::with_capacity(graph.nodes().filter(is_root).count());
631 roots.extend(graph.nodes().filter(is_root));
632 SortedIntView::owned(roots)
633}
634
635/// Returns the nodes reachable from `source`, in ascending order and with `source` included.
636/// Equivalent to [`reachable_from_sources(graph, &[source])`](reachable_from_sources) - Java's
637/// overload `reachableFrom(Graph, int)`.
638///
639/// **Time:** O(node_count + edge_count).
640/// **Memory:** as for [`reachable_from_sources`].
641///
642/// # Panics
643/// With an `index out of bounds` message if `source` is not in `0..node_count`.
644#[track_caller]
645pub fn reachable_from(graph: &Graph, source: u32) -> SortedIntView<'static> {
646 reachable_from_sources(graph, &[source])
647}
648
649/// Returns the nodes reachable from at least one of `sources`, in ascending order and with the sources
650/// included - Java's overload `reachableFrom(Graph, IntList)`.
651///
652/// The search follows the edges in their direction; for the nodes from which a source is reachable,
653/// search the transposed graph, as shown at [`BiAdjacentGraph::transposed`]. A source given twice
654/// counts once, and with no sources, no node is reachable. Being sorted, the result goes straight into
655/// [`NodeMapping::for_subgraph_sorted`] for the subgraph of the reachable nodes, as shown at
656/// [`remapped`]. For distances and shortest paths, use [`BfsDistances`](crate::BfsDistances).
657///
658/// **Time:** O(sources.len() + node_count + edge_count).
659/// **Memory:** 4 bytes per reachable node for the result; while it runs, 1 bit per node and briefly
660/// up to 12 bytes per reachable node.
661///
662/// # Panics
663/// With an `index out of bounds` message if a source is not in `0..node_count`.
664#[track_caller]
665pub fn reachable_from_sources(graph: &Graph, sources: &[u32]) -> SortedIntView<'static> {
666 let n = graph.node_count();
667 crate::error::check_nodes(sources, n);
668 let out = graph.out_adjacency_start();
669 let adj = graph.out_adjacency();
670 let mut visited = vec![0u64; (n as usize >> 6) + 1];
671 // Every reachable node enters the queue exactly once, so the queue grows into the result.
672 // The initial capacity holds every distinct source.
673 let mut queue: Vec<u32> = Vec::with_capacity((n as usize).min(sources.len().max(16)));
674 for &s in sources {
675 let (w, bit) = (s as usize >> 6, 1u64 << (s & 63));
676 if visited[w] & bit == 0 {
677 visited[w] |= bit;
678 queue.push(s);
679 }
680 }
681 let mut head = 0usize;
682 while head < queue.len() {
683 let u = queue[head] as usize;
684 head += 1;
685 for &v in &adj[out[u] as usize..out[u + 1] as usize] {
686 let (w, bit) = (v as usize >> 6, 1u64 << (v & 63));
687 if visited[w] & bit == 0 {
688 visited[w] |= bit;
689 if queue.len() == queue.capacity() {
690 // Doubles, but never beyond one entry per node, as in Java.
691 let grown = (2 * queue.capacity()).min(n as usize);
692 queue.reserve_exact(grown - queue.len());
693 }
694 queue.push(v);
695 }
696 }
697 }
698 // The queue is done; refill it in ascending order from the bit set, at its exact length.
699 queue.shrink_to_fit();
700 let mut k = 0usize;
701 for (w, &word) in visited.iter().enumerate() {
702 let mut bits = word;
703 while bits != 0 {
704 queue[k] = ((w << 6) + bits.trailing_zeros() as usize) as u32;
705 k += 1;
706 bits &= bits - 1;
707 }
708 }
709 SortedIntView::owned(queue)
710}
711
712/// Returns whether `graph` is a DAG: a graph without cycles. A self-loop is a cycle.
713///
714/// [`find_cycle`] returns a cycle where this function finds one.
715///
716/// **Time:** O(node_count + edge_count), stopping at the first cycle.
717/// **Memory:** 2 bits per node while it runs, and up to 8 x node_count bytes for the stack, which
718/// grows with the deepest path.
719///
720/// # Panics
721/// With an `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
722pub fn is_dag(graph: &Graph) -> bool {
723 cycle_check(graph, false).is_none()
724}
725
726/// Returns the nodes of a cycle of `graph` in the order of its edges, or an empty vector if `graph` is
727/// a DAG.
728///
729/// The last node has an edge to the first, and a self-loop is a cycle of one node. The search goes
730/// depth-first, from each unvisited node in ascending order and through the out-nodes in ascending
731/// order, and returns the first cycle it closes: always the same one, but not necessarily the
732/// shortest. Here, the cycle in the dependencies between the packages of a program:
733///
734/// <!-- example: graph_operations.rs#findCycle -->
735/// ```
736/// # use graphity_core::graphs;
737/// # let dependencies = graphity_core::Graph::of(
738/// # &[0, 3, 4, 7, 9, 10, 13, 14, 14],
739/// # &[1, 2, 3, 7, 3, 4, 7, 4, 5, 5, 4, 6, 7, 7],
740/// # ).unwrap();
741/// let cycle = graphs::find_cycle(&dependencies);
742/// // cycle: [4, 5] - model and storage, closed by the edge storage -> model
743/// # assert_eq!(cycle, [4, 5]);
744/// ```
745///
746/// For a cycle inside a given SCC, search the subgraph of its nodes from [`remapped`]; the node
747/// mapping of the subgraph translates the result back. The result is a vector the caller owns, with
748/// each node once - Java returns an unmodifiable `IntList`.
749///
750/// **Time:** O(node_count + edge_count), stopping at the first cycle.
751/// **Memory:** 4 bytes per node of the cycle for the result; while it runs, 2 bits per node and up to
752/// 8 x node_count bytes for the stack, which grows with the deepest path.
753///
754/// # Panics
755/// With an `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
756pub fn find_cycle(graph: &Graph) -> Vec<u32> {
757 cycle_check(graph, true).unwrap_or_default()
758}
759
760/// Returns whether `graph` is a forest: a DAG in which every node has in-degree at most 1, so that the
761/// edges point away from the root nodes.
762///
763/// The empty graph is a forest. For the undirected reading, see [`is_undirected_forest`].
764///
765/// **Time:** O(node_count + edge_count).
766/// **Memory:** 8 x node_count bytes while it runs.
767pub fn is_forest(graph: &Graph) -> bool {
768 forest_info(graph).is_some()
769}
770
771/// Returns whether `graph` is a tree: a forest with at most one root node.
772///
773/// The edges of a tree point away from its root. For a tree whose edges point toward the root, check
774/// the transposed graph, which is `BiAdjacentGraph::of(&graph).transposed()`. For the undirected
775/// reading, see [`is_undirected_tree`]. The empty graph is a tree.
776///
777/// **Time:** O(node_count + edge_count).
778/// **Memory:** 8 x node_count bytes while it runs.
779pub fn is_tree(graph: &Graph) -> bool {
780 forest_info(graph).is_some_and(|info| info.root_count <= 1)
781}
782
783/// Returns whether `graph` is a path: a tree in which every node has out-degree at most 1.
784///
785/// The empty graph is a path.
786///
787/// **Time:** O(node_count + edge_count).
788/// **Memory:** 8 x node_count bytes while it runs.
789pub fn is_path(graph: &Graph) -> bool {
790 forest_info(graph).is_some_and(|info| info.root_count <= 1 && info.max_out_degree <= 1)
791}
792
793/// Returns whether `graph` is strongly connected: every node reaches every other along the edges.
794///
795/// Answers without the partition of [`components::sccs_of`](crate::components::sccs_of). Uses
796/// [Tarjan's algorithm](https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm),
797/// without recursion. It starts from node 0 and stops as soon as an SCC without node 0 is complete.
798/// Where the SCCs are already computed,
799/// [`Sccs::is_strongly_connected`](crate::Sccs::is_strongly_connected) answers in O(1). The empty
800/// graph is strongly connected, and so is a single node. For the undirected reading, see
801/// [`is_weakly_connected`].
802///
803/// **Time:** O(node_count + edge_count), stopping at the first SCC without node 0.
804/// **Memory:** 8 x node_count bytes while it runs, and up to 8 x node_count bytes for the stack, which
805/// grows with the deepest path.
806///
807/// # Panics
808/// With an `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
809pub fn is_strongly_connected(graph: &Graph) -> bool {
810 let n = graph.node_count() as usize;
811 if n <= 1 {
812 return true;
813 }
814 let out = graph.out_adjacency_start();
815 let adj = graph.out_adjacency();
816 let mut index = vec![0u32; n]; // discovery time from 1; 0 = unvisited
817 let mut low = vec![0u32; n];
818 let mut frames = dfs_frames::initial(n as u32);
819 let mut time = 1u32;
820 index[0] = 1;
821 low[0] = 1;
822 frames[0] = 0;
823 frames[1] = out[0];
824 let mut top = 0usize;
825
826 'outer: loop {
827 let u = frames[2 * top] as usize;
828 let end = out[u + 1] as usize;
829 let mut i = frames[2 * top + 1] as usize;
830 while i < end {
831 let v = adj[i] as usize;
832 i += 1;
833 if index[v] == 0 {
834 frames[2 * top + 1] = i as u32;
835 time += 1;
836 index[v] = time;
837 low[v] = time;
838 top += 1;
839 if top == frames.len() >> 1 {
840 dfs_frames::grow(&mut frames, n as u32);
841 }
842 frames[2 * top] = v as u32;
843 frames[2 * top + 1] = out[v];
844 continue 'outer;
845 }
846 if index[v] < low[u] {
847 low[u] = index[v];
848 }
849 }
850 if top == 0 {
851 return time as usize == n;
852 }
853 if low[u] == index[u] {
854 return false;
855 }
856 let parent = frames[2 * (top - 1)] as usize;
857 if low[u] < low[parent] {
858 low[parent] = low[u];
859 }
860 top -= 1;
861 }
862}
863
864/// Iterative depth-first search for a back edge, a self-loop included. Returns `None` without a
865/// cycle, otherwise the cycle closed by the first back edge if `record_cycle`, else an empty list.
866fn cycle_check(graph: &Graph, record_cycle: bool) -> Option<Vec<u32>> {
867 let n = graph.node_count() as usize;
868 let out = graph.out_adjacency_start();
869 let adj = graph.out_adjacency();
870 // Visited and on-stack, 2 bits per node, 16 nodes per word.
871 let mut state = vec![0u32; (n >> 4) + 1];
872 let mut frames = dfs_frames::initial(n as u32);
873
874 for root in 0..n {
875 let r_shift = (root & 0xF) << 1;
876 if (state[root >> 4] >> r_shift) & VISITED != 0 {
877 continue;
878 }
879 state[root >> 4] |= (VISITED | ON_STACK) << r_shift;
880 frames[0] = root as u32;
881 frames[1] = out[root];
882 let mut top = 0usize;
883
884 'outer: loop {
885 let u = frames[2 * top] as usize;
886 let end = out[u + 1] as usize;
887 let mut i = frames[2 * top + 1] as usize;
888 while i < end {
889 let v = adj[i] as usize;
890 i += 1;
891 let shift = (v & 0xF) << 1;
892 let flags = state[v >> 4] >> shift;
893 if flags & ON_STACK != 0 {
894 if !record_cycle {
895 return Some(Vec::new());
896 }
897 // The path from v up to u, the top, is on the frame stack: u -> v closes it.
898 let mut at = top;
899 while frames[2 * at] as usize != v {
900 at -= 1;
901 }
902 return Some((at..=top).map(|k| frames[2 * k]).collect());
903 }
904 if flags & VISITED == 0 {
905 frames[2 * top + 1] = i as u32;
906 state[v >> 4] |= (VISITED | ON_STACK) << shift;
907 top += 1;
908 if top == frames.len() >> 1 {
909 dfs_frames::grow(&mut frames, n as u32);
910 }
911 frames[2 * top] = v as u32;
912 frames[2 * top + 1] = out[v];
913 continue 'outer;
914 }
915 }
916 state[u >> 4] &= !(ON_STACK << ((u & 0xF) << 1));
917 if top == 0 {
918 break;
919 }
920 top -= 1;
921 }
922 }
923 None
924}
925
926struct ForestInfo {
927 root_count: u32,
928 max_out_degree: u32,
929}
930
931/// The root count and largest out-degree if `graph` is a forest, or `None` if some node has
932/// in-degree above 1 or lies on or below a cycle. [`Ancestry::of`](crate::Ancestry::of) makes the
933/// same check, with a witness for its message; a change to what counts as a forest changes both.
934fn forest_info(graph: &Graph) -> Option<ForestInfo> {
935 let n = graph.node_count() as usize;
936 let targets = graph.out_adjacency();
937 let start = graph.out_adjacency_start();
938
939 let mut in_degree = vec![0u32; n];
940 for &target in targets {
941 let degree = &mut in_degree[target as usize];
942 *degree += 1;
943 if *degree > 1 {
944 return None;
945 }
946 }
947 // With every in-degree <= 1, a BFS from the roots enqueues each node at most once; a node it
948 // misses lies on a cycle or below one.
949 let mut queue = vec![0u32; n];
950 let mut tail = 0usize;
951 let mut max_out_degree = 0u32;
952 for i in 0..n {
953 max_out_degree = max_out_degree.max(start[i + 1] - start[i]);
954 if in_degree[i] == 0 {
955 queue[tail] = i as u32;
956 tail += 1;
957 }
958 }
959 let root_count = tail as u32;
960 let mut head = 0usize;
961 while head < tail {
962 let node = queue[head] as usize;
963 head += 1;
964 for &child in &targets[start[node] as usize..start[node + 1] as usize] {
965 queue[tail] = child;
966 tail += 1;
967 }
968 }
969 (tail == n).then_some(ForestInfo {
970 root_count,
971 max_out_degree,
972 })
973}
974
975/// Returns whether `graph` is bipartite: its nodes split into two sets such that every edge runs from
976/// one set to the other.
977///
978/// Reads the graph as undirected, so the direction of the edges does not matter. A self-loop makes the
979/// graph not bipartite, unlike the other checks of the undirected reading, which ignore self-loops.
980/// The empty graph is bipartite.
981///
982/// **Time:** O(node_count + edge_count x alpha(node_count)), stopping at the first cycle of odd
983/// length.
984/// **Memory:** 10 x node_count bytes while it runs.
985///
986/// # Panics
987/// With an `invalid argument` message if `graph` has more than `2^30 - 5` nodes.
988pub fn is_bipartite(graph: &Graph) -> bool {
989 let n = graph.node_count();
990 check_node_count(n, MAX_NODE_COUNT_TWO_INTS, "is_bipartite");
991 let targets = graph.out_adjacency();
992 let start = graph.out_adjacency_start();
993
994 // Double cover: element u means "u in class A", element u + n "u in class B". An edge ties
995 // each endpoint to the other's opposite, so once a node shares a set with its own opposite,
996 // both classes would have to hold it - an odd cycle. Both unions are symmetric in u and v,
997 // which is why the stored direction does not matter and a reciprocal pair repeats them.
998 let mut parent = union_find::singletons(2 * n as usize);
999 let mut rank = vec![0u8; 2 * n as usize];
1000 for u in 0..n {
1001 for &v in &targets[start[u as usize] as usize..start[u as usize + 1] as usize] {
1002 if u == v {
1003 return false;
1004 }
1005 union_find::union(&mut parent, &mut rank, u, v + n);
1006 union_find::union(&mut parent, &mut rank, u + n, v);
1007 if union_find::find(&mut parent, u) == union_find::find(&mut parent, u + n) {
1008 return false;
1009 }
1010 }
1011 }
1012 true
1013}
1014
1015/// Returns whether `graph` is a tree when read as undirected: connected and without cycles.
1016///
1017/// Unlike for [`is_tree`], the direction of the edges does not matter: edges toward the root, or in
1018/// mixed directions, make a tree as well. The edges `a -> b` and `b -> a` count as one, so a tree may
1019/// store its edges in both directions, and self-loops are ignored. The empty graph is a tree.
1020///
1021/// **Time:** O(node_count + edge_count x alpha(node_count)), plus O(log max_out_degree) for each pair
1022/// `a -> b`, `b -> a`; O(1) for more than 3 x node_count - 2 edges, too many for any tree.
1023/// **Memory:** 5 x node_count bytes while it runs.
1024pub fn is_undirected_tree(graph: &Graph) -> bool {
1025 let n = graph.node_count();
1026 if n == 0 {
1027 return true;
1028 }
1029 if exceeds_acyclic_edge_bound(graph) {
1030 return false;
1031 }
1032 // A cycle yields None, which never equals n - 1, so one comparison covers both acyclicity and
1033 // connectedness.
1034 undirected_merge_count(graph) == Some(n - 1)
1035}
1036
1037/// Returns whether `graph` is a forest when read as undirected: without cycles.
1038///
1039/// Unlike for [`is_forest`], the direction of the edges does not matter. The edges `a -> b` and
1040/// `b -> a` count as one, so they make no cycle, and self-loops are ignored. The empty graph is a
1041/// forest.
1042///
1043/// **Time:** O(node_count + edge_count x alpha(node_count)), plus O(log max_out_degree) for each pair
1044/// `a -> b`, `b -> a`; O(1) for more than 3 x node_count - 2 edges, too many for any forest.
1045/// **Memory:** 5 x node_count bytes while it runs.
1046pub fn is_undirected_forest(graph: &Graph) -> bool {
1047 !exceeds_acyclic_edge_bound(graph) && undirected_merge_count(graph).is_some()
1048}
1049
1050/// Returns whether `graph` is weakly connected: connected when the direction of the edges is ignored.
1051///
1052/// Answers without the partition of [`components::wccs_of`](crate::components::wccs_of), and stops
1053/// as soon as all nodes are connected. The empty graph is weakly connected, and so is a single node.
1054/// For the directed reading, see [`is_strongly_connected`].
1055///
1056/// **Time:** O(node_count + edge_count x alpha(node_count)), stopping once all nodes are connected.
1057/// **Memory:** 5 x node_count bytes while it runs.
1058pub fn is_weakly_connected(graph: &Graph) -> bool {
1059 let n = graph.node_count();
1060 if n <= 1 {
1061 return true;
1062 }
1063 let targets = graph.out_adjacency();
1064 let start = graph.out_adjacency_start();
1065 // A second union of the same two nodes merges nothing, and neither does a self-loop.
1066 let mut parent = union_find::singletons(n as usize);
1067 let mut rank = vec![0u8; n as usize];
1068 let mut merges = 0u32;
1069 for u in 0..n {
1070 for &v in &targets[start[u as usize] as usize..start[u as usize + 1] as usize] {
1071 if union_find::union(&mut parent, &mut rank, u, v) {
1072 merges += 1;
1073 if merges == n - 1 {
1074 return true; // n - 1 merges join every node
1075 }
1076 }
1077 }
1078 }
1079 false
1080}
1081
1082/// Whether `graph` holds more edges than any acyclic undirected reading could: at most
1083/// `node_count - 1` undirected edges, each stored in up to two directions, plus at most one
1084/// self-loop per node. A shortcut that answers in O(1) and allocates nothing.
1085fn exceeds_acyclic_edge_bound(graph: &Graph) -> bool {
1086 let n = u64::from(graph.node_count());
1087 u64::from(graph.edge_count()) > if n == 0 { 0 } else { 3 * n - 2 }
1088}
1089
1090/// Merges the endpoints of every undirected edge and returns the number of merges, so that the
1091/// nodes form `node_count - result` components; or `None` as soon as an edge closes an undirected
1092/// cycle. Self-loops are skipped.
1093///
1094/// Nodes are walked in ascending order, which makes a failed union classifiable: both endpoints
1095/// are already connected, so the edge is either the second stored direction of an edge already
1096/// counted or a genuine extra edge. For `v > u` the opposite direction sits in a list not yet
1097/// visited, so this is the first encounter and the failure is a cycle; for `v < u` one binary
1098/// search in `v`'s out-adjacency decides it.
1099fn undirected_merge_count(graph: &Graph) -> Option<u32> {
1100 let n = graph.node_count();
1101 let targets = graph.out_adjacency();
1102 let start = graph.out_adjacency_start();
1103 let mut parent = union_find::singletons(n as usize);
1104 let mut rank = vec![0u8; n as usize];
1105 let mut merges = 0u32;
1106 for u in 0..n {
1107 for &v in &targets[start[u as usize] as usize..start[u as usize + 1] as usize] {
1108 if u == v {
1109 continue;
1110 }
1111 if union_find::union(&mut parent, &mut rank, u, v) {
1112 merges += 1;
1113 } else if v > u
1114 || !contains_in_range(
1115 targets,
1116 start[v as usize] as usize,
1117 start[v as usize + 1] as usize,
1118 u,
1119 )
1120 {
1121 return None;
1122 }
1123 }
1124 }
1125 Some(merges)
1126}
1127
1128/// Returns the whole graph as text: one line per node with its out-nodes, in ascending order.
1129///
1130/// Each line ends with a line feed. For the control flow of a method with a loop:
1131///
1132/// <!-- example: graph_operations.rs#adjacencyListOf -->
1133/// ```
1134/// # use graphity_core::graphs;
1135/// # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
1136/// let text = graphs::adjacency_list_of(&cfg);
1137/// // 0 -> [1]
1138/// // 1 -> [2, 5]
1139/// // 2 -> [3, 4]
1140/// // 3 -> [4]
1141/// // 4 -> [1]
1142/// // 5 -> []
1143/// # assert_eq!(text, "0 -> [1]\n1 -> [2, 5]\n2 -> [3, 4]\n3 -> [4]\n4 -> [1]\n5 -> []\n");
1144/// ```
1145///
1146/// Unlike the [`Display`](std::fmt::Display) form of a graph, which is cut short for large graphs,
1147/// this lists every node and edge; the graph of a [`BiAdjacentGraph`] lists its out-nodes.
1148///
1149/// **Time:** O(node_count + edge_count).
1150/// **Memory:** 1 byte per character for the result; while it runs, about as much again.
1151pub fn adjacency_list_of(graph: &Graph) -> String {
1152 let start = graph.out_adjacency_start();
1153 let targets = graph.out_adjacency();
1154 let n = graph.node_count() as usize;
1155 let capacity = (LIST_CHARS_PER_NODE * n as u64 + LIST_CHARS_PER_EDGE * targets.len() as u64)
1156 .min(u64::from(MAX_ARRAY_LENGTH));
1157 let mut text = String::with_capacity(capacity as usize);
1158 for v in 0..n {
1159 let _ = write!(text, "{v} -> [");
1160 for (k, target) in targets[start[v] as usize..start[v + 1] as usize]
1161 .iter()
1162 .enumerate()
1163 {
1164 if k > 0 {
1165 text.push_str(", ");
1166 }
1167 let _ = write!(text, "{target}");
1168 }
1169 text.push_str("]\n");
1170 }
1171 // The estimate is the working memory; the result keeps 1 byte per character, as Java's
1172 // toString copy does.
1173 text.shrink_to_fit();
1174 text
1175}
1176
1177/// Returns a 64-bit hash of the nodes and edges of `graph`, consistent with `==`.
1178///
1179/// Equal graphs have equal hashes, and different graphs rarely do. The graph of a
1180/// [`BiAdjacentGraph`] and a `Graph` with the same nodes and edges count as equal. Like the
1181/// [`Hash`](std::hash::Hash) of a graph, the hash is computed on every call: compute it once and
1182/// keep it, for instance as the key of a cache of results per graph, or to see when a
1183/// transformation stops changing a graph. It depends on nothing but the nodes and edges, so it is
1184/// the same in every run and on every platform; a release of Graphity that changes it says so in
1185/// its changelog. Every implementation of Graphity computes the same hash. It is an `i64` like
1186/// Java's `long`, so that the numbers agree too. Equal hashes do not prove equal graphs, and graphs
1187/// can be made to collide on purpose: compare with `==` where it matters.
1188///
1189/// **Time:** O(node_count + edge_count).
1190pub fn topology_hash(graph: &Graph) -> i64 {
1191 let start = graph.out_adjacency_start();
1192 let targets = graph.out_adjacency();
1193 let n = graph.node_count();
1194 let mut h = mix_into(HASH_SEED, n);
1195 h = mix_into(h, graph.edge_count());
1196 for v in 0..n as usize {
1197 let (from, end) = (start[v] as usize, start[v + 1] as usize);
1198 h = mix_into(h, (end - from) as u32);
1199 for &target in &targets[from..end] {
1200 h = mix_into(h, target);
1201 }
1202 }
1203 // SplitMix64 finalizer: every input bit reaches every output bit.
1204 h = (h ^ (h >> 30)).wrapping_mul(SPLITMIX64_MULTIPLIER_1);
1205 h = (h ^ (h >> 27)).wrapping_mul(SPLITMIX64_MULTIPLIER_2);
1206 (h ^ (h >> 31)) as i64
1207}
1208
1209/// One order-sensitive step of [`topology_hash`]. The value is a Java `int`, sign-extended when
1210/// multiplied with the 64-bit gamma, as Java does.
1211#[inline]
1212fn mix_into(h: u64, value: u32) -> u64 {
1213 let spread = (value as i32 as i64 as u64).wrapping_mul(HASH_GOLDEN_GAMMA);
1214 (h ^ spread).rotate_left(29).wrapping_mul(HASH_STEP_PRIME)
1215}
1216
1217/// Returns the edges added and removed between `before` and `after`. Both are graphs over the same
1218/// nodes.
1219///
1220/// Added edges come with their edge indices in `after`, removed edges with theirs in `before`. With
1221/// these edge indices, the caller can look up data on the edges of either graph in arrays indexed by
1222/// edge index. Both lists are in edge index order. An empty diff means that the graphs are equal.
1223///
1224/// **Time:** O(node_count + edge_count), with the edges of both graphs.
1225/// **Memory:** 12 bytes per added or removed edge for the result; while it runs, up to 18 bytes more
1226/// per such edge.
1227///
1228/// # Panics
1229/// With an `invalid argument` message if the node counts differ.
1230#[track_caller]
1231pub fn diff(before: &Graph, after: &Graph) -> GraphDiff {
1232 let n = before.node_count();
1233 if after.node_count() != n {
1234 invalid_argument!(
1235 "diff needs graphs over the same nodes, but before has {n} nodes and after {}",
1236 after.node_count()
1237 );
1238 }
1239 let old_start = before.out_adjacency_start();
1240 let old_targets = before.out_adjacency();
1241 let new_start = after.out_adjacency_start();
1242 let new_targets = after.out_adjacency();
1243 // Parallel lists, so that none needs more entries than its graph has edges.
1244 let (mut added_sources, mut added_targets, mut added_indices) =
1245 (Vec::new(), Vec::new(), Vec::new());
1246 let (mut removed_sources, mut removed_targets, mut removed_indices) =
1247 (Vec::new(), Vec::new(), Vec::new());
1248 for v in 0..n as usize {
1249 let (mut old_pos, old_end) = (old_start[v] as usize, old_start[v + 1] as usize);
1250 let (mut new_pos, new_end) = (new_start[v] as usize, new_start[v + 1] as usize);
1251 // No target reaches u32::MAX - node IDs stay below it -, so it marks an exhausted list.
1252 while old_pos < old_end || new_pos < new_end {
1253 let old_target = if old_pos < old_end {
1254 old_targets[old_pos]
1255 } else {
1256 u32::MAX
1257 };
1258 let new_target = if new_pos < new_end {
1259 new_targets[new_pos]
1260 } else {
1261 u32::MAX
1262 };
1263 if old_target == new_target {
1264 old_pos += 1;
1265 new_pos += 1;
1266 } else if old_target < new_target {
1267 growth::push(&mut removed_sources, v as u32);
1268 growth::push(&mut removed_targets, old_target);
1269 growth::push(&mut removed_indices, old_pos as u32);
1270 old_pos += 1;
1271 } else {
1272 growth::push(&mut added_sources, v as u32);
1273 growth::push(&mut added_targets, new_target);
1274 growth::push(&mut added_indices, new_pos as u32);
1275 new_pos += 1;
1276 }
1277 }
1278 }
1279 // Both lists are in edge index order already, which sorted_edges detects and only copies.
1280 GraphDiff::new(
1281 Edges::sorted_edges(
1282 after,
1283 &added_sources,
1284 &added_targets,
1285 &added_indices,
1286 added_sources.len(),
1287 false,
1288 ),
1289 Edges::sorted_edges(
1290 before,
1291 &removed_sources,
1292 &removed_targets,
1293 &removed_indices,
1294 removed_sources.len(),
1295 false,
1296 ),
1297 )
1298}