Skip to main content

subgraphsearch_core/
generate.rs

1//! Random graph generators, ported from the original `ggen`.
2//!
3//! Densities are in *per mille* (0..=1000), as in `ggen`. Each generator is generic over the
4//! random number generator: with [`crate::rng::Randu`] seeded as `ggen` is, the output is
5//! identical to `ggen`'s.
6
7use serde::{Deserialize, Serialize};
8
9use crate::Error;
10use crate::graph::{Graph, GraphBuilder, WeightedGraph};
11use crate::rng::{SearchRng, Xoshiro};
12
13/// The resolution of random coordinates and probabilities, as in `ggen`.
14pub const SCALE: u32 = 10_000;
15
16/// The random graph models `ggen` provides.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "lowercase")]
19pub enum Model {
20    /// Erdős–Rényi: each pair is an edge independently with probability `density / 1000`.
21    Exponential,
22    /// Every vertex `i < n - l` is joined to `l` distinct vertices chosen uniformly from those
23    /// numbered after it, with `l = density * (n - 1) / (2000 - density)`. (`ggen` calls these
24    /// "power" graphs; they are not preferential-attachment graphs and have no heavy tail.)
25    Power,
26    /// Random geometric graph in the unit square (no wrap-around): points are joined when the
27    /// disc around one with area `density / 1000` contains the other.
28    Geometric,
29}
30
31impl std::str::FromStr for Model {
32    type Err = String;
33
34    fn from_str(s: &str) -> Result<Self, Self::Err> {
35        match s.to_ascii_lowercase().as_str() {
36            "exponential" | "erdos-renyi" | "gnp" => Ok(Model::Exponential),
37            "power" => Ok(Model::Power),
38            "geometric" => Ok(Model::Geometric),
39            _ => Err(format!(
40                "unknown model '{s}' (expected exponential, power or geometric)"
41            )),
42        }
43    }
44}
45
46/// Generates a graph from `model` on `n` vertices with `density` per mille.
47pub fn generate<R: SearchRng>(
48    model: Model,
49    n: usize,
50    density: u32,
51    rng: &mut R,
52) -> Result<Graph, Error> {
53    if density > 1000 {
54        return Err(Error::Invalid(format!(
55            "density must be between 0 and 1000, got {density}"
56        )));
57    }
58    Ok(match model {
59        Model::Exponential => exponential(n, density, rng),
60        Model::Power => power(n, density, rng),
61        Model::Geometric => geometric(n, density, rng),
62    })
63}
64
65/// Erdős–Rényi random graph; see [`Model::Exponential`].
66pub fn exponential<R: SearchRng>(n: usize, density: u32, rng: &mut R) -> Graph {
67    let threshold = density * SCALE / 1000;
68    let mut b = GraphBuilder::new(n);
69    for i in 0..n {
70        for j in i + 1..n {
71            if rng.below(SCALE) < threshold {
72                b.set(i, j, true);
73            }
74        }
75    }
76    b.build()
77}
78
79/// `ggen`'s "power" random graph; see [`Model::Power`].
80pub fn power<R: SearchRng>(n: usize, density: u32, rng: &mut R) -> Graph {
81    // signed arithmetic, as in ggen, so that n = 0 behaves identically
82    let v = n as i64;
83    let l = i64::from(density) * (v - 1) / (2000 - i64::from(density));
84    let mut b = GraphBuilder::new(n);
85    let mut rand_perm = vec![0i64; n];
86    let mut i = 0;
87    while i < v - l {
88        for j in 0..(v - i) {
89            rand_perm[j as usize] = j;
90        }
91        let k = v - i - l - 1;
92        let mut j = l + k;
93        while j > k {
94            let temp = rng.below(j as u32) as usize;
95            let m = rand_perm[temp] + i + 1;
96            rand_perm[temp] = rand_perm[(j - 1) as usize];
97            b.set(i as usize, m as usize, true);
98            j -= 1;
99        }
100        i += 1;
101    }
102    b.build()
103}
104
105/// Random geometric graph; see [`Model::Geometric`].
106pub fn geometric<R: SearchRng>(n: usize, density: u32, rng: &mut R) -> Graph {
107    let mut coords = Vec::with_capacity(n);
108    for _ in 0..n {
109        let x = i64::from(rng.below(SCALE));
110        let y = i64::from(rng.below(SCALE));
111        coords.push((x, y));
112    }
113    // ggen's integer arithmetic: SCALE^2 / 3140 approximates SCALE^2 / (1000 pi)
114    let threshold = i64::from(SCALE * SCALE / 3140) * i64::from(density);
115    let mut b = GraphBuilder::new(n);
116    for i in 0..n {
117        for j in i + 1..n {
118            let (dx, dy) = (coords[i].0 - coords[j].0, coords[i].1 - coords[j].1);
119            if dx * dx + dy * dy < threshold {
120                b.set(i, j, true);
121            }
122        }
123    }
124    b.build()
125}
126
127/// The largest weight [`weighted`] creates: the original `wggen` and `wsub_search` store weights in a
128/// signed `char`.
129pub const MAX_GENERATED_WEIGHT: u8 = 127;
130
131/// A weighted random graph, as the original `wggen` makes it: `v * (v - 1) * density / 200` times, a
132/// uniformly random pair of distinct vertices has its weight increased by 1. So `density` is in
133/// percent, and the mean weight per vertex pair is `density / 100`; it may exceed 100. Fails if
134/// any weight would exceed [`MAX_GENERATED_WEIGHT`] or the total weight would not fit an `i32`.
135pub fn weighted<R: SearchRng>(n: usize, density: u32, rng: &mut R) -> Result<WeightedGraph, Error> {
136    if n < 1 {
137        return Err(Error::Invalid(
138            "a weighted graph needs at least 1 vertex".into(),
139        ));
140    }
141    let total = n as f64 * (n as f64 - 1.0) * f64::from(density) / 200.0;
142    if total > f64::from(i32::MAX) {
143        return Err(Error::Invalid(format!(
144            "total weight v * (v - 1) * density / 200 exceeds {}",
145            i32::MAX
146        )));
147    }
148    let mut weights = vec![0u8; n * n];
149    for _ in 0..total as i64 {
150        let j = rng.below(n as u32) as usize;
151        let k = loop {
152            let k = rng.below(n as u32) as usize;
153            if k != j {
154                break k;
155            }
156        };
157        if weights[j * n + k] == MAX_GENERATED_WEIGHT {
158            return Err(Error::Invalid(format!(
159                "edge weight exceeds {MAX_GENERATED_WEIGHT}; lower the density"
160            )));
161        }
162        weights[j * n + k] += 1;
163        weights[k * n + j] += 1;
164    }
165    Ok(WeightedGraph::from_matrix(n, weights))
166}
167
168/// A random `degree`-regular graph on `n` vertices, close to uniform among them. Random regular
169/// graphs are, with high probability, expanders nearly as good as possible (their second largest
170/// eigenvalue is close to the Ramanujan bound `2 sqrt(degree - 1)`).
171///
172/// Each vertex gets `degree` half-edges, and random pairs of half-edges at distinct, not yet adjacent
173/// vertices are joined until none are left; if no such pair can be found the attempt starts over
174/// (Steger and Wormald's variant of the pairing model). Above `n / 2` it builds the complement of a
175/// random `(n - 1 - degree)`-regular graph instead, which is the same distribution and much faster.
176pub fn random_regular(n: usize, degree: usize, rng: &mut Xoshiro) -> Result<Graph, Error> {
177    if degree >= n.max(1) || (n * degree) % 2 == 1 {
178        return Err(Error::Invalid(format!(
179            "no {degree}-regular graph on {n} vertices: the degree must be below n, and n times the degree even"
180        )));
181    }
182    if 2 * degree > n {
183        return Ok(crate::ops::complement(&random_regular(
184            n,
185            n - 1 - degree,
186            rng,
187        )?));
188    }
189    for _attempt in 0..1000 {
190        let mut b = GraphBuilder::new(n);
191        let mut ends: Vec<usize> = (0..n * degree).map(|i| i / degree).collect();
192        let mut stuck = false;
193        while !ends.is_empty() {
194            let len = ends.len() as u32;
195            // a few random tries find a usable pair unless almost none are left
196            let pair = (0..64 * ends.len()).find_map(|_| {
197                let (i, j) = (rng.below(len) as usize, rng.below(len) as usize);
198                let (u, v) = (ends[i], ends[j]);
199                (u != v && !b.get(u, v)).then_some((i.max(j), i.min(j)))
200            });
201            let Some((hi, lo)) = pair else {
202                stuck = true;
203                break;
204            };
205            b.set(ends[hi], ends[lo], true);
206            ends.swap_remove(hi);
207            ends.swap_remove(lo);
208        }
209        if !stuck {
210            return Ok(b.build());
211        }
212    }
213    Err(Error::Invalid(format!(
214        "could not build a random {degree}-regular graph on {n} vertices"
215    )))
216}
217
218/// The most dimensions [`hypercube`] builds: the 16-cube has 65,536 vertices, and a graph's
219/// adjacency matrix takes a bit per pair of vertices.
220pub const MAX_HYPERCUBE_DIMENSION: usize = 16;
221
222/// The `dimension`-dimensional hypercube: vertices `0..2^dimension`, joined when they differ in one
223/// bit.
224pub fn hypercube(dimension: usize) -> Result<Graph, Error> {
225    if dimension > MAX_HYPERCUBE_DIMENSION {
226        return Err(Error::Invalid(format!(
227            "hypercubes of up to {MAX_HYPERCUBE_DIMENSION} dimensions are supported, got {dimension}"
228        )));
229    }
230    let n = 1usize << dimension;
231    let mut b = GraphBuilder::new(n);
232    for u in 0..n {
233        for bit in 0..dimension {
234            b.set(u, u ^ (1 << bit), true);
235        }
236    }
237    Ok(b.build())
238}
239
240/// The `rows` by `cols` grid: vertex `r * cols + c` is joined to the vertices beside it in its row
241/// and column.
242pub fn grid(rows: usize, cols: usize) -> Graph {
243    let mut b = GraphBuilder::new(rows * cols);
244    for r in 0..rows {
245        for c in 0..cols {
246            let u = r * cols + c;
247            if c + 1 < cols {
248                b.set(u, u + 1, true);
249            }
250            if r + 1 < rows {
251                b.set(u, u + cols, true);
252            }
253        }
254    }
255    b.build()
256}
257
258/// An Erdős–Rényi random graph with each pair of vertices an edge independently with probability
259/// `mean_degree / (n - 1)`, so that vertices have `mean_degree` neighbors on average. Unlike
260/// [`exponential`], which draws a number for every pair, it skips from one edge to the next
261/// (Batagelj and Brandes, 2005), so it takes time in proportion to the number of edges and suits
262/// large sparse graphs.
263pub fn sparse_random(n: usize, mean_degree: f64, rng: &mut Xoshiro) -> Result<Graph, Error> {
264    let most = n.saturating_sub(1) as f64;
265    if !(0.0..=most).contains(&mean_degree) {
266        return Err(Error::Invalid(format!(
267            "mean degree must be between 0 and {most} (the number of vertices minus 1), got {mean_degree}"
268        )));
269    }
270    let mut b = GraphBuilder::new(n);
271    if n < 2 || mean_degree == 0.0 {
272        return Ok(b.build());
273    }
274    let p = mean_degree / most;
275    if p >= 1.0 {
276        for u in 0..n {
277            for v in u + 1..n {
278                b.set(u, v, true);
279            }
280        }
281        return Ok(b.build());
282    }
283    // walk through the pairs (v, w) with w < v in order, jumping a geometrically distributed
284    // number of pairs to the next edge
285    let log_q = (1.0 - p).ln();
286    let (mut v, mut w) = (1usize, -1i64);
287    while v < n {
288        // uniform in [0, 1), from the top 53 bits
289        let r = (rng.next_u64() >> 11) as f64 / (1u64 << 53) as f64;
290        w += 1 + ((1.0 - r).ln() / log_q).floor() as i64;
291        while w >= v as i64 && v < n {
292            w -= v as i64;
293            v += 1;
294        }
295        if v < n {
296            b.set(v, w as usize, true);
297        }
298    }
299    Ok(b.build())
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use crate::rng::{Randu, Xoshiro};
306
307    #[test]
308    fn density_extremes() {
309        let mut r = Xoshiro::new(3);
310        assert_eq!(exponential(20, 0, &mut r).num_edges(), 0);
311        assert_eq!(exponential(20, 1000, &mut r).num_edges(), 190);
312        assert_eq!(power(20, 0, &mut r).num_edges(), 0);
313        // l = n - 1 at density 1000, so vertex 0 alone is joined to everyone
314        assert_eq!(power(20, 1000, &mut r).num_edges(), 19);
315        assert!(generate(Model::Geometric, 5, 1001, &mut r).is_err());
316    }
317
318    #[test]
319    fn weighted_graphs_have_the_requested_total_weight() {
320        let g = weighted(50, 150, &mut Xoshiro::new(2)).unwrap();
321        assert_eq!(g.total_weight(), 50 * 49 * 150 / 200);
322        assert!(g.edges().any(|(_, _, w)| w > 1));
323        assert!(weighted(10, 30_000, &mut Randu::new(1)).is_err());
324        assert!(weighted(0, 5, &mut Randu::new(1)).is_err());
325    }
326
327    #[test]
328    fn power_graphs_have_the_expected_edge_count() {
329        let (n, density) = (100usize, 500u32);
330        let l = (density as usize) * (n - 1) / (2000 - density as usize);
331        let g = power(n, density, &mut Randu::new(7));
332        assert_eq!(g.num_edges(), (n - l) * l);
333    }
334
335    #[test]
336    fn random_regular_graphs() {
337        for (n, d) in [(64, 8), (100, 3), (30, 25), (10, 9), (11, 0)] {
338            let g = random_regular(n, d, &mut Xoshiro::new(5)).unwrap();
339            assert_eq!(g.num_vertices(), n);
340            assert!(g.degrees().iter().all(|&x| x == d), "{n} {d}");
341        }
342        let again = random_regular(64, 8, &mut Xoshiro::new(5)).unwrap();
343        assert_eq!(again, random_regular(64, 8, &mut Xoshiro::new(5)).unwrap());
344        assert_ne!(again, random_regular(64, 8, &mut Xoshiro::new(6)).unwrap());
345        assert!(random_regular(7, 3, &mut Xoshiro::new(1)).is_err());
346        assert!(random_regular(5, 5, &mut Xoshiro::new(1)).is_err());
347    }
348
349    #[test]
350    fn hypercubes_and_grids() {
351        let q = hypercube(5).unwrap();
352        assert_eq!((q.num_vertices(), q.num_edges()), (32, 80));
353        assert!(q.has_edge(0b10110, 0b10100) && !q.has_edge(0b10110, 0b10101));
354        assert!(q.degrees().iter().all(|&d| d == 5));
355        assert_eq!(hypercube(0).unwrap().num_vertices(), 1);
356        assert!(hypercube(MAX_HYPERCUBE_DIMENSION + 1).is_err());
357
358        let g = grid(3, 4);
359        assert_eq!((g.num_vertices(), g.num_edges()), (12, 3 * 3 + 2 * 4));
360        assert!(g.has_edge(5, 6) && g.has_edge(5, 9) && !g.has_edge(3, 4));
361    }
362
363    #[test]
364    fn sparse_random_graphs_have_the_requested_mean_degree() {
365        let n = 20_000;
366        let g = sparse_random(n, 3.0, &mut Xoshiro::new(1)).unwrap();
367        let mean = 2.0 * g.num_edges() as f64 / n as f64;
368        assert!((mean - 3.0).abs() < 0.05, "{mean}");
369        // and with the same seed, the same graph
370        let again = sparse_random(n, 3.0, &mut Xoshiro::new(1)).unwrap();
371        assert!(g.edges().eq(again.edges()));
372        assert_eq!(
373            sparse_random(30, 29.0, &mut Xoshiro::new(1))
374                .unwrap()
375                .num_edges(),
376            435
377        );
378        assert_eq!(
379            sparse_random(30, 0.0, &mut Xoshiro::new(1))
380                .unwrap()
381                .num_edges(),
382            0
383        );
384        assert!(sparse_random(30, 30.0, &mut Xoshiro::new(1)).is_err());
385        assert!(sparse_random(30, -1.0, &mut Xoshiro::new(1)).is_err());
386    }
387}