graphity_core/top_order_and_levels.rs
1use crate::error::check_index;
2use crate::{Graph, GraphError};
3
4/// A topological order of a DAG (directed acyclic graph) with the level of each node. A root node has
5/// level 0, and every other node has one more than the highest level of its in-nodes.
6///
7/// The level of a node is the number of edges on a longest path to it from a root node, so no path
8/// connects two nodes of the same level. [`order`](Self::order) lists the nodes level by level,
9/// [`level_of`](Self::level_of) and [`levels`](Self::levels) return their levels, and
10/// [`level_count`](Self::level_count) the number of levels.
11///
12/// Uses [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn%27s_algorithm):
13/// [`of`](Self::of) starts with the root nodes in ascending order, places a node once all its
14/// in-nodes are placed and takes the out-nodes of each node in ascending order, so a graph always
15/// gets the same order. For the order alone, [`top_order::of`](crate::top_order::of) needs less
16/// memory.
17///
18/// ```
19/// use graphity_core::{GraphBuilder, TopOrderAndLevels};
20///
21/// let mut b = GraphBuilder::new();
22/// b.add_nodes(4);
23/// b.add_edge_pairs(&[0, 1, 0, 2, 1, 3, 2, 3]);
24/// let levels = TopOrderAndLevels::of(&b.build()).unwrap();
25/// assert_eq!(levels.order(), [0, 1, 2, 3]);
26/// assert_eq!(levels.level_of(3), 2);
27/// assert_eq!(levels.level_count(), 3);
28/// ```
29///
30/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
31///
32/// **Memory:** 8 x node_count bytes.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct TopOrderAndLevels {
35 order: Box<[u32]>,
36 levels: Box<[u32]>,
37 level_count: u32,
38}
39
40impl TopOrderAndLevels {
41 /// Returns the topological order and the levels of `graph`.
42 ///
43 /// On the graph of a [`BiAdjacentGraph`](crate::BiAdjacentGraph), it reads the in-degrees instead of
44 /// counting them in a pass over the edges.
45 ///
46 /// **Time:** O(node_count + edge_count).
47 /// **Memory:** 8 x node_count bytes for the result; while it runs, 8 x node_count bytes more.
48 ///
49 /// # Errors
50 /// An [`InvalidArgument`](crate::ErrorKind::InvalidArgument) error, "graph contains a cycle", if
51 /// `graph` has a cycle, a self-loop included.
52 pub fn of(graph: &Graph) -> Result<TopOrderAndLevels, GraphError> {
53 let n = graph.node_count() as usize;
54
55 // 1) In-degrees; a bi-adjacent graph has them in its offsets.
56 let mut in_degree = vec![0u32; n];
57 match graph.in_adjacency_start_if_present() {
58 Some(in_start) => {
59 for (v, degree) in in_degree.iter_mut().enumerate() {
60 *degree = in_start[v + 1] - in_start[v];
61 }
62 }
63 None => {
64 for &target in graph.out_adjacency() {
65 in_degree[target as usize] += 1;
66 }
67 }
68 }
69
70 // 2) Roots.
71 let mut queue = vec![0u32; n];
72 let mut queue_tail = 0usize;
73 for (v, °ree) in in_degree.iter().enumerate() {
74 if degree == 0 {
75 queue[queue_tail] = v as u32;
76 queue_tail += 1;
77 }
78 }
79
80 // 3) Kahn, one wave per level: a node joins the wave after that of its last predecessor.
81 let mut order = vec![0u32; n];
82 let mut levels = vec![0u32; n];
83 let mut order_pos = 0usize;
84 let mut level = 0u32;
85 let adjacency = graph.out_adjacency();
86 let adjacency_start = graph.out_adjacency_start();
87 let mut queue_head = 0usize;
88 while queue_head < queue_tail {
89 let level_end = queue_tail;
90 while queue_head < level_end {
91 let node = queue[queue_head] as usize;
92 queue_head += 1;
93 order[order_pos] = node as u32;
94 order_pos += 1;
95 levels[node] = level;
96 for &target in
97 &adjacency[adjacency_start[node] as usize..adjacency_start[node + 1] as usize]
98 {
99 let degree = &mut in_degree[target as usize];
100 *degree -= 1;
101 if *degree == 0 {
102 queue[queue_tail] = target;
103 queue_tail += 1;
104 }
105 }
106 }
107 level += 1;
108 }
109 if order_pos != n {
110 return Err(GraphError::invalid_argument("graph contains a cycle"));
111 }
112 Ok(TopOrderAndLevels {
113 order: order.into_boxed_slice(),
114 levels: levels.into_boxed_slice(),
115 level_count: level,
116 })
117 }
118
119 /// Returns the nodes in topological order, level by level: for every edge `u -> v`, `u` comes before
120 /// `v`.
121 ///
122 /// **Time:** O(1).
123 #[inline]
124 pub fn order(&self) -> &[u32] {
125 &self.order
126 }
127
128 /// Returns the level of every node, by node ID.
129 ///
130 /// **Time:** O(1).
131 #[inline]
132 pub fn levels(&self) -> &[u32] {
133 &self.levels
134 }
135
136 /// Returns the level of `node`. Equivalent to `levels()[node]`.
137 ///
138 /// **Time:** O(1).
139 ///
140 /// # Panics
141 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
142 #[inline]
143 #[track_caller]
144 pub fn level_of(&self, node: u32) -> u32 {
145 check_index(node, self.levels.len() as u32);
146 self.levels[node as usize]
147 }
148
149 /// Returns the number of levels, or `0` for a graph without nodes. It equals the number of nodes on a
150 /// longest path.
151 ///
152 /// **Time:** O(1).
153 #[inline]
154 pub fn level_count(&self) -> u32 {
155 self.level_count
156 }
157}