Skip to main content

hypergraph_rs/generators/
uniform.rs

1//! Uniform random hypergraph generators (XGI `generators/uniform.py`).
2//!
3//! `uniform_HSBM` / `uniform_HPPM` require an m-dimensional probability tensor and
4//! are deferred (see the plan's Open questions).
5
6use std::collections::HashSet;
7
8use indexmap::IndexMap;
9use serde_json::Value;
10
11use super::classic::{complete_hypergraph, GeneratorError};
12use super::rng::{
13    choice_without_replacement, comb, geometric, index_to_edge_comb, index_to_edge_prod, seeded_rng,
14};
15use crate::Hypergraph;
16
17/// How `p` is interpreted in `uniform_erdos_renyi_model`.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum PType {
20    /// `p` is the per-edge probability.
21    Prob,
22    /// `p` is the target mean degree.
23    Degree,
24}
25
26/// m-uniform Erdős–Rényi hypergraph. XGI `uniform_erdos_renyi_model`.
27pub fn uniform_erdos_renyi_model(
28    n: usize,
29    m: usize,
30    p: f64,
31    p_type: PType,
32    multiedges: bool,
33    seed: Option<u64>,
34) -> Result<Hypergraph, GeneratorError> {
35    let q = match p_type {
36        PType::Degree => {
37            if multiedges {
38                p / (m as f64 * (n as f64).powi((m - 1) as i32))
39            } else {
40                p * n as f64 / (m as f64 * comb(n as u64, m as u64) as f64)
41            }
42        }
43        PType::Prob => p,
44    };
45    if !(0.0..=1.0).contains(&q) {
46        return Err(GeneratorError::InvalidParameter(
47            "probability not in [0, 1]".into(),
48        ));
49    }
50    if q == 1.0 && !multiedges {
51        return complete_hypergraph(n, Some(m - 1), None, false);
52    }
53
54    let mut h = Hypergraph::new();
55    h.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));
56    if q == 0.0 {
57        return Ok(h);
58    }
59
60    let mut rng = seeded_rng(seed);
61    // FINDING 1: when m (the edge/tuple size) exceeds n, the combination count
62    // is 0 and there is no valid index at all — XGI's
63    // `comb(n, m, exact=True) - 1` is -1 (a signed bigint) so its
64    // `while index <= max_index` loop never runs. Skip the whole sampling loop
65    // in that case instead of computing a saturated (wrong) max_index of 0,
66    // which would otherwise let `index_to_edge_comb`/`index_to_edge_prod` run
67    // once on an out-of-range index and overflow `comb`'s accumulator.
68    let count: u64 = if multiedges {
69        (n as u64).pow(m as u32)
70    } else {
71        comb(n as u64, m as u64)
72    };
73    if count > 0 {
74        let max_index = count - 1;
75        let mut index = geometric(q, &mut rng) - 1;
76        // Bounded: index strictly increases by >= 1 each step, capped by max_index.
77        while index <= max_index {
78            let tuple = if multiedges {
79                index_to_edge_prod(index, n as u64, m as u64)
80            } else {
81                index_to_edge_comb(index, n as u64, m as u64)
82            };
83            // dedup to a set; keep only if still size m (discard self-loop artifacts)
84            let set: HashSet<usize> = tuple.iter().copied().collect();
85            if set.len() == m {
86                let members: Vec<String> = tuple.iter().map(|i| i.to_string()).collect();
87                let _ = h.add_edge(members, None, Value::Null);
88            }
89            index += geometric(q, &mut rng);
90        }
91    }
92    Ok(h)
93}
94
95/// m-uniform configuration model from a node-degree sequence.
96/// XGI `uniform_configuration_model(k, m)`.
97///
98/// XGI increases random node degrees when `sum(k) % m != 0`; we instead drop the
99/// remainder stubs (documented deviation — still deterministic, avoids mutating
100/// the caller's degree map). Loopy/duplicate-collapsed edges are discarded.
101pub fn uniform_configuration_model(
102    k: &IndexMap<String, usize>,
103    m: usize,
104    seed: Option<u64>,
105) -> Hypergraph {
106    let mut rng = seeded_rng(seed);
107
108    // stub list: each node id repeated by its degree, in insertion order
109    let mut stubs: Vec<String> = Vec::new();
110    for (idx, &deg) in k {
111        for _ in 0..deg {
112            stubs.push(idx.clone());
113        }
114    }
115    // drop remainder stubs so len is divisible by m (deviation from XGI)
116    let rem = stubs.len() % m;
117    for _ in 0..rem {
118        stubs.pop();
119    }
120
121    let mut h = Hypergraph::new();
122    for key in k.keys() {
123        h.add_node(key, Value::Null);
124    }
125
126    // Bounded: each iteration removes exactly m stubs; stubs.len()/m iterations.
127    while stubs.len() >= m {
128        let picks = choice_without_replacement(&mut rng, stubs.len(), m);
129        // Dedup in draw order (NOT via HashSet iteration, whose order is
130        // process-randomized) so `members()` is reproducible bit-for-bit given
131        // a seed, per the Global Constraint.
132        let mut seen: HashSet<String> = HashSet::new();
133        let mut members: Vec<String> = Vec::with_capacity(m);
134        for &pi in &picks {
135            let s = stubs[pi].clone();
136            if seen.insert(s.clone()) {
137                members.push(s);
138            }
139        }
140        if members.len() == m {
141            let _ = h.add_edge(members, None, Value::Null);
142        }
143        // remove chosen stubs, largest index first
144        let mut sorted = picks.clone();
145        sorted.sort_unstable_by(|a, b| b.cmp(a));
146        for pi in sorted {
147            stubs.remove(pi);
148        }
149    }
150    h
151}