subgraphsearch-core 4.4.3

Randomized tabu search for induced subgraphs with a given number of vertices and edges, or regular ones, plus graph generators and formats
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! Simple undirected graphs on vertices `0..n`.
//!
//! [`Graph`] stores both a bitset adjacency matrix (O(1) edge queries, `n * n / 8` bytes) and
//! sorted neighbor lists (fast traversal), mirroring the original C programs, which kept a
//! `char` adjacency matrix alongside adjacency lists for the same reasons.

use std::sync::Arc;

use crate::Error;

/// An undirected graph without self-loops or multiple edges.
#[derive(Clone, PartialEq, Eq)]
pub struct Graph {
    n: usize,
    words_per_row: usize,
    bits: Vec<u64>,
    neighbors: Vec<Vec<u32>>,
    num_edges: usize,
}

impl std::fmt::Debug for Graph {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Graph")
            .field("vertices", &self.n)
            .field("edges", &self.num_edges)
            .finish()
    }
}

/// Whether bit `v` of an adjacency-matrix row (see [`Graph::row`]) is set, as 0 or 1.
#[inline(always)]
pub fn bit(row: &[u64], v: usize) -> u64 {
    row[v >> 6] >> (v & 63) & 1
}

/// Incrementally builds a [`Graph`]. Repeated edges are ignored.
#[derive(Clone, Debug)]
pub struct GraphBuilder {
    n: usize,
    words_per_row: usize,
    bits: Vec<u64>,
}

impl GraphBuilder {
    /// Starts an empty graph on `n` vertices.
    pub fn new(n: usize) -> Self {
        let words_per_row = n.div_ceil(64);
        GraphBuilder {
            n,
            words_per_row,
            bits: vec![0; words_per_row * n],
        }
    }

    /// Number of vertices.
    pub fn num_vertices(&self) -> usize {
        self.n
    }

    /// Adds the edge `{u, v}`. Fails if either endpoint is out of range or `u == v`.
    pub fn add_edge(&mut self, u: usize, v: usize) -> Result<(), Error> {
        self.check(u)?;
        self.check(v)?;
        if u == v {
            return Err(Error::SelfLoop(u));
        }
        self.set(u, v, true);
        Ok(())
    }

    /// Sets or clears the edge `{u, v}`; both endpoints must be valid and distinct.
    pub(crate) fn set(&mut self, u: usize, v: usize, present: bool) {
        let (wu, bu) = (u * self.words_per_row + v / 64, 1u64 << (v % 64));
        let (wv, bv) = (v * self.words_per_row + u / 64, 1u64 << (u % 64));
        if present {
            self.bits[wu] |= bu;
            self.bits[wv] |= bv;
        } else {
            self.bits[wu] &= !bu;
            self.bits[wv] &= !bv;
        }
    }

    pub(crate) fn get(&self, u: usize, v: usize) -> bool {
        self.bits[u * self.words_per_row + v / 64] >> (v % 64) & 1 == 1
    }

    fn check(&self, v: usize) -> Result<(), Error> {
        if v >= self.n {
            return Err(Error::VertexOutOfRange {
                vertex: v as i64,
                n: self.n,
            });
        }
        Ok(())
    }

    /// Finishes the graph, computing sorted neighbor lists.
    pub fn build(self) -> Graph {
        let GraphBuilder {
            n,
            words_per_row,
            bits,
        } = self;
        let mut neighbors = Vec::with_capacity(n);
        let mut twice_edges = 0;
        for u in 0..n {
            let row = &bits[u * words_per_row..(u + 1) * words_per_row];
            let mut list = Vec::new();
            for (w, &word) in row.iter().enumerate() {
                let mut word = word;
                while word != 0 {
                    let b = word.trailing_zeros() as usize;
                    list.push((w * 64 + b) as u32);
                    word &= word - 1;
                }
            }
            twice_edges += list.len();
            neighbors.push(list);
        }
        Graph {
            n,
            words_per_row,
            bits,
            neighbors,
            num_edges: twice_edges / 2,
        }
    }
}

impl Graph {
    /// The graph on integer vectors of length `dim`, held one after another in `vectors`, with two
    /// joined when their inner product is one of `allowed`.
    ///
    /// Sets of vectors with prescribed inner products are then cliques: rows of a Hadamard matrix
    /// are pairwise orthogonal (`allowed = [0]`), equiangular lines have inner products `±c`. The
    /// inner products are computed in parallel straight into the adjacency matrix, so no edge list
    /// is built, which matters when there are hundreds of millions of edges. Entries must be small
    /// enough that inner products fit an `i64`.
    pub fn from_vectors(vectors: &[i64], dim: usize, allowed: &[i64]) -> Result<Graph, Error> {
        use rayon::prelude::*;

        if dim == 0 || !vectors.len().is_multiple_of(dim) {
            return Err(Error::Invalid(format!(
                "{} entries are not a whole number of vectors of length {dim}",
                vectors.len()
            )));
        }
        let n = vectors.len() / dim;
        let mut allowed = allowed.to_vec();
        allowed.sort_unstable();
        allowed.dedup();
        let mut b = GraphBuilder::new(n);
        let words_per_row = b.words_per_row;
        if words_per_row > 0 {
            b.bits
                .par_chunks_mut(words_per_row)
                .enumerate()
                .for_each(|(u, row)| {
                    let x = &vectors[u * dim..(u + 1) * dim];
                    for (v, y) in vectors.chunks_exact(dim).enumerate() {
                        if v == u {
                            continue;
                        }
                        let dot: i64 = x.iter().zip(y).map(|(a, b)| a * b).sum();
                        if allowed.binary_search(&dot).is_ok() {
                            row[v / 64] |= 1 << (v % 64);
                        }
                    }
                });
        }
        Ok(b.build())
    }

    /// The graph on binary words of up to 64 bits, each given as an integer whose bit `i` is the
    /// word's `i`-th entry, with two joined when their Hamming distance (the number of places in
    /// which they differ) is one of `distances`.
    ///
    /// A binary code of minimum distance `d` is then a clique when `distances` is `d..=len`, and an
    /// independent set in the graph with `distances` `1..d`. Distances are computed in parallel
    /// straight into the adjacency matrix, each as one exclusive or and a bit count.
    pub fn from_words(words: &[u64], distances: &[u32]) -> Graph {
        use rayon::prelude::*;

        let n = words.len();
        let mut wanted = [false; 65];
        for &d in distances {
            if let Some(slot) = wanted.get_mut(d as usize) {
                *slot = true;
            }
        }
        let mut b = GraphBuilder::new(n);
        let words_per_row = b.words_per_row;
        if words_per_row > 0 {
            b.bits
                .par_chunks_mut(words_per_row)
                .enumerate()
                .for_each(|(u, row)| {
                    let x = words[u];
                    for (v, &y) in words.iter().enumerate() {
                        if v != u && wanted[(x ^ y).count_ones() as usize] {
                            row[v / 64] |= 1 << (v % 64);
                        }
                    }
                });
        }
        b.build()
    }

    /// Builds a graph on `n` vertices from an edge list.
    pub fn from_edges<I>(n: usize, edges: I) -> Result<Graph, Error>
    where
        I: IntoIterator<Item = (usize, usize)>,
    {
        let mut b = GraphBuilder::new(n);
        for (u, v) in edges {
            b.add_edge(u, v)?;
        }
        Ok(b.build())
    }

    /// The empty graph on `n` vertices.
    pub fn empty(n: usize) -> Graph {
        GraphBuilder::new(n).build()
    }

    /// Number of vertices.
    #[inline]
    pub fn num_vertices(&self) -> usize {
        self.n
    }

    /// Number of edges.
    #[inline]
    pub fn num_edges(&self) -> usize {
        self.num_edges
    }

    /// Whether `{u, v}` is an edge. Panics if either vertex is out of range.
    #[inline]
    pub fn has_edge(&self, u: usize, v: usize) -> bool {
        self.bits[u * self.words_per_row + v / 64] >> (v % 64) & 1 == 1
    }

    /// Row `u` of the adjacency matrix as a bitset: bit `v % 64` of word `v / 64` is set iff
    /// `{u, v}` is an edge. Test bits with [`bit`].
    #[inline]
    pub fn row(&self, u: usize) -> &[u64] {
        &self.bits[u * self.words_per_row..(u + 1) * self.words_per_row]
    }

    /// The neighbors of `u`, in ascending order.
    #[inline]
    pub fn neighbors(&self, u: usize) -> &[u32] {
        &self.neighbors[u]
    }

    /// The degree of `u`.
    #[inline]
    pub fn degree(&self, u: usize) -> usize {
        self.neighbors[u].len()
    }

    /// All degrees, indexed by vertex.
    pub fn degrees(&self) -> Vec<usize> {
        self.neighbors.iter().map(Vec::len).collect()
    }

    /// Edges `(u, v)` with `u < v`, in lexicographic order.
    pub fn edges(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
        self.neighbors.iter().enumerate().flat_map(|(u, list)| {
            list.iter()
                .map(|&v| v as usize)
                .filter(move |&v| v > u)
                .map(move |v| (u, v))
        })
    }

    /// Edge density `m / (n choose 2)`, or 0 for graphs with fewer than two vertices.
    pub fn density(&self) -> f64 {
        if self.n < 2 {
            return 0.0;
        }
        self.num_edges as f64 / (self.n as f64 * (self.n as f64 - 1.0) / 2.0)
    }

    /// Converts back into a builder, e.g. to modify the graph.
    pub fn into_builder(self) -> GraphBuilder {
        GraphBuilder {
            n: self.n,
            words_per_row: self.words_per_row,
            bits: self.bits,
        }
    }

    /// Number of edges among `vertices`, which must be distinct.
    pub fn induced_edge_count(&self, vertices: &[usize]) -> usize {
        let mut count = 0;
        for (i, &u) in vertices.iter().enumerate() {
            for &v in &vertices[i + 1..] {
                if self.has_edge(u, v) {
                    count += 1;
                }
            }
        }
        count
    }

    /// Connected components, as a component index per vertex plus the number of components.
    pub fn components(&self) -> (Vec<usize>, usize) {
        let mut comp = vec![usize::MAX; self.n];
        let mut count = 0;
        let mut stack = Vec::new();
        for s in 0..self.n {
            if comp[s] != usize::MAX {
                continue;
            }
            comp[s] = count;
            stack.push(s);
            while let Some(u) = stack.pop() {
                for &v in self.neighbors(u) {
                    let v = v as usize;
                    if comp[v] == usize::MAX {
                        comp[v] = count;
                        stack.push(v);
                    }
                }
            }
            count += 1;
        }
        (comp, count)
    }
}

/// The real-valued scores a [`WeightedGraph`] was made from with [`WeightedGraph::from_scores`]:
/// an `n x n` row-major matrix, 0 for pairs without a score, shared between copies of the graph.
/// Compared bit for bit, so that graphs stay `Eq`.
#[derive(Clone)]
struct Scores(Arc<Vec<f64>>);

impl PartialEq for Scores {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
            || (self.0.len() == other.0.len()
                && self
                    .0
                    .iter()
                    .zip(other.0.iter())
                    .all(|(a, b)| a.to_bits() == b.to_bits()))
    }
}

impl Eq for Scores {}

/// An undirected graph whose edges carry small positive integer weights (1 to 255), as used by
/// the original `wsub_search` and `wggen`. Weights live in an `n x n` byte matrix (O(1) lookup, `n * n`
/// bytes) alongside sorted neighbor lists. A graph made from real-valued scores with
/// [`WeightedGraph::from_scores`] also keeps those scores (`8 * n * n` bytes), so that results can be
/// totalled exactly ([`WeightedGraph::induced_score`]).
#[derive(Clone, PartialEq, Eq)]
pub struct WeightedGraph {
    n: usize,
    weights: Vec<u8>,
    neighbors: Vec<Vec<u32>>,
    /// The largest weight in each row.
    row_max: Vec<u8>,
    num_edges: usize,
    total_weight: u64,
    /// With [`WeightedGraph::from_scores`]: the scores the weights were rounded from.
    scores: Option<Scores>,
}

impl std::fmt::Debug for WeightedGraph {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WeightedGraph")
            .field("vertices", &self.n)
            .field("edges", &self.num_edges)
            .field("total_weight", &self.total_weight)
            .finish()
    }
}

impl WeightedGraph {
    /// Builds a weighted graph from `(u, v, weight)` triples. Weights must be between 1 and
    /// 255; if an edge is listed more than once, the last weight given wins.
    pub fn from_weighted_edges<I>(n: usize, edges: I) -> Result<WeightedGraph, Error>
    where
        I: IntoIterator<Item = (usize, usize, u32)>,
    {
        let mut weights = vec![0u8; n * n];
        for (u, v, w) in edges {
            for x in [u, v] {
                if x >= n {
                    return Err(Error::VertexOutOfRange {
                        vertex: x as i64,
                        n,
                    });
                }
            }
            if u == v {
                return Err(Error::SelfLoop(u));
            }
            if !(1..=255).contains(&w) {
                return Err(Error::Invalid(format!(
                    "edge {{{u}, {v}}} has weight {w}; weights must be between 1 and 255"
                )));
            }
            weights[u * n + v] = w as u8;
            weights[v * n + u] = w as u8;
        }
        Ok(Self::from_matrix(n, weights))
    }

    /// Builds a weighted graph from real-valued, non-negative scores between pairs of vertices,
    /// such as distances or similarities, given as `(u, v, score)` triples, and returns it with the
    /// factor the scores were scaled by. Weights are integers from 1 to 255, so each score is
    /// multiplied by `resolution / largest score` and rounded (ties to even): the largest becomes
    /// `resolution`, at most 255. A positive score too small to survive rounding keeps weight 1, and
    /// a score of 0 is no edge. A total weight `t` stands for scores totalling about `t / factor`;
    /// the graph keeps the scores, so [`WeightedGraph::induced_score`] gives the exact total. If a
    /// pair is listed more than once, the last score given wins.
    pub fn from_scores<I>(
        n: usize,
        scores: I,
        resolution: u32,
    ) -> Result<(WeightedGraph, f64), Error>
    where
        I: IntoIterator<Item = (usize, usize, f64)>,
    {
        if !(1..=255).contains(&resolution) {
            return Err(Error::Invalid(
                "resolution must be from 1 to 255, the range of weights".into(),
            ));
        }
        let mut matrix = vec![0.0f64; n * n];
        for (u, v, score) in scores {
            for x in [u, v] {
                if x >= n {
                    return Err(Error::VertexOutOfRange {
                        vertex: x as i64,
                        n,
                    });
                }
            }
            if !score.is_finite() || score < 0.0 {
                return Err(Error::Invalid(format!(
                    "the score of {{{u}, {v}}} is {score}; scores must be finite and non-negative"
                )));
            }
            if u == v {
                if score != 0.0 {
                    return Err(Error::SelfLoop(u));
                }
                continue;
            }
            matrix[u * n + v] = score;
            matrix[v * n + u] = score;
        }
        let top = matrix.iter().copied().fold(0.0, f64::max);
        let factor = if top > 0.0 {
            f64::from(resolution) / top
        } else {
            1.0
        };
        let weights = matrix
            .iter()
            .map(|&s| {
                if s == 0.0 {
                    0
                } else {
                    ((s * factor).round_ties_even() as u8).max(1)
                }
            })
            .collect();
        let mut g = Self::from_matrix(n, weights);
        g.scores = Some(Scores(Arc::new(matrix)));
        Ok((g, factor))
    }

    /// The scores the graph was made from with [`WeightedGraph::from_scores`], as an `n x n`
    /// row-major matrix (0 for pairs without a score), or `None` for other graphs.
    pub fn scores(&self) -> Option<&[f64]> {
        self.scores.as_ref().map(|s| &s.0[..])
    }

    /// The total score of the pairs among `vertices`, from the scores the graph was made from: the
    /// exact counterpart of [`WeightedGraph::induced_weight`]. `None` for graphs without scores.
    pub fn induced_score(&self, vertices: &[usize]) -> Option<f64> {
        let scores = self.scores()?;
        let mut total = 0.0;
        for (i, &u) in vertices.iter().enumerate() {
            let row = &scores[u * self.n..(u + 1) * self.n];
            total += vertices[i + 1..].iter().map(|&v| row[v]).sum::<f64>();
        }
        Some(total)
    }

    /// Every edge of `g` with weight 1.
    pub fn from_graph(g: &Graph) -> WeightedGraph {
        let n = g.num_vertices();
        Self::from_weighted_edges(n, g.edges().map(|(u, v)| (u, v, 1))).unwrap()
    }

    pub(crate) fn from_matrix(n: usize, weights: Vec<u8>) -> WeightedGraph {
        let mut neighbors = Vec::with_capacity(n);
        let mut row_max = Vec::with_capacity(n);
        let (mut twice_edges, mut twice_weight) = (0usize, 0u64);
        for u in 0..n {
            let row = &weights[u * n..(u + 1) * n];
            let list: Vec<u32> = (0..n).filter(|&v| row[v] != 0).map(|v| v as u32).collect();
            twice_edges += list.len();
            twice_weight += row.iter().map(|&w| u64::from(w)).sum::<u64>();
            row_max.push(row.iter().copied().max().unwrap_or(0));
            neighbors.push(list);
        }
        WeightedGraph {
            n,
            weights,
            neighbors,
            row_max,
            num_edges: twice_edges / 2,
            total_weight: twice_weight / 2,
            scores: None,
        }
    }

    /// Number of vertices.
    #[inline]
    pub fn num_vertices(&self) -> usize {
        self.n
    }

    /// Number of edges.
    #[inline]
    pub fn num_edges(&self) -> usize {
        self.num_edges
    }

    /// Sum of all edge weights.
    #[inline]
    pub fn total_weight(&self) -> u64 {
        self.total_weight
    }

    /// The largest weight of an edge at `u`, or 0 if it has none.
    #[inline]
    pub fn max_weight_at(&self, u: usize) -> u8 {
        self.row_max[u]
    }

    /// The weight of `{u, v}`, or 0 if it is not an edge.
    #[inline]
    pub fn weight(&self, u: usize, v: usize) -> u8 {
        self.weights[u * self.n + v]
    }

    /// Row `u` of the weight matrix.
    #[inline]
    pub fn row(&self, u: usize) -> &[u8] {
        &self.weights[u * self.n..(u + 1) * self.n]
    }

    /// The neighbors of `u`, in ascending order.
    #[inline]
    pub fn neighbors(&self, u: usize) -> &[u32] {
        &self.neighbors[u]
    }

    /// Edges `(u, v, weight)` with `u < v`, in lexicographic order.
    pub fn edges(&self) -> impl Iterator<Item = (usize, usize, u8)> + '_ {
        self.neighbors
            .iter()
            .enumerate()
            .flat_map(move |(u, list)| {
                list.iter()
                    .map(|&v| v as usize)
                    .filter(move |&v| v > u)
                    .map(move |v| (u, v, self.weight(u, v)))
            })
    }

    /// Total weight of the edges among `vertices`, which must be distinct.
    pub fn induced_weight(&self, vertices: &[usize]) -> u64 {
        let mut total = 0;
        for (i, &u) in vertices.iter().enumerate() {
            for &v in &vertices[i + 1..] {
                total += u64::from(self.weight(u, v));
            }
        }
        total
    }

    /// The underlying unweighted graph.
    pub fn structure(&self) -> Graph {
        Graph::from_edges(self.n, self.edges().map(|(u, v, _)| (u, v))).unwrap()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scores_become_weights_and_stay_exact() {
        let (w, factor) =
            WeightedGraph::from_scores(3, [(0, 1, 2.5), (1, 2, 1.0), (0, 2, 0.01)], 255).unwrap();
        // the largest score becomes 255; 1.0 rounds to 102; 0.01 would round to 0, so keeps 1
        assert_eq!(
            (w.weight(0, 1), w.weight(1, 2), w.weight(0, 2)),
            (255, 102, 1)
        );
        assert_eq!(factor, 102.0);
        assert_eq!(w.induced_weight(&[0, 1, 2]), 358);
        assert!((w.induced_score(&[0, 1, 2]).unwrap() - 3.51).abs() < 1e-12);
        assert_eq!(w.scores().unwrap()[1], 2.5);
        // ties round to even, as numpy's rint does: 0.5 and 1.5 become 0 (so 1) and 2
        let (w, _) =
            WeightedGraph::from_scores(3, [(0, 1, 4.0), (1, 2, 1.5), (0, 2, 0.5)], 4).unwrap();
        assert_eq!((w.weight(1, 2), w.weight(0, 2)), (2, 1));
        // a score of 0 is no edge; graphs not made from scores have none
        let (w, _) = WeightedGraph::from_scores(3, [(0, 1, 1.0), (1, 2, 0.0)], 255).unwrap();
        assert_eq!(w.num_edges(), 1);
        let plain = WeightedGraph::from_weighted_edges(3, [(0, 1, 5)]).unwrap();
        assert_eq!((plain.scores(), plain.induced_score(&[0, 1])), (None, None));
        for bad in [-1.0, f64::NAN, f64::INFINITY] {
            assert!(WeightedGraph::from_scores(2, [(0, 1, bad)], 255).is_err());
        }
        assert!(WeightedGraph::from_scores(2, [(0, 2, 1.0)], 255).is_err());
        assert!(WeightedGraph::from_scores(2, [(1, 1, 1.0)], 255).is_err());
        assert!(WeightedGraph::from_scores(2, [(0, 1, 1.0)], 0).is_err());
    }

    #[test]
    fn graphs_of_words_join_allowed_distances() {
        // all 3-bit words: distance 3 joins each word to its complement, distances 2 and 3 give the
        // complement of the 3-cube
        let words: Vec<u64> = (0..8).collect();
        let opposite = Graph::from_words(&words, &[3]);
        assert_eq!(opposite.num_edges(), 4);
        assert!(opposite.has_edge(0b000, 0b111) && opposite.has_edge(0b010, 0b101));
        let cube = Graph::from_words(&words, &[1]);
        assert_eq!(cube.num_edges(), 12);
        assert_eq!(Graph::from_words(&words, &[2, 3]).num_edges(), 28 - 12);
        // the same as distances from inner products of +-1 vectors, n - 2t
        let signs: Vec<i64> = words
            .iter()
            .flat_map(|w| (0..3).map(move |b| if w >> b & 1 == 1 { -1 } else { 1 }))
            .collect();
        assert_eq!(
            Graph::from_vectors(&signs, 3, &[-1, -3]).unwrap(),
            Graph::from_words(&words, &[2, 3])
        );
        assert_eq!(Graph::from_words(&[], &[1]).num_vertices(), 0);
        assert_eq!(Graph::from_words(&words, &[70]).num_edges(), 0);
    }

    #[test]
    fn graphs_of_vectors_join_allowed_inner_products() {
        // the 8 vectors of {+-1}^3: orthogonal pairs never occur (inner products are odd), and
        // inner product -3 joins each vector to its negation
        let cube: Vec<i64> = (0..8)
            .flat_map(|i| (0..3).map(move |b| if i >> b & 1 == 1 { -1 } else { 1 }))
            .collect();
        assert_eq!(Graph::from_vectors(&cube, 3, &[0]).unwrap().num_edges(), 0);
        let opposite = Graph::from_vectors(&cube, 3, &[-3]).unwrap();
        assert_eq!(opposite.num_edges(), 4);
        assert!(opposite.has_edge(0, 7) && opposite.has_edge(2, 5));
        // inner products 1 and -1 join vectors differing in one or two places: 8 * (3 + 3) / 2 pairs
        let near = Graph::from_vectors(&cube, 3, &[1, -1, 1]).unwrap();
        assert_eq!(near.num_edges(), 24);
        // the same as computing every pair by hand, on vectors with more than 64 rows
        let many: Vec<i64> = (0..100i64)
            .flat_map(|i| [i % 3 - 1, i % 5 - 2, i % 7 - 3])
            .collect();
        let g = Graph::from_vectors(&many, 3, &[0, 2]).unwrap();
        let dot = |u: usize, v: usize| {
            (0..3)
                .map(|k| many[3 * u + k] * many[3 * v + k])
                .sum::<i64>()
        };
        for u in 0..100 {
            for v in 0..100 {
                assert_eq!(
                    g.has_edge(u, v),
                    u != v && [0, 2].contains(&dot(u, v)),
                    "{u} {v}"
                );
            }
        }
        assert!(Graph::from_vectors(&[1, 2, 3], 2, &[0]).is_err());
        assert!(Graph::from_vectors(&[1, 2], 0, &[0]).is_err());
        assert_eq!(Graph::from_vectors(&[], 4, &[0]).unwrap().num_vertices(), 0);
    }

    #[test]
    fn builds_sorted_symmetric_neighbor_lists() {
        let g = Graph::from_edges(70, [(3, 1), (1, 65), (1, 3), (0, 69)]).unwrap();
        assert_eq!(g.num_edges(), 3);
        assert_eq!(g.neighbors(1), &[3, 65]);
        assert_eq!(g.neighbors(65), &[1]);
        assert!(g.has_edge(69, 0) && !g.has_edge(2, 3));
        assert_eq!(
            g.edges().collect::<Vec<_>>(),
            vec![(0, 69), (1, 3), (1, 65)]
        );
    }

    #[test]
    fn rejects_bad_edges() {
        assert!(matches!(
            Graph::from_edges(3, [(0, 3)]),
            Err(Error::VertexOutOfRange { .. })
        ));
        assert!(matches!(
            Graph::from_edges(3, [(1, 1)]),
            Err(Error::SelfLoop(1))
        ));
    }

    #[test]
    fn weighted_graphs() {
        let g = WeightedGraph::from_weighted_edges(4, [(0, 1, 3), (2, 1, 5), (0, 1, 2)]).unwrap();
        assert_eq!((g.num_edges(), g.total_weight()), (2, 7));
        assert_eq!((g.weight(1, 0), g.weight(1, 2), g.weight(0, 3)), (2, 5, 0));
        assert_eq!(g.edges().collect::<Vec<_>>(), vec![(0, 1, 2), (1, 2, 5)]);
        assert_eq!(g.induced_weight(&[0, 1, 2]), 7);
        assert_eq!(g.structure().num_edges(), 2);
        assert_eq!(WeightedGraph::from_graph(&g.structure()).total_weight(), 2);
        assert!(WeightedGraph::from_weighted_edges(3, [(0, 1, 0)]).is_err());
        assert!(WeightedGraph::from_weighted_edges(3, [(0, 1, 256)]).is_err());
    }

    #[test]
    fn counts_components() {
        let g = Graph::from_edges(6, [(0, 1), (1, 2), (4, 5)]).unwrap();
        assert_eq!(g.components().1, 3);
        assert_eq!(g.induced_edge_count(&[0, 1, 2, 4]), 2);
    }
}