Skip to main content

caroli_walk/
graph.rs

1//! Graphs whose edges carry the spins, with an order on the edges at each node.
2//!
3//! The walker lives on the half-edges: node `x` has one half-edge per incident edge, and the
4//! position of a half-edge among those of its node is its color. Half-edges are numbered node
5//! by node, so the half-edges of a node are consecutive.
6
7use std::ops::Range;
8
9/// A graph with numbered edges (edge `e` carries spin `e`) and colored half-edges.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct Graph {
12    nodes: usize,
13    /// Half-edges of node `x`: `offsets[x]..offsets[x + 1]`, in color order.
14    offsets: Vec<usize>,
15    /// Node and edge of each half-edge.
16    half_edges: Vec<(usize, usize)>,
17    /// The two half-edges of each edge, the first at the edge's first node.
18    halves: Vec<(usize, usize)>,
19}
20
21impl Graph {
22    /// From the colored neighbourhoods: `colors[x][c]` is the edge of color `c` at node `x`, and
23    /// `ends[e]` the two nodes of edge `e` (they may coincide only for distinct edges, as in a
24    /// two-node cycle). Every edge must appear exactly once at each of its ends.
25    pub fn new(ends: &[(usize, usize)], colors: &[Vec<usize>]) -> Self {
26        let nodes = colors.len();
27        let mut offsets = vec![0];
28        let mut half_edges = Vec::new();
29        for (x, edges) in colors.iter().enumerate() {
30            for &e in edges {
31                assert!(e < ends.len(), "node {x}: edge {e} does not exist");
32                half_edges.push((x, e));
33            }
34            offsets.push(half_edges.len());
35        }
36        let mut halves = vec![(usize::MAX, usize::MAX); ends.len()];
37        for (e, &(x, y)) in ends.iter().enumerate() {
38            assert!(x < nodes && y < nodes, "edge {e} joins a missing node");
39            assert!(x != y, "edge {e} is a loop");
40            let at = |node: usize| {
41                let found: Vec<usize> =
42                    (offsets[node]..offsets[node + 1]).filter(|&h| half_edges[h].1 == e).collect();
43                assert!(found.len() == 1, "edge {e} must appear once at node {node}");
44                found[0]
45            };
46            halves[e] = (at(x), at(y));
47        }
48        assert!(half_edges.len() == 2 * ends.len(), "every half-edge must belong to an edge of the list");
49        Self { nodes, offsets, half_edges, halves }
50    }
51
52    /// Edges in the order given; the colors of each node follow the order in which its edges
53    /// appear in the list.
54    pub fn from_edges(nodes: usize, ends: &[(usize, usize)]) -> Self {
55        let mut colors = vec![Vec::new(); nodes];
56        for (e, &(x, y)) in ends.iter().enumerate() {
57            colors[x].push(e);
58            colors[y].push(e);
59        }
60        Self::new(ends, &colors)
61    }
62
63    /// Ring of `n ≥ 2` nodes, as in Sellapillay & Verga: edge `x` joins `x` and `x + 1`, color 0
64    /// of node `x` points to `x + 1` and color 1 to `x − 1`.
65    pub fn cycle(n: usize) -> Self {
66        assert!(n >= 2, "a cycle needs two nodes");
67        let ends: Vec<(usize, usize)> = (0..n).map(|x| (x, (x + 1) % n)).collect();
68        let colors: Vec<Vec<usize>> = (0..n).map(|x| vec![x, (x + n - 1) % n]).collect();
69        Self::new(&ends, &colors)
70    }
71
72    /// Chain of `n ≥ 2` nodes: edge `x` joins `x` and `x + 1`; color 0 points to `x + 1` and
73    /// color 1 to `x − 1` (the end nodes have one color).
74    pub fn path(n: usize) -> Self {
75        assert!(n >= 2, "a path needs two nodes");
76        let ends: Vec<(usize, usize)> = (0..n - 1).map(|x| (x, x + 1)).collect();
77        let colors: Vec<Vec<usize>> = (0..n)
78            .map(|x| {
79                let mut c = Vec::new();
80                if x + 1 < n {
81                    c.push(x);
82                }
83                if x > 0 {
84                    c.push(x - 1);
85                }
86                c
87            })
88            .collect();
89        Self::new(&ends, &colors)
90    }
91
92    /// Number of nodes, `|V|`.
93    pub fn nodes(&self) -> usize {
94        self.nodes
95    }
96
97    /// Number of edges, `|E|`: one spin each.
98    pub fn edges(&self) -> usize {
99        self.halves.len()
100    }
101
102    /// Number of half-edges, `2|E|`.
103    pub fn half_edges(&self) -> usize {
104        self.half_edges.len()
105    }
106
107    /// Degree of node `x`.
108    pub fn degree(&self, x: usize) -> usize {
109        self.offsets[x + 1] - self.offsets[x]
110    }
111
112    /// Largest degree.
113    pub fn max_degree(&self) -> usize {
114        (0..self.nodes).map(|x| self.degree(x)).max().unwrap_or(0)
115    }
116
117    /// Half-edges of node `x`, in color order.
118    pub fn half_edges_of(&self, x: usize) -> Range<usize> {
119        self.offsets[x]..self.offsets[x + 1]
120    }
121
122    /// The half-edge of color `c` at node `x`.
123    pub fn half_edge(&self, x: usize, c: usize) -> usize {
124        assert!(c < self.degree(x), "node {x} has no color {c}");
125        self.offsets[x] + c
126    }
127
128    /// Node and color of half-edge `h`.
129    pub fn node_and_color(&self, h: usize) -> (usize, usize) {
130        let x = self.half_edges[h].0;
131        (x, h - self.offsets[x])
132    }
133
134    /// Edge of half-edge `h`.
135    pub fn edge_of(&self, h: usize) -> usize {
136        self.half_edges[h].1
137    }
138
139    /// The two half-edges of edge `e`.
140    pub fn halves(&self, e: usize) -> (usize, usize) {
141        self.halves[e]
142    }
143
144    /// The two nodes of edge `e`.
145    pub fn ends(&self, e: usize) -> (usize, usize) {
146        let (a, b) = self.halves[e];
147        (self.half_edges[a].0, self.half_edges[b].0)
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[test]
156    fn cycle_colors() {
157        let g = Graph::cycle(5);
158        assert_eq!((g.nodes(), g.edges(), g.half_edges()), (5, 5, 10));
159        // Edge 2 joins color 0 of node 2 and color 1 of node 3.
160        assert_eq!(g.halves(2), (g.half_edge(2, 0), g.half_edge(3, 1)));
161        assert_eq!(g.ends(4), (4, 0));
162        assert_eq!(g.node_and_color(g.half_edge(4, 1)), (4, 1));
163        assert_eq!(g.edge_of(g.half_edge(0, 1)), 4);
164        // Two nodes: two distinct edges between them.
165        let g = Graph::cycle(2);
166        assert_eq!(g.halves(0), (0, 3));
167        assert_eq!(g.halves(1), (2, 1));
168    }
169
170    #[test]
171    fn path_and_edge_list() {
172        let g = Graph::path(4);
173        assert_eq!((g.edges(), g.degree(0), g.degree(1), g.degree(3)), (3, 1, 2, 1));
174        assert_eq!(g.halves(0), (g.half_edge(0, 0), g.half_edge(1, 1)));
175        let star = Graph::from_edges(4, &[(0, 1), (0, 2), (0, 3)]);
176        assert_eq!((star.degree(0), star.max_degree()), (3, 3));
177        assert_eq!(star.halves(2), (star.half_edge(0, 2), star.half_edge(3, 0)));
178    }
179}