subgraphsearch-core 1.2.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
//! 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 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 {
    /// 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)
    }
}

/// 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.
#[derive(Clone, PartialEq, Eq)]
pub struct WeightedGraph {
    n: usize,
    weights: Vec<u8>,
    neighbors: Vec<Vec<u32>>,
    num_edges: usize,
    total_weight: u64,
}

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))
    }

    /// 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 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>();
            neighbors.push(list);
        }
        WeightedGraph {
            n,
            weights,
            neighbors,
            num_edges: twice_edges / 2,
            total_weight: twice_weight / 2,
        }
    }

    /// 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 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 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);
    }
}