Skip to main content

hypergraph_rs/generators/
random.rs

1//! Random (non-uniform) hypergraph generators (XGI `generators/random.py`).
2
3use std::collections::{BTreeSet, HashSet};
4
5use indexmap::IndexMap;
6use serde_json::Value;
7
8use super::classic::GeneratorError;
9use super::lattice::{ring_lattice, ring_lattice_edges};
10use super::rng::{
11    choice_without_replacement, comb, geometric, index_to_edge_comb, random_below, seeded_rng,
12    uniform_f64,
13};
14use rand_pcg::Pcg64Mcg;
15
16use crate::Hypergraph;
17
18/// Resolve `(ps, order)` per XGI `_check_input_args`: default `order = 1..=len(ps)`;
19/// validate every `p in [0, 1]` and lengths match.
20fn check_input_args(ps: &[f64], order: Option<&[usize]>) -> Result<Vec<usize>, GeneratorError> {
21    let order: Vec<usize> = match order {
22        None => (0..ps.len()).map(|i| i + 1).collect(),
23        Some(o) => {
24            if o.len() != ps.len() {
25                return Err(GeneratorError::InvalidParameter(
26                    "the length of ps must match the length of order".into(),
27                ));
28            }
29            o.to_vec()
30        }
31    };
32    if ps.iter().any(|&p| !(0.0..=1.0).contains(&p)) {
33        return Err(GeneratorError::InvalidParameter(
34            "all elements of ps must be between 0 and 1".into(),
35        ));
36    }
37    Ok(order)
38}
39
40/// Enumerate strictly-increasing `k`-combinations of `0..n`.
41fn all_combinations(n: usize, k: usize) -> Vec<Vec<usize>> {
42    let mut out = Vec::new();
43    if k == 0 || k > n {
44        return out;
45    }
46    let mut idx: Vec<usize> = (0..k).collect();
47    loop {
48        out.push(idx.clone());
49        let mut i = k;
50        while i > 0 {
51            i -= 1;
52            if idx[i] != i + n - k {
53                idx[i] += 1;
54                for j in (i + 1)..k {
55                    idx[j] = idx[j - 1] + 1;
56                }
57                break;
58            }
59            if i == 0 {
60                return out;
61            }
62        }
63    }
64}
65
66/// Fast random hypergraph via geometric skip-sampling. XGI `fast_random_hypergraph`.
67pub fn fast_random_hypergraph(
68    n: usize,
69    ps: &[f64],
70    order: Option<&[usize]>,
71    seed: Option<u64>,
72) -> Result<Hypergraph, GeneratorError> {
73    let order = check_input_args(ps, order)?;
74    let mut rng = seeded_rng(seed);
75
76    let mut h = Hypergraph::new();
77    h.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));
78
79    for (d, &p) in order.iter().zip(ps.iter()) {
80        let d = *d;
81        if p == 1.0 {
82            for combo in all_combinations(n, d + 1) {
83                let members: Vec<String> = combo.iter().map(|i| i.to_string()).collect();
84                let _ = h.add_edge(members, None, Value::Null);
85            }
86        } else if p > 0.0 {
87            let count = comb(n as u64, (d + 1) as u64);
88            // FINDING 1: when the requested edge size (d+1) exceeds n, comb == 0
89            // and there is no valid combination index at all — XGI's
90            // `comb(n, d+1, exact=True) - 1` is -1 (a signed bigint) so its
91            // `while index <= max_index` loop never runs. Our `max_index` is
92            // unsigned, so skip the order entirely instead of computing a
93            // saturated (wrong) max_index of 0, which would otherwise let
94            // `index_to_edge_comb` run once on an out-of-range index and drive
95            // `comb`'s accumulator into overflow (see rng.rs `comb`).
96            if count > 0 {
97                let max_index = count - 1;
98                // -1 for zero-indexing (geometric >= 1 here)
99                let mut index = geometric(p, &mut rng) - 1;
100                // Bounded: index strictly increases by >= 1 each step, capped by max_index.
101                while index <= max_index {
102                    let combo = index_to_edge_comb(index, n as u64, (d + 1) as u64);
103                    let members: Vec<String> = combo.iter().map(|i| i.to_string()).collect();
104                    let _ = h.add_edge(members, None, Value::Null);
105                    index += geometric(p, &mut rng);
106                }
107            }
108        }
109    }
110    Ok(h)
111}
112
113/// Random hypergraph via Bernoulli over every combination. XGI `random_hypergraph`.
114pub fn random_hypergraph(
115    n: usize,
116    ps: &[f64],
117    order: Option<&[usize]>,
118    seed: Option<u64>,
119) -> Result<Hypergraph, GeneratorError> {
120    let order = check_input_args(ps, order)?;
121    let mut rng = seeded_rng(seed);
122
123    let mut h = Hypergraph::new();
124    h.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));
125
126    for (d, &p) in order.iter().zip(ps.iter()) {
127        for combo in all_combinations(n, *d + 1) {
128            if uniform_f64(&mut rng) <= p {
129                let members: Vec<String> = combo.iter().map(|i| i.to_string()).collect();
130                let _ = h.add_edge(members, None, Value::Null);
131            }
132        }
133    }
134    Ok(h)
135}
136
137/// Chung–Lu hypergraph from node-degree and edge-size sequences.
138/// XGI `chung_lu_hypergraph(k1, k2)`.
139///
140/// `k1`: node id -> degree; `k2`: edge id -> size. Determinism: nodes/edges are
141/// sorted by value descending with a stable tiebreak on the (insertion-ordered)
142/// key, so the traversal is reproducible.
143pub fn chung_lu_hypergraph(
144    k1: &IndexMap<String, f64>,
145    k2: &IndexMap<String, f64>,
146    seed: Option<u64>,
147) -> Hypergraph {
148    let mut rng = seeded_rng(seed);
149
150    // sort by value desc; stable tiebreak preserves IndexMap insertion order
151    let mut node_labels: Vec<&String> = k1.keys().collect();
152    node_labels.sort_by(|a, b| k2_cmp(k1[*b], k1[*a]));
153    let mut edge_labels: Vec<&String> = k2.keys().collect();
154    edge_labels.sort_by(|a, b| k2_cmp(k2[*b], k2[*a]));
155
156    let m = k2.len();
157    let s: f64 = k1.values().sum();
158
159    let mut h = Hypergraph::new();
160    for &nid in &node_labels {
161        h.add_node(nid, Value::Null);
162    }
163
164    for &u in &node_labels {
165        let mut j = 0usize;
166        if m == 0 {
167            continue;
168        }
169        let mut v = edge_labels[0];
170        let mut p = ((k1[u] * k2[v]) / s).min(1.0);
171        // Bounded: j strictly increases toward m.
172        while j < m {
173            if p != 1.0 {
174                if p <= 0.0 {
175                    // geometric(p<=0) returns the u64::MAX "infinity" sentinel;
176                    // XGI relies on Python float `j += inf` to end the loop for
177                    // this node. Break instead of adding the sentinel, which
178                    // would overflow `j` (a real panic risk when j > 0).
179                    break;
180                }
181                j += geometric(p, &mut rng) as usize;
182            }
183            if j < m {
184                v = edge_labels[j];
185                let q = ((k1[u] * k2[v]) / s).min(1.0);
186                let r = uniform_f64(&mut rng);
187                if p > 0.0 && r < q / p {
188                    let _ = h.add_node_to_edge(v, u);
189                }
190                p = q;
191                j += 1;
192            }
193        }
194    }
195    h
196}
197
198/// Total order on f64 for descending sort (NaN sinks last). Not exported.
199fn k2_cmp(a: f64, b: f64) -> std::cmp::Ordering {
200    a.partial_cmp(&b).unwrap_or(std::cmp::Ordering::Equal)
201}
202
203/// Watts–Strogatz hypergraph: a ring lattice with each edge rewired with prob `p`,
204/// as XGI 1.1 rewrote `watts_strogatz_hypergraph(n, d, k, l, p)`.
205///
206/// Each edge of the lattice is visited in order. With probability `p`, its farthest node (the last
207/// one) is replaced by a node chosen uniformly among the nodes that do not share an edge with the
208/// originating node (the first member of the lattice edge) in the current, partly rewired hypergraph.
209/// The edge keeps its id and its size; it is left alone when no such node exists. The same seed gives
210/// the same hypergraph; the draws are not XGI's.
211///
212/// # Errors
213///
214/// `GeneratorError::InvalidParameter` when `n == 0` or `d == 0`.
215pub fn watts_strogatz_hypergraph(
216    n: usize,
217    d: usize,
218    k: usize,
219    l: usize,
220    p: f64,
221    seed: Option<u64>,
222) -> Result<Hypergraph, GeneratorError> {
223    /// Rejection sampling gives up after this many draws and picks from the explicit candidates.
224    const MAX_DRAWS: usize = 64;
225
226    let mut rng = seeded_rng(seed);
227    let mut h = ring_lattice(n, d, k, l, false)?;
228    let lattice = ring_lattice_edges(n, d, k, l);
229
230    for (e, members) in lattice.iter().enumerate() {
231        if uniform_f64(&mut rng) >= p {
232            continue;
233        }
234        let node = members[0];
235        let node_id = node.to_string();
236        let neighbors: HashSet<usize> = h
237            .node_neighbors(&node_id)
238            .unwrap_or_default()
239            .iter()
240            .filter_map(|s| s.parse::<usize>().ok())
241            .collect();
242        let candidates = n.saturating_sub(neighbors.len() + 1);
243        if candidates == 0 {
244            continue;
245        }
246        let mut chosen: Option<usize> = None;
247        if 2 * candidates >= n {
248            for _ in 0..MAX_DRAWS {
249                let z = random_below(&mut rng, n as u64) as usize;
250                if z != node && !neighbors.contains(&z) {
251                    chosen = Some(z);
252                    break;
253                }
254            }
255        }
256        let z = chosen.unwrap_or_else(|| {
257            let pool: Vec<usize> = (0..n)
258                .filter(|z| *z != node && !neighbors.contains(z))
259                .collect();
260            pool[random_below(&mut rng, pool.len() as u64) as usize]
261        });
262        let id = e.to_string();
263        let mut new_edge: Vec<String> = members[..d - 1].iter().map(ToString::to_string).collect();
264        new_edge.push(z.to_string());
265        let _ = h.remove_edge(&id);
266        let _ = h.add_edge(new_edge, Some(id), Value::Null);
267    }
268    Ok(h)
269}
270
271/// Draw one index with probability proportional to its weight, from the running sums of the weights.
272fn weighted_index(rng: &mut Pcg64Mcg, cumulative: &[f64]) -> usize {
273    let total = *cumulative.last().expect("at least one weight");
274    let target = uniform_f64(rng) * total;
275    cumulative
276        .partition_point(|&c| c <= target)
277        .min(cumulative.len() - 1)
278}
279
280/// `k` node indices drawn with replacement, proportionally to `cumulative`'s weights; repeats collapse.
281fn chung_lu_draw(rng: &mut Pcg64Mcg, cumulative: &[f64], k: usize) -> BTreeSet<usize> {
282    (0..k).map(|_| weighted_index(rng, cumulative)).collect()
283}
284
285/// Simplicial Chung-Lu hypergraph (Kim et al. 2023). XGI 1.1 `simplicial_chung_lu_hypergraph(k1, k2, p, seed)`.
286///
287/// `k1`: node -> degree; `k2`: edge -> size. The sizes are taken in a random order. For each, with
288/// probability `p` the new edge is made from an earlier edge of another size, picked uniformly: a random
289/// subset of it when it is larger, or it plus Chung-Lu nodes when it is smaller (a plain Chung-Lu edge when
290/// there is no such earlier edge); otherwise the new edge is a plain Chung-Lu edge, its members drawn with
291/// replacement with probability proportional to their degree. Members drawn with replacement collapse, so an
292/// edge may be smaller than its drawn size, as in XGI.
293///
294/// Nodes of `k1` are added first, in `k1`'s order. Edges are added in the order they are made; a repeated
295/// member set is a second edge (XGI's `add_edges_from` of a list keeps multi-edges). All degrees zero gives
296/// the nodes of `k1` and no edge. The same seed gives the same hypergraph; the draws are not XGI's.
297///
298/// # Errors
299///
300/// `GeneratorError::InvalidParameter` when `p` is outside [0, 1].
301pub fn simplicial_chung_lu_hypergraph(
302    k1: &IndexMap<String, usize>,
303    k2: &IndexMap<String, usize>,
304    p: f64,
305    seed: Option<u64>,
306) -> Result<Hypergraph, GeneratorError> {
307    if !(0.0..=1.0).contains(&p) {
308        return Err(GeneratorError::InvalidParameter(
309            "p must be between 0 and 1.".into(),
310        ));
311    }
312    let mut rng = seeded_rng(seed);
313    let labels: Vec<&String> = k1.keys().collect();
314    let mut h = Hypergraph::new();
315    for label in &labels {
316        h.add_node(label, Value::Null);
317    }
318    let cumulative: Vec<f64> = k1
319        .values()
320        .scan(0.0, |running, &d| {
321            *running += d as f64;
322            Some(*running)
323        })
324        .collect();
325    if cumulative.last().copied().unwrap_or(0.0) <= 0.0 {
326        return Ok(h);
327    }
328
329    let sizes: Vec<usize> = k2.values().copied().collect();
330    let order = choice_without_replacement(&mut rng, sizes.len(), sizes.len());
331    let mut edges: Vec<BTreeSet<usize>> = Vec::with_capacity(sizes.len());
332    for k in order.into_iter().map(|i| sizes[i]) {
333        let new_edge = if uniform_f64(&mut rng) < p {
334            let others: Vec<&BTreeSet<usize>> = edges.iter().filter(|e| e.len() != k).collect();
335            if others.is_empty() {
336                chung_lu_draw(&mut rng, &cumulative, k)
337            } else {
338                let prime = others[random_below(&mut rng, others.len() as u64) as usize];
339                let members: Vec<usize> = prime.iter().copied().collect();
340                if members.len() > k {
341                    choice_without_replacement(&mut rng, members.len(), k)
342                        .into_iter()
343                        .map(|i| members[i])
344                        .collect()
345                } else {
346                    let mut grown = prime.clone();
347                    grown.extend(chung_lu_draw(&mut rng, &cumulative, k - members.len()));
348                    grown
349                }
350            }
351        } else {
352            chung_lu_draw(&mut rng, &cumulative, k)
353        };
354        edges.push(new_edge);
355    }
356    for edge in edges {
357        let members = edge.into_iter().map(|i| labels[i].clone()).collect();
358        let _ = h.add_edge(members, None, Value::Null);
359    }
360    Ok(h)
361}
362
363/// The rewiring probabilities of [`random_nested_hypergraph`]: one for every edge size below `d`, or one
364/// per size, `PerSize[t - 2]` for size `t`.
365#[derive(Debug, Clone, PartialEq)]
366pub enum NestedEpsilon {
367    /// The same value for every size.
368    Scalar(f64),
369    /// One value per size from 2 to `d - 1`.
370    PerSize(Vec<f64>),
371}
372
373/// Random nested hypergraph (Kim et al. 2023). XGI 1.1 `random_nested_hypergraph(n, m, d, epsilon, seed)`.
374///
375/// Draws `m` distinct facets of `d` of the `n` nodes, adds every subset of size 2 to `d` of each facet, then
376/// keeps each subset of size `t < d` with probability `epsilon` for `t`, and otherwise rewires it: one of its
377/// nodes is kept and the others are replaced by `t - 1` nodes drawn without replacement. The final edges are a
378/// set, as in XGI: a repeated member set collapses. Edges are added in ascending order of their sorted members,
379/// so ids never depend on a hash order. The same seed gives the same hypergraph; the draws are not XGI's.
380///
381/// # Errors
382///
383/// `GeneratorError::InvalidParameter` when `m > C(n, d)` or `epsilon` has fewer than `d - 2` values.
384pub fn random_nested_hypergraph(
385    n: usize,
386    m: usize,
387    d: usize,
388    epsilon: &NestedEpsilon,
389    seed: Option<u64>,
390) -> Result<Hypergraph, GeneratorError> {
391    let num_facets = comb(n as u64, d as u64);
392    if m as u64 > num_facets {
393        return Err(GeneratorError::InvalidParameter(
394            "m cannot exceed the number of possible facets.".into(),
395        ));
396    }
397    let eps: Vec<f64> = match epsilon {
398        NestedEpsilon::Scalar(e) => vec![*e; d.saturating_sub(2)],
399        NestedEpsilon::PerSize(v) if v.len() < d.saturating_sub(2) => {
400            return Err(GeneratorError::InvalidParameter(format!(
401                "epsilon must hold one value per edge size from 2 to d - 1 ({}), not {}",
402                d.saturating_sub(2),
403                v.len()
404            )))
405        }
406        NestedEpsilon::PerSize(v) => v.clone(),
407    };
408    let mut rng = seeded_rng(seed);
409
410    // Step 1: m distinct facets of size d, drawn uniformly (the complement when the facets are dense).
411    let draw_facet = |rng: &mut Pcg64Mcg| -> Vec<usize> {
412        let mut f = choice_without_replacement(rng, n, d);
413        f.sort_unstable();
414        f
415    };
416    let dense = m as u64 > num_facets / 2;
417    let target = if dense { num_facets as usize - m } else { m };
418    let mut drawn: BTreeSet<Vec<usize>> = BTreeSet::new();
419    // Each draw is new with probability at least 1/2, so the cap is never reached in practice; past it, the
420    // rest are picked from the explicit candidates, which gives the same distribution.
421    let max_draws = 64 * (target + 1);
422    for _ in 0..max_draws {
423        if drawn.len() >= target {
424            break;
425        }
426        drawn.insert(draw_facet(&mut rng));
427    }
428    if drawn.len() < target {
429        let pool: Vec<Vec<usize>> = all_combinations(n, d)
430            .into_iter()
431            .filter(|f| !drawn.contains(f))
432            .collect();
433        let need = target - drawn.len();
434        for i in choice_without_replacement(&mut rng, pool.len(), need) {
435            drawn.insert(pool[i].clone());
436        }
437    }
438    let facets: BTreeSet<Vec<usize>> = if dense {
439        all_combinations(n, d)
440            .into_iter()
441            .filter(|f| !drawn.contains(f))
442            .collect()
443    } else {
444        drawn
445    };
446
447    // Step 2: every subset of size 2..=d of each facet.
448    let mut all_edges: BTreeSet<Vec<usize>> = BTreeSet::new();
449    for facet in &facets {
450        for size in 2..=facet.len() {
451            for positions in all_combinations(facet.len(), size) {
452                all_edges.insert(positions.into_iter().map(|i| facet[i]).collect());
453            }
454        }
455    }
456
457    // Step 3: rewire the edges smaller than d.
458    let mut final_edges: BTreeSet<Vec<usize>> = BTreeSet::new();
459    for edge in all_edges {
460        let t = edge.len();
461        if t < d && uniform_f64(&mut rng) > eps[t - 2] {
462            let pivot = edge[random_below(&mut rng, t as u64) as usize];
463            let others: Vec<usize> = (0..n).filter(|&v| v != pivot).collect();
464            let mut rewired: Vec<usize> = choice_without_replacement(&mut rng, others.len(), t - 1)
465                .into_iter()
466                .map(|i| others[i])
467                .collect();
468            rewired.push(pivot);
469            rewired.sort_unstable();
470            final_edges.insert(rewired);
471        } else {
472            final_edges.insert(edge);
473        }
474    }
475
476    let mut h = Hypergraph::new();
477    h.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));
478    for edge in final_edges {
479        let members = edge.iter().map(ToString::to_string).collect();
480        let _ = h.add_edge(members, None, Value::Null);
481    }
482    Ok(h)
483}