Skip to main content

subgraphsearch_core/
graph.rs

1//! Simple undirected graphs on vertices `0..n`.
2//!
3//! [`Graph`] stores both a bitset adjacency matrix (O(1) edge queries, `n * n / 8` bytes) and
4//! sorted neighbor lists (fast traversal), mirroring the original C programs, which kept a
5//! `char` adjacency matrix alongside adjacency lists for the same reasons.
6
7use std::sync::Arc;
8
9use crate::Error;
10
11/// An undirected graph without self-loops or multiple edges.
12#[derive(Clone, PartialEq, Eq)]
13pub struct Graph {
14    n: usize,
15    words_per_row: usize,
16    bits: Vec<u64>,
17    neighbors: Vec<Vec<u32>>,
18    num_edges: usize,
19}
20
21impl std::fmt::Debug for Graph {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        f.debug_struct("Graph")
24            .field("vertices", &self.n)
25            .field("edges", &self.num_edges)
26            .finish()
27    }
28}
29
30/// Whether bit `v` of an adjacency-matrix row (see [`Graph::row`]) is set, as 0 or 1.
31#[inline(always)]
32pub fn bit(row: &[u64], v: usize) -> u64 {
33    row[v >> 6] >> (v & 63) & 1
34}
35
36/// Incrementally builds a [`Graph`]. Repeated edges are ignored.
37#[derive(Clone, Debug)]
38pub struct GraphBuilder {
39    n: usize,
40    words_per_row: usize,
41    bits: Vec<u64>,
42}
43
44impl GraphBuilder {
45    /// Starts an empty graph on `n` vertices.
46    pub fn new(n: usize) -> Self {
47        let words_per_row = n.div_ceil(64);
48        GraphBuilder {
49            n,
50            words_per_row,
51            bits: vec![0; words_per_row * n],
52        }
53    }
54
55    /// Number of vertices.
56    pub fn num_vertices(&self) -> usize {
57        self.n
58    }
59
60    /// Adds the edge `{u, v}`. Fails if either endpoint is out of range or `u == v`.
61    pub fn add_edge(&mut self, u: usize, v: usize) -> Result<(), Error> {
62        self.check(u)?;
63        self.check(v)?;
64        if u == v {
65            return Err(Error::SelfLoop(u));
66        }
67        self.set(u, v, true);
68        Ok(())
69    }
70
71    /// Sets or clears the edge `{u, v}`; both endpoints must be valid and distinct.
72    pub(crate) fn set(&mut self, u: usize, v: usize, present: bool) {
73        let (wu, bu) = (u * self.words_per_row + v / 64, 1u64 << (v % 64));
74        let (wv, bv) = (v * self.words_per_row + u / 64, 1u64 << (u % 64));
75        if present {
76            self.bits[wu] |= bu;
77            self.bits[wv] |= bv;
78        } else {
79            self.bits[wu] &= !bu;
80            self.bits[wv] &= !bv;
81        }
82    }
83
84    pub(crate) fn get(&self, u: usize, v: usize) -> bool {
85        self.bits[u * self.words_per_row + v / 64] >> (v % 64) & 1 == 1
86    }
87
88    fn check(&self, v: usize) -> Result<(), Error> {
89        if v >= self.n {
90            return Err(Error::VertexOutOfRange {
91                vertex: v as i64,
92                n: self.n,
93            });
94        }
95        Ok(())
96    }
97
98    /// Finishes the graph, computing sorted neighbor lists.
99    pub fn build(self) -> Graph {
100        let GraphBuilder {
101            n,
102            words_per_row,
103            bits,
104        } = self;
105        let mut neighbors = Vec::with_capacity(n);
106        let mut twice_edges = 0;
107        for u in 0..n {
108            let row = &bits[u * words_per_row..(u + 1) * words_per_row];
109            let mut list = Vec::new();
110            for (w, &word) in row.iter().enumerate() {
111                let mut word = word;
112                while word != 0 {
113                    let b = word.trailing_zeros() as usize;
114                    list.push((w * 64 + b) as u32);
115                    word &= word - 1;
116                }
117            }
118            twice_edges += list.len();
119            neighbors.push(list);
120        }
121        Graph {
122            n,
123            words_per_row,
124            bits,
125            neighbors,
126            num_edges: twice_edges / 2,
127        }
128    }
129}
130
131impl Graph {
132    /// The graph on integer vectors of length `dim`, held one after another in `vectors`, with two
133    /// joined when their inner product is one of `allowed`.
134    ///
135    /// Sets of vectors with prescribed inner products are then cliques: rows of a Hadamard matrix
136    /// are pairwise orthogonal (`allowed = [0]`), equiangular lines have inner products `±c`. The
137    /// inner products are computed in parallel straight into the adjacency matrix, so no edge list
138    /// is built, which matters when there are hundreds of millions of edges. Entries must be small
139    /// enough that inner products fit an `i64`.
140    pub fn from_vectors(vectors: &[i64], dim: usize, allowed: &[i64]) -> Result<Graph, Error> {
141        use rayon::prelude::*;
142
143        if dim == 0 || !vectors.len().is_multiple_of(dim) {
144            return Err(Error::Invalid(format!(
145                "{} entries are not a whole number of vectors of length {dim}",
146                vectors.len()
147            )));
148        }
149        let n = vectors.len() / dim;
150        let mut allowed = allowed.to_vec();
151        allowed.sort_unstable();
152        allowed.dedup();
153        let mut b = GraphBuilder::new(n);
154        let words_per_row = b.words_per_row;
155        if words_per_row > 0 {
156            b.bits
157                .par_chunks_mut(words_per_row)
158                .enumerate()
159                .for_each(|(u, row)| {
160                    let x = &vectors[u * dim..(u + 1) * dim];
161                    for (v, y) in vectors.chunks_exact(dim).enumerate() {
162                        if v == u {
163                            continue;
164                        }
165                        let dot: i64 = x.iter().zip(y).map(|(a, b)| a * b).sum();
166                        if allowed.binary_search(&dot).is_ok() {
167                            row[v / 64] |= 1 << (v % 64);
168                        }
169                    }
170                });
171        }
172        Ok(b.build())
173    }
174
175    /// The graph on binary words of up to 64 bits, each given as an integer whose bit `i` is the
176    /// word's `i`-th entry, with two joined when their Hamming distance (the number of places in
177    /// which they differ) is one of `distances`.
178    ///
179    /// A binary code of minimum distance `d` is then a clique when `distances` is `d..=len`, and an
180    /// independent set in the graph with `distances` `1..d`. Distances are computed in parallel
181    /// straight into the adjacency matrix, each as one exclusive or and a bit count.
182    pub fn from_words(words: &[u64], distances: &[u32]) -> Graph {
183        use rayon::prelude::*;
184
185        let n = words.len();
186        let mut wanted = [false; 65];
187        for &d in distances {
188            if let Some(slot) = wanted.get_mut(d as usize) {
189                *slot = true;
190            }
191        }
192        let mut b = GraphBuilder::new(n);
193        let words_per_row = b.words_per_row;
194        if words_per_row > 0 {
195            b.bits
196                .par_chunks_mut(words_per_row)
197                .enumerate()
198                .for_each(|(u, row)| {
199                    let x = words[u];
200                    for (v, &y) in words.iter().enumerate() {
201                        if v != u && wanted[(x ^ y).count_ones() as usize] {
202                            row[v / 64] |= 1 << (v % 64);
203                        }
204                    }
205                });
206        }
207        b.build()
208    }
209
210    /// Builds a graph on `n` vertices from an edge list.
211    pub fn from_edges<I>(n: usize, edges: I) -> Result<Graph, Error>
212    where
213        I: IntoIterator<Item = (usize, usize)>,
214    {
215        let mut b = GraphBuilder::new(n);
216        for (u, v) in edges {
217            b.add_edge(u, v)?;
218        }
219        Ok(b.build())
220    }
221
222    /// The empty graph on `n` vertices.
223    pub fn empty(n: usize) -> Graph {
224        GraphBuilder::new(n).build()
225    }
226
227    /// Number of vertices.
228    #[inline]
229    pub fn num_vertices(&self) -> usize {
230        self.n
231    }
232
233    /// Number of edges.
234    #[inline]
235    pub fn num_edges(&self) -> usize {
236        self.num_edges
237    }
238
239    /// Whether `{u, v}` is an edge. Panics if either vertex is out of range.
240    #[inline]
241    pub fn has_edge(&self, u: usize, v: usize) -> bool {
242        self.bits[u * self.words_per_row + v / 64] >> (v % 64) & 1 == 1
243    }
244
245    /// Row `u` of the adjacency matrix as a bitset: bit `v % 64` of word `v / 64` is set iff
246    /// `{u, v}` is an edge. Test bits with [`bit`].
247    #[inline]
248    pub fn row(&self, u: usize) -> &[u64] {
249        &self.bits[u * self.words_per_row..(u + 1) * self.words_per_row]
250    }
251
252    /// The neighbors of `u`, in ascending order.
253    #[inline]
254    pub fn neighbors(&self, u: usize) -> &[u32] {
255        &self.neighbors[u]
256    }
257
258    /// The degree of `u`.
259    #[inline]
260    pub fn degree(&self, u: usize) -> usize {
261        self.neighbors[u].len()
262    }
263
264    /// All degrees, indexed by vertex.
265    pub fn degrees(&self) -> Vec<usize> {
266        self.neighbors.iter().map(Vec::len).collect()
267    }
268
269    /// Edges `(u, v)` with `u < v`, in lexicographic order.
270    pub fn edges(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
271        self.neighbors.iter().enumerate().flat_map(|(u, list)| {
272            list.iter()
273                .map(|&v| v as usize)
274                .filter(move |&v| v > u)
275                .map(move |v| (u, v))
276        })
277    }
278
279    /// Edge density `m / (n choose 2)`, or 0 for graphs with fewer than two vertices.
280    pub fn density(&self) -> f64 {
281        if self.n < 2 {
282            return 0.0;
283        }
284        self.num_edges as f64 / (self.n as f64 * (self.n as f64 - 1.0) / 2.0)
285    }
286
287    /// Converts back into a builder, e.g. to modify the graph.
288    pub fn into_builder(self) -> GraphBuilder {
289        GraphBuilder {
290            n: self.n,
291            words_per_row: self.words_per_row,
292            bits: self.bits,
293        }
294    }
295
296    /// Number of edges among `vertices`, which must be distinct.
297    pub fn induced_edge_count(&self, vertices: &[usize]) -> usize {
298        let mut count = 0;
299        for (i, &u) in vertices.iter().enumerate() {
300            for &v in &vertices[i + 1..] {
301                if self.has_edge(u, v) {
302                    count += 1;
303                }
304            }
305        }
306        count
307    }
308
309    /// Connected components, as a component index per vertex plus the number of components.
310    pub fn components(&self) -> (Vec<usize>, usize) {
311        let mut comp = vec![usize::MAX; self.n];
312        let mut count = 0;
313        let mut stack = Vec::new();
314        for s in 0..self.n {
315            if comp[s] != usize::MAX {
316                continue;
317            }
318            comp[s] = count;
319            stack.push(s);
320            while let Some(u) = stack.pop() {
321                for &v in self.neighbors(u) {
322                    let v = v as usize;
323                    if comp[v] == usize::MAX {
324                        comp[v] = count;
325                        stack.push(v);
326                    }
327                }
328            }
329            count += 1;
330        }
331        (comp, count)
332    }
333}
334
335/// The real-valued scores a [`WeightedGraph`] was made from with [`WeightedGraph::from_scores`]:
336/// an `n x n` row-major matrix, 0 for pairs without a score, shared between copies of the graph.
337/// Compared bit for bit, so that graphs stay `Eq`.
338#[derive(Clone)]
339struct Scores(Arc<Vec<f64>>);
340
341impl PartialEq for Scores {
342    fn eq(&self, other: &Self) -> bool {
343        Arc::ptr_eq(&self.0, &other.0)
344            || (self.0.len() == other.0.len()
345                && self
346                    .0
347                    .iter()
348                    .zip(other.0.iter())
349                    .all(|(a, b)| a.to_bits() == b.to_bits()))
350    }
351}
352
353impl Eq for Scores {}
354
355/// An undirected graph whose edges carry small positive integer weights (1 to 255), as used by
356/// the original `wsub_search` and `wggen`. Weights live in an `n x n` byte matrix (O(1) lookup, `n * n`
357/// bytes) alongside sorted neighbor lists. A graph made from real-valued scores with
358/// [`WeightedGraph::from_scores`] also keeps those scores (`8 * n * n` bytes), so that results can be
359/// totalled exactly ([`WeightedGraph::induced_score`]).
360#[derive(Clone, PartialEq, Eq)]
361pub struct WeightedGraph {
362    n: usize,
363    weights: Vec<u8>,
364    neighbors: Vec<Vec<u32>>,
365    /// The largest weight in each row.
366    row_max: Vec<u8>,
367    num_edges: usize,
368    total_weight: u64,
369    /// With [`WeightedGraph::from_scores`]: the scores the weights were rounded from.
370    scores: Option<Scores>,
371}
372
373impl std::fmt::Debug for WeightedGraph {
374    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
375        f.debug_struct("WeightedGraph")
376            .field("vertices", &self.n)
377            .field("edges", &self.num_edges)
378            .field("total_weight", &self.total_weight)
379            .finish()
380    }
381}
382
383impl WeightedGraph {
384    /// Builds a weighted graph from `(u, v, weight)` triples. Weights must be between 1 and
385    /// 255; if an edge is listed more than once, the last weight given wins.
386    pub fn from_weighted_edges<I>(n: usize, edges: I) -> Result<WeightedGraph, Error>
387    where
388        I: IntoIterator<Item = (usize, usize, u32)>,
389    {
390        let mut weights = vec![0u8; n * n];
391        for (u, v, w) in edges {
392            for x in [u, v] {
393                if x >= n {
394                    return Err(Error::VertexOutOfRange {
395                        vertex: x as i64,
396                        n,
397                    });
398                }
399            }
400            if u == v {
401                return Err(Error::SelfLoop(u));
402            }
403            if !(1..=255).contains(&w) {
404                return Err(Error::Invalid(format!(
405                    "edge {{{u}, {v}}} has weight {w}; weights must be between 1 and 255"
406                )));
407            }
408            weights[u * n + v] = w as u8;
409            weights[v * n + u] = w as u8;
410        }
411        Ok(Self::from_matrix(n, weights))
412    }
413
414    /// Builds a weighted graph from real-valued, non-negative scores between pairs of vertices,
415    /// such as distances or similarities, given as `(u, v, score)` triples, and returns it with the
416    /// factor the scores were scaled by. Weights are integers from 1 to 255, so each score is
417    /// multiplied by `resolution / largest score` and rounded (ties to even): the largest becomes
418    /// `resolution`, at most 255. A positive score too small to survive rounding keeps weight 1, and
419    /// a score of 0 is no edge. A total weight `t` stands for scores totalling about `t / factor`;
420    /// the graph keeps the scores, so [`WeightedGraph::induced_score`] gives the exact total. If a
421    /// pair is listed more than once, the last score given wins.
422    pub fn from_scores<I>(
423        n: usize,
424        scores: I,
425        resolution: u32,
426    ) -> Result<(WeightedGraph, f64), Error>
427    where
428        I: IntoIterator<Item = (usize, usize, f64)>,
429    {
430        if !(1..=255).contains(&resolution) {
431            return Err(Error::Invalid(
432                "resolution must be from 1 to 255, the range of weights".into(),
433            ));
434        }
435        let mut matrix = vec![0.0f64; n * n];
436        for (u, v, score) in scores {
437            for x in [u, v] {
438                if x >= n {
439                    return Err(Error::VertexOutOfRange {
440                        vertex: x as i64,
441                        n,
442                    });
443                }
444            }
445            if !score.is_finite() || score < 0.0 {
446                return Err(Error::Invalid(format!(
447                    "the score of {{{u}, {v}}} is {score}; scores must be finite and non-negative"
448                )));
449            }
450            if u == v {
451                if score != 0.0 {
452                    return Err(Error::SelfLoop(u));
453                }
454                continue;
455            }
456            matrix[u * n + v] = score;
457            matrix[v * n + u] = score;
458        }
459        let top = matrix.iter().copied().fold(0.0, f64::max);
460        let factor = if top > 0.0 {
461            f64::from(resolution) / top
462        } else {
463            1.0
464        };
465        let weights = matrix
466            .iter()
467            .map(|&s| {
468                if s == 0.0 {
469                    0
470                } else {
471                    ((s * factor).round_ties_even() as u8).max(1)
472                }
473            })
474            .collect();
475        let mut g = Self::from_matrix(n, weights);
476        g.scores = Some(Scores(Arc::new(matrix)));
477        Ok((g, factor))
478    }
479
480    /// The scores the graph was made from with [`WeightedGraph::from_scores`], as an `n x n`
481    /// row-major matrix (0 for pairs without a score), or `None` for other graphs.
482    pub fn scores(&self) -> Option<&[f64]> {
483        self.scores.as_ref().map(|s| &s.0[..])
484    }
485
486    /// The total score of the pairs among `vertices`, from the scores the graph was made from: the
487    /// exact counterpart of [`WeightedGraph::induced_weight`]. `None` for graphs without scores.
488    pub fn induced_score(&self, vertices: &[usize]) -> Option<f64> {
489        let scores = self.scores()?;
490        let mut total = 0.0;
491        for (i, &u) in vertices.iter().enumerate() {
492            let row = &scores[u * self.n..(u + 1) * self.n];
493            total += vertices[i + 1..].iter().map(|&v| row[v]).sum::<f64>();
494        }
495        Some(total)
496    }
497
498    /// Every edge of `g` with weight 1.
499    pub fn from_graph(g: &Graph) -> WeightedGraph {
500        let n = g.num_vertices();
501        Self::from_weighted_edges(n, g.edges().map(|(u, v)| (u, v, 1))).unwrap()
502    }
503
504    pub(crate) fn from_matrix(n: usize, weights: Vec<u8>) -> WeightedGraph {
505        let mut neighbors = Vec::with_capacity(n);
506        let mut row_max = Vec::with_capacity(n);
507        let (mut twice_edges, mut twice_weight) = (0usize, 0u64);
508        for u in 0..n {
509            let row = &weights[u * n..(u + 1) * n];
510            let list: Vec<u32> = (0..n).filter(|&v| row[v] != 0).map(|v| v as u32).collect();
511            twice_edges += list.len();
512            twice_weight += row.iter().map(|&w| u64::from(w)).sum::<u64>();
513            row_max.push(row.iter().copied().max().unwrap_or(0));
514            neighbors.push(list);
515        }
516        WeightedGraph {
517            n,
518            weights,
519            neighbors,
520            row_max,
521            num_edges: twice_edges / 2,
522            total_weight: twice_weight / 2,
523            scores: None,
524        }
525    }
526
527    /// Number of vertices.
528    #[inline]
529    pub fn num_vertices(&self) -> usize {
530        self.n
531    }
532
533    /// Number of edges.
534    #[inline]
535    pub fn num_edges(&self) -> usize {
536        self.num_edges
537    }
538
539    /// Sum of all edge weights.
540    #[inline]
541    pub fn total_weight(&self) -> u64 {
542        self.total_weight
543    }
544
545    /// The largest weight of an edge at `u`, or 0 if it has none.
546    #[inline]
547    pub fn max_weight_at(&self, u: usize) -> u8 {
548        self.row_max[u]
549    }
550
551    /// The weight of `{u, v}`, or 0 if it is not an edge.
552    #[inline]
553    pub fn weight(&self, u: usize, v: usize) -> u8 {
554        self.weights[u * self.n + v]
555    }
556
557    /// Row `u` of the weight matrix.
558    #[inline]
559    pub fn row(&self, u: usize) -> &[u8] {
560        &self.weights[u * self.n..(u + 1) * self.n]
561    }
562
563    /// The neighbors of `u`, in ascending order.
564    #[inline]
565    pub fn neighbors(&self, u: usize) -> &[u32] {
566        &self.neighbors[u]
567    }
568
569    /// Edges `(u, v, weight)` with `u < v`, in lexicographic order.
570    pub fn edges(&self) -> impl Iterator<Item = (usize, usize, u8)> + '_ {
571        self.neighbors
572            .iter()
573            .enumerate()
574            .flat_map(move |(u, list)| {
575                list.iter()
576                    .map(|&v| v as usize)
577                    .filter(move |&v| v > u)
578                    .map(move |v| (u, v, self.weight(u, v)))
579            })
580    }
581
582    /// Total weight of the edges among `vertices`, which must be distinct.
583    pub fn induced_weight(&self, vertices: &[usize]) -> u64 {
584        let mut total = 0;
585        for (i, &u) in vertices.iter().enumerate() {
586            for &v in &vertices[i + 1..] {
587                total += u64::from(self.weight(u, v));
588            }
589        }
590        total
591    }
592
593    /// The underlying unweighted graph.
594    pub fn structure(&self) -> Graph {
595        Graph::from_edges(self.n, self.edges().map(|(u, v, _)| (u, v))).unwrap()
596    }
597}
598
599#[cfg(test)]
600mod tests {
601    use super::*;
602
603    #[test]
604    fn scores_become_weights_and_stay_exact() {
605        let (w, factor) =
606            WeightedGraph::from_scores(3, [(0, 1, 2.5), (1, 2, 1.0), (0, 2, 0.01)], 255).unwrap();
607        // the largest score becomes 255; 1.0 rounds to 102; 0.01 would round to 0, so keeps 1
608        assert_eq!(
609            (w.weight(0, 1), w.weight(1, 2), w.weight(0, 2)),
610            (255, 102, 1)
611        );
612        assert_eq!(factor, 102.0);
613        assert_eq!(w.induced_weight(&[0, 1, 2]), 358);
614        assert!((w.induced_score(&[0, 1, 2]).unwrap() - 3.51).abs() < 1e-12);
615        assert_eq!(w.scores().unwrap()[1], 2.5);
616        // ties round to even, as numpy's rint does: 0.5 and 1.5 become 0 (so 1) and 2
617        let (w, _) =
618            WeightedGraph::from_scores(3, [(0, 1, 4.0), (1, 2, 1.5), (0, 2, 0.5)], 4).unwrap();
619        assert_eq!((w.weight(1, 2), w.weight(0, 2)), (2, 1));
620        // a score of 0 is no edge; graphs not made from scores have none
621        let (w, _) = WeightedGraph::from_scores(3, [(0, 1, 1.0), (1, 2, 0.0)], 255).unwrap();
622        assert_eq!(w.num_edges(), 1);
623        let plain = WeightedGraph::from_weighted_edges(3, [(0, 1, 5)]).unwrap();
624        assert_eq!((plain.scores(), plain.induced_score(&[0, 1])), (None, None));
625        for bad in [-1.0, f64::NAN, f64::INFINITY] {
626            assert!(WeightedGraph::from_scores(2, [(0, 1, bad)], 255).is_err());
627        }
628        assert!(WeightedGraph::from_scores(2, [(0, 2, 1.0)], 255).is_err());
629        assert!(WeightedGraph::from_scores(2, [(1, 1, 1.0)], 255).is_err());
630        assert!(WeightedGraph::from_scores(2, [(0, 1, 1.0)], 0).is_err());
631    }
632
633    #[test]
634    fn graphs_of_words_join_allowed_distances() {
635        // all 3-bit words: distance 3 joins each word to its complement, distances 2 and 3 give the
636        // complement of the 3-cube
637        let words: Vec<u64> = (0..8).collect();
638        let opposite = Graph::from_words(&words, &[3]);
639        assert_eq!(opposite.num_edges(), 4);
640        assert!(opposite.has_edge(0b000, 0b111) && opposite.has_edge(0b010, 0b101));
641        let cube = Graph::from_words(&words, &[1]);
642        assert_eq!(cube.num_edges(), 12);
643        assert_eq!(Graph::from_words(&words, &[2, 3]).num_edges(), 28 - 12);
644        // the same as distances from inner products of +-1 vectors, n - 2t
645        let signs: Vec<i64> = words
646            .iter()
647            .flat_map(|w| (0..3).map(move |b| if w >> b & 1 == 1 { -1 } else { 1 }))
648            .collect();
649        assert_eq!(
650            Graph::from_vectors(&signs, 3, &[-1, -3]).unwrap(),
651            Graph::from_words(&words, &[2, 3])
652        );
653        assert_eq!(Graph::from_words(&[], &[1]).num_vertices(), 0);
654        assert_eq!(Graph::from_words(&words, &[70]).num_edges(), 0);
655    }
656
657    #[test]
658    fn graphs_of_vectors_join_allowed_inner_products() {
659        // the 8 vectors of {+-1}^3: orthogonal pairs never occur (inner products are odd), and
660        // inner product -3 joins each vector to its negation
661        let cube: Vec<i64> = (0..8)
662            .flat_map(|i| (0..3).map(move |b| if i >> b & 1 == 1 { -1 } else { 1 }))
663            .collect();
664        assert_eq!(Graph::from_vectors(&cube, 3, &[0]).unwrap().num_edges(), 0);
665        let opposite = Graph::from_vectors(&cube, 3, &[-3]).unwrap();
666        assert_eq!(opposite.num_edges(), 4);
667        assert!(opposite.has_edge(0, 7) && opposite.has_edge(2, 5));
668        // inner products 1 and -1 join vectors differing in one or two places: 8 * (3 + 3) / 2 pairs
669        let near = Graph::from_vectors(&cube, 3, &[1, -1, 1]).unwrap();
670        assert_eq!(near.num_edges(), 24);
671        // the same as computing every pair by hand, on vectors with more than 64 rows
672        let many: Vec<i64> = (0..100i64)
673            .flat_map(|i| [i % 3 - 1, i % 5 - 2, i % 7 - 3])
674            .collect();
675        let g = Graph::from_vectors(&many, 3, &[0, 2]).unwrap();
676        let dot = |u: usize, v: usize| {
677            (0..3)
678                .map(|k| many[3 * u + k] * many[3 * v + k])
679                .sum::<i64>()
680        };
681        for u in 0..100 {
682            for v in 0..100 {
683                assert_eq!(
684                    g.has_edge(u, v),
685                    u != v && [0, 2].contains(&dot(u, v)),
686                    "{u} {v}"
687                );
688            }
689        }
690        assert!(Graph::from_vectors(&[1, 2, 3], 2, &[0]).is_err());
691        assert!(Graph::from_vectors(&[1, 2], 0, &[0]).is_err());
692        assert_eq!(Graph::from_vectors(&[], 4, &[0]).unwrap().num_vertices(), 0);
693    }
694
695    #[test]
696    fn builds_sorted_symmetric_neighbor_lists() {
697        let g = Graph::from_edges(70, [(3, 1), (1, 65), (1, 3), (0, 69)]).unwrap();
698        assert_eq!(g.num_edges(), 3);
699        assert_eq!(g.neighbors(1), &[3, 65]);
700        assert_eq!(g.neighbors(65), &[1]);
701        assert!(g.has_edge(69, 0) && !g.has_edge(2, 3));
702        assert_eq!(
703            g.edges().collect::<Vec<_>>(),
704            vec![(0, 69), (1, 3), (1, 65)]
705        );
706    }
707
708    #[test]
709    fn rejects_bad_edges() {
710        assert!(matches!(
711            Graph::from_edges(3, [(0, 3)]),
712            Err(Error::VertexOutOfRange { .. })
713        ));
714        assert!(matches!(
715            Graph::from_edges(3, [(1, 1)]),
716            Err(Error::SelfLoop(1))
717        ));
718    }
719
720    #[test]
721    fn weighted_graphs() {
722        let g = WeightedGraph::from_weighted_edges(4, [(0, 1, 3), (2, 1, 5), (0, 1, 2)]).unwrap();
723        assert_eq!((g.num_edges(), g.total_weight()), (2, 7));
724        assert_eq!((g.weight(1, 0), g.weight(1, 2), g.weight(0, 3)), (2, 5, 0));
725        assert_eq!(g.edges().collect::<Vec<_>>(), vec![(0, 1, 2), (1, 2, 5)]);
726        assert_eq!(g.induced_weight(&[0, 1, 2]), 7);
727        assert_eq!(g.structure().num_edges(), 2);
728        assert_eq!(WeightedGraph::from_graph(&g.structure()).total_weight(), 2);
729        assert!(WeightedGraph::from_weighted_edges(3, [(0, 1, 0)]).is_err());
730        assert!(WeightedGraph::from_weighted_edges(3, [(0, 1, 256)]).is_err());
731    }
732
733    #[test]
734    fn counts_components() {
735        let g = Graph::from_edges(6, [(0, 1), (1, 2), (4, 5)]).unwrap();
736        assert_eq!(g.components().1, 3);
737        assert_eq!(g.induced_edge_count(&[0, 1, 2, 4]), 2);
738    }
739}