Skip to main content

graphity_core/
edges.rs

1use crate::{EdgeType, EdgeTypes, Graph, NONE};
2
3/// A list of edges of a graph, each with its source, target and edge index. Algorithms such as
4/// [`back_edges::of`](crate::back_edges::of) and
5/// [`Biconnectivity::bridges`](crate::Biconnectivity::bridges) return it.
6///
7/// The edge at position `p`, in `0..count()`, is `source_nodes()[p] -> target_nodes()[p]`, and
8/// `edge_indices()[p]` is its edge index in the graph the algorithm ran on. The edge index finds the
9/// data of the edge in the caller's arrays indexed by edge index, without a search. Here, the back
10/// edges of the calls between the methods of a program are its recursive calls. `names` holds the
11/// names of the methods, and `site_count` holds the number of call sites of each call, by edge index:
12///
13/// <!-- example: building_and_reading.rs#edges -->
14/// ```
15/// # use std::io::Write;
16/// # use graphity_core::back_edges;
17/// # let calls = graphity_core::Graph::of(
18/// #     &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
19/// #     &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
20/// # ).unwrap();
21/// # let names: &[&str] = &[
22/// #     "main", "parseArgs", "run", "load", "save", "show", "parse", "format", "read", "write",
23/// # ];
24/// # let site_count = [1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1];
25/// # let mut out = Vec::new();
26/// let recursive = back_edges::of(&calls);
27/// for p in 0..recursive.count() as usize {
28///     let caller = recursive.source_nodes()[p];
29///     let callee = recursive.target_nodes()[p];
30///     let edge = recursive.edge_indices()[p];
31///     writeln!(
32///         out,
33///         "{} -> {}: {}",
34///         names[caller as usize], names[callee as usize], site_count[edge as usize]
35///     )?;
36/// }
37/// // parse -> parse: 2
38/// // format -> format: 1
39/// # assert_eq!(String::from_utf8(out).unwrap(), "parse -> parse: 2\nformat -> format: 1\n");
40/// # Ok::<(), std::io::Error>(())
41/// ```
42///
43/// Each function that returns `Edges` says in which order the edges come.
44/// [`GraphBuilder::add_edges`](crate::GraphBuilder::add_edges) adds them to a graph under
45/// construction.
46///
47/// The three lists are slices that cannot be modified - Java returns unmodifiable `IntList`s.
48/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
49///
50/// **Memory:** 12 bytes per edge.
51#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
52pub struct Edges {
53    source_nodes: Vec<u32>,
54    target_nodes: Vec<u32>,
55    edge_indices: Vec<u32>,
56}
57
58impl Edges {
59    /// Edges over three lists of equal length.
60    pub(crate) fn wrap(
61        source_nodes: Vec<u32>,
62        target_nodes: Vec<u32>,
63        edge_indices: Vec<u32>,
64    ) -> Self {
65        debug_assert!(
66            source_nodes.len() == target_nodes.len() && target_nodes.len() == edge_indices.len()
67        );
68        Self {
69            source_nodes,
70            target_nodes,
71            edge_indices,
72        }
73    }
74
75    /// Returns the edges of one type from an edge classification, in edge index order.
76    ///
77    /// Each call goes through every edge, however few have the type: call it once per type and keep the
78    /// result.
79    ///
80    /// **Time:** O(node_count + edge_count).
81    /// **Memory:** 12 bytes per edge of the result.
82    pub fn of(edge_types: &EdgeTypes, edge_type: EdgeType) -> Edges {
83        // Counts the edges of the type first, so that the arrays of the result get their exact
84        // length, then fills them in one scan over all edges.
85        let types = &*edge_types.types;
86        let count = types.iter().filter(|&&t| t == edge_type).count();
87        if count == 0 {
88            return Edges::default();
89        }
90        let adjacency = edge_types.graph.out_adjacency();
91        let adjacency_start = edge_types.graph.out_adjacency_start();
92        let mut sources = Vec::with_capacity(count);
93        let mut targets = Vec::with_capacity(count);
94        let mut edge_indices = Vec::with_capacity(count);
95        for node in 0..adjacency_start.len() - 1 {
96            for e in adjacency_start[node]..adjacency_start[node + 1] {
97                if types[e as usize] == edge_type {
98                    sources.push(node as u32);
99                    targets.push(adjacency[e as usize]);
100                    edge_indices.push(e);
101                }
102            }
103        }
104        Edges::wrap(sources, targets, edge_indices)
105    }
106
107    /// Returns the source of each edge, by position.
108    ///
109    /// **Time:** O(1).
110    #[inline]
111    pub fn source_nodes(&self) -> &[u32] {
112        &self.source_nodes
113    }
114
115    /// Returns the target of each edge, by position.
116    ///
117    /// **Time:** O(1).
118    #[inline]
119    pub fn target_nodes(&self) -> &[u32] {
120        &self.target_nodes
121    }
122
123    /// Returns the edge index of each edge in the graph the algorithm ran on, by position.
124    ///
125    /// **Time:** O(1).
126    #[inline]
127    pub fn edge_indices(&self) -> &[u32] {
128        &self.edge_indices
129    }
130
131    /// Returns the number of edges.
132    ///
133    /// **Time:** O(1).
134    #[inline]
135    pub fn count(&self) -> u32 {
136        self.source_nodes.len() as u32
137    }
138
139    /// Returns whether there are no edges. Equivalent to `count() == 0`.
140    ///
141    /// **Time:** O(1).
142    #[inline]
143    pub fn is_empty(&self) -> bool {
144        self.source_nodes.is_empty()
145    }
146
147    /// Orders `count` edges of `graph`, given as three parallel arrays in their direction in the
148    /// graph, by source and then target - which is edge index order -, optionally dropping
149    /// repeated edges. An edge index of [`NONE`] is looked up with one binary search in the
150    /// source's adjacency; callers pass the index wherever they know it. Two stable counting
151    /// passes, first by target, then by source: O(node count + count) without comparisons. Input
152    /// that is already in order, or in exactly reverse order - the bridges of a path arrive that
153    /// way -, is copied instead; the check stops at the first edge out of line.
154    ///
155    /// The arrays are parallel so that none of them needs more than `count` entries.
156    ///
157    /// **Memory:** 4 x node count bytes for the counts and 24 x count bytes for the intermediate
158    /// and final lists.
159    pub(crate) fn sorted_edges(
160        graph: &Graph,
161        sources: &[u32],
162        targets: &[u32],
163        edge_indices: &[u32],
164        count: usize,
165        drop_duplicates: bool,
166    ) -> Edges {
167        if count == 0 {
168            return Edges::default();
169        }
170        let (sources, targets, edge_indices) =
171            (&sources[..count], &targets[..count], &edge_indices[..count]);
172        let (mut sorted_sources, mut sorted_targets, mut sorted_edge_indices) =
173            match direction(sources, targets) {
174                d if d > 0 => (sources.to_vec(), targets.to_vec(), edge_indices.to_vec()),
175                d if d < 0 => (
176                    sources.iter().rev().copied().collect(),
177                    targets.iter().rev().copied().collect(),
178                    edge_indices.iter().rev().copied().collect(),
179                ),
180                _ => counting_sort(sources, targets, edge_indices, graph.node_count() as usize),
181            };
182        if drop_duplicates {
183            let mut kept = 0usize;
184            for i in 0..count {
185                if kept > 0
186                    && sorted_sources[kept - 1] == sorted_sources[i]
187                    && sorted_targets[kept - 1] == sorted_targets[i]
188                {
189                    if sorted_edge_indices[kept - 1] == NONE {
190                        sorted_edge_indices[kept - 1] = sorted_edge_indices[i];
191                    }
192                    continue;
193                }
194                sorted_sources[kept] = sorted_sources[i];
195                sorted_targets[kept] = sorted_targets[i];
196                sorted_edge_indices[kept] = sorted_edge_indices[i];
197                kept += 1;
198            }
199            // Trimmed, as Java copies the lists to the kept length.
200            for list in [
201                &mut sorted_sources,
202                &mut sorted_targets,
203                &mut sorted_edge_indices,
204            ] {
205                list.truncate(kept);
206                list.shrink_to_fit();
207            }
208        }
209        for p in 0..sorted_sources.len() {
210            let (source, target) = (sorted_sources[p], sorted_targets[p]);
211            if sorted_edge_indices[p] == NONE {
212                sorted_edge_indices[p] = graph
213                    .edge_index_of(source, target)
214                    .expect("every listed edge is an edge of the graph");
215            }
216            debug_assert_eq!(
217                Some(sorted_edge_indices[p]),
218                graph.edge_index_of(source, target),
219                "{source} -> {target} is not edge {}",
220                sorted_edge_indices[p]
221            );
222        }
223        Edges::wrap(sorted_sources, sorted_targets, sorted_edge_indices)
224    }
225}
226
227/// `1` if the edges are in order, `-1` if exactly reversed, else `0`.
228fn direction(sources: &[u32], targets: &[u32]) -> i32 {
229    let mut direction = 0;
230    for i in 1..sources.len() {
231        let step = (sources[i - 1], targets[i - 1]).cmp(&(sources[i], targets[i]));
232        let sign = match step {
233            std::cmp::Ordering::Equal => continue,
234            std::cmp::Ordering::Less => 1,
235            std::cmp::Ordering::Greater => -1,
236        };
237        if direction == 0 {
238            direction = sign;
239        } else if direction != sign {
240            return 0;
241        }
242    }
243    if direction == 0 { 1 } else { direction }
244}
245
246type Lists = (Vec<u32>, Vec<u32>, Vec<u32>);
247
248/// Two stable counting passes, by target and then by source.
249fn counting_sort(
250    sources: &[u32],
251    targets: &[u32],
252    edge_indices: &[u32],
253    node_count: usize,
254) -> Lists {
255    let count = sources.len();
256    let mut start = vec![0u32; node_count + 1];
257    for &t in targets {
258        start[t as usize + 1] += 1;
259    }
260    for v in 0..node_count {
261        start[v + 1] += start[v];
262    }
263    let mut by_target_sources = vec![0u32; count];
264    let mut by_target_targets = vec![0u32; count];
265    let mut by_target_edge_indices = vec![0u32; count];
266    for i in 0..count {
267        let slot = &mut start[targets[i] as usize];
268        let s = *slot as usize;
269        *slot += 1;
270        by_target_sources[s] = sources[i];
271        by_target_targets[s] = targets[i];
272        by_target_edge_indices[s] = edge_indices[i];
273    }
274    start.fill(0);
275    for &s in &by_target_sources {
276        start[s as usize + 1] += 1;
277    }
278    for v in 0..node_count {
279        start[v + 1] += start[v];
280    }
281    let mut sorted_sources = vec![0u32; count];
282    let mut sorted_targets = vec![0u32; count];
283    let mut sorted_edge_indices = vec![0u32; count];
284    for i in 0..count {
285        let source = by_target_sources[i];
286        let slot = &mut start[source as usize];
287        let s = *slot as usize;
288        *slot += 1;
289        sorted_sources[s] = source;
290        sorted_targets[s] = by_target_targets[i];
291        sorted_edge_indices[s] = by_target_edge_indices[i];
292    }
293    (sorted_sources, sorted_targets, sorted_edge_indices)
294}
295
296#[cfg(test)]
297mod tests {
298    use super::*;
299    use crate::GraphBuilder;
300
301    /// Fills the slots past `count`, as a growing list leaves them; never a valid node.
302    const JUNK: u32 = 1_000_000;
303
304    fn graph(n: u32, edges: &[u32]) -> Graph {
305        let mut b = GraphBuilder::new();
306        b.add_nodes(n);
307        b.add_edge_pairs(edges);
308        b.build()
309    }
310
311    fn with_junk_tail(values: &[u32]) -> Vec<u32> {
312        let mut array = values.to_vec();
313        array.extend([JUNK; 3]);
314        array
315    }
316
317    #[test]
318    fn constructor_stores_all_three_lists() {
319        let edges = Edges::wrap(vec![0, 1, 2], vec![3, 4, 5], vec![6, 7, 8]);
320        assert_eq!(edges.source_nodes(), [0, 1, 2]);
321        assert_eq!(edges.target_nodes(), [3, 4, 5]);
322        assert_eq!(edges.edge_indices(), [6, 7, 8]);
323        assert_eq!(edges.count(), 3);
324        assert!(!edges.is_empty());
325    }
326
327    #[test]
328    fn empty_edges() {
329        let edges = Edges::default();
330        assert!(edges.is_empty());
331        assert_eq!(edges.count(), 0);
332        assert!(edges.source_nodes().is_empty());
333        assert!(edges.target_nodes().is_empty());
334        assert!(edges.edge_indices().is_empty());
335        assert!(Edges::wrap(vec![], vec![], vec![]).is_empty());
336    }
337
338    #[test]
339    fn orders_random_ascending_and_descending_input_alike() {
340        let mut state = 5u64;
341        let mut next = |bound: u32| {
342            state = state
343                .wrapping_mul(6364136223846793005)
344                .wrapping_add(1442695040888963407);
345            ((state >> 33) % u64::from(bound)) as u32
346        };
347        for iteration in 0..500 {
348            let node_count = 1 + next(20);
349            let count = next(40) as usize;
350            let mut keys: Vec<(u32, u32)> = (0..count)
351                .map(|_| (next(node_count), next(node_count)))
352                .collect();
353            match iteration % 3 {
354                1 => keys.sort(),
355                2 => {
356                    keys.sort();
357                    keys.reverse();
358                }
359                _ => {}
360            }
361            for drop_duplicates in [false, true] {
362                let flat: Vec<u32> = keys.iter().flat_map(|&(s, t)| [s, t]).collect();
363                let g = graph(node_count, &flat);
364                let mut expected = keys.clone();
365                expected.sort();
366                if drop_duplicates {
367                    expected.dedup();
368                }
369                let sources: Vec<u32> = keys.iter().map(|k| k.0).collect();
370                let targets: Vec<u32> = keys.iter().map(|k| k.1).collect();
371                let indices: Vec<u32> = keys
372                    .iter()
373                    .map(|&(s, t)| {
374                        if iteration % 2 == 0 {
375                            g.edge_index_of(s, t).unwrap()
376                        } else {
377                            NONE
378                        }
379                    })
380                    .collect();
381                let edges =
382                    Edges::sorted_edges(&g, &sources, &targets, &indices, count, drop_duplicates);
383                let actual: Vec<(u32, u32)> = (0..edges.count() as usize)
384                    .map(|p| (edges.source_nodes()[p], edges.target_nodes()[p]))
385                    .collect();
386                assert_eq!(actual, expected, "iteration {iteration}");
387                for (&(source, target), &e) in actual.iter().zip(edges.edge_indices()) {
388                    assert_eq!(Some(e), g.edge_index_of(source, target));
389                }
390            }
391        }
392    }
393
394    #[test]
395    fn reads_only_the_first_count_entries_and_leaves_the_arrays_untouched() {
396        // 0 -> 1 (edge 0), 0 -> 2 (1), 1 -> 2 (2), 2 -> 0 (3), 3 -> 1 (4).
397        let g = graph(4, &[0, 1, 0, 2, 1, 2, 2, 0, 3, 1]);
398        const N: u32 = NONE;
399        let mixed = [[2, 0, 3, 0, 1], [0, 2, 1, 1, 2], [3, N, 4, 0, N]];
400        let ascending = [[0, 0, 1, 2, 3], [1, 2, 2, 0, 1], [N, 1, 2, N, 4]];
401        let descending = [[3, 2, 1, 0, 0], [1, 0, 2, 2, 1], [4, 3, N, 1, 0]];
402        for input in [mixed, ascending, descending] {
403            let sources = with_junk_tail(&input[0]);
404            let targets = with_junk_tail(&input[1]);
405            let indices = with_junk_tail(&input[2]);
406            let before = (sources.clone(), targets.clone(), indices.clone());
407            let edges = Edges::sorted_edges(&g, &sources, &targets, &indices, 5, false);
408            assert_eq!(edges.source_nodes(), [0, 0, 1, 2, 3]);
409            assert_eq!(edges.target_nodes(), [1, 2, 2, 0, 1]);
410            assert_eq!(edges.edge_indices(), [0, 1, 2, 3, 4]);
411            assert_eq!((sources, targets, indices), before);
412        }
413    }
414
415    #[test]
416    fn drops_duplicates_from_parallel_arrays() {
417        // 0 -> 1 (edge 0), 1 -> 0 (1), 1 -> 2 (2).
418        let g = graph(3, &[0, 1, 1, 0, 1, 2]);
419        let sources = with_junk_tail(&[1, 0, 1, 1, 0]);
420        let targets = with_junk_tail(&[2, 1, 0, 2, 1]);
421        let indices = with_junk_tail(&[NONE, 0, 1, 2, NONE]);
422        let edges = Edges::sorted_edges(&g, &sources, &targets, &indices, 5, true);
423        assert_eq!(edges.source_nodes(), [0, 1, 1]);
424        assert_eq!(edges.target_nodes(), [1, 0, 2]);
425        assert_eq!(edges.edge_indices(), [0, 1, 2]);
426        // Trimmed to the kept edges, as Java's Arrays.copyOf.
427        assert_eq!(
428            [
429                edges.source_nodes.capacity(),
430                edges.target_nodes.capacity(),
431                edges.edge_indices.capacity()
432            ],
433            [3, 3, 3]
434        );
435    }
436}