Skip to main content

hypergraph_rs/generators/
rng.rs

1//! Seeded RNG + sampling + combinatorics helpers for the generators.
2//!
3//! We drive `rand_pcg::Pcg64Mcg` through the version-stable `rand_core` traits
4//! (`SeedableRng::seed_from_u64` + `RngCore::next_u64`) and derive all sampling
5//! primitives ourselves. This sidesteps rand 0.10's `Rng`/`RngExt` trait split
6//! (the probe showed `random_range` moved to `RngExt`) and guarantees a fixed,
7//! documented f64 construction for cross-build reproducibility.
8
9use rand_core::{Rng, SeedableRng};
10use rand_pcg::Pcg64Mcg;
11
12/// Build a `Pcg64Mcg` from an optional seed. `None` uses a fixed default seed so
13/// that "unseeded" callers are STILL deterministic within a process/build
14/// (III.7: non-determinism is a bug — we never reach for entropy).
15pub fn seeded_rng(seed: Option<u64>) -> Pcg64Mcg {
16    Pcg64Mcg::seed_from_u64(seed.unwrap_or(0))
17}
18
19/// A uniform f64 in `[0, 1)` from 53 bits of the generator (IEEE-754 double
20/// mantissa). Fixed construction: `(next_u64() >> 11) / 2^53`.
21pub fn uniform_f64(rng: &mut Pcg64Mcg) -> f64 {
22    let bits = rng.next_u64() >> 11;
23    (bits as f64) * (1.0f64 / ((1u64 << 53) as f64))
24}
25
26/// A uniform integer in `[0, n)`. Panics via debug-assert if `n == 0`.
27/// Uses modulo reduction (deterministic; slight low-bit bias is acceptable —
28/// generator conformance is structural, not sequence-exact).
29pub fn random_below(rng: &mut Pcg64Mcg, n: u64) -> u64 {
30    debug_assert!(n > 0, "random_below requires n > 0");
31    rng.next_u64() % n
32}
33
34/// Sample `k` distinct indices from `0..pool_len` (partial Fisher–Yates).
35/// Returns them in draw order. Requires `k <= pool_len`.
36pub fn choice_without_replacement(rng: &mut Pcg64Mcg, pool_len: usize, k: usize) -> Vec<usize> {
37    debug_assert!(k <= pool_len, "cannot draw {k} distinct from {pool_len}");
38    let mut idx: Vec<usize> = (0..pool_len).collect();
39    let mut out = Vec::with_capacity(k);
40    // Bounded loop: exactly k iterations.
41    for i in 0..k {
42        let remaining = pool_len - i;
43        let j = i + (random_below(rng, remaining as u64) as usize);
44        idx.swap(i, j);
45        out.push(idx[i]);
46    }
47    out
48}
49
50/// The geometric sampler (number of trials to first success), clamped to `>= 1`.
51///
52/// XGI: `ceil(log(r) / log(1 - p))`, `p == 1 -> 1`, `p == 0 -> inf`
53/// (`xgi/utils/utilities.py:564`). We clamp to `max(1)` so the `index += geometric`
54/// loops in the random/uniform generators strictly advance (Power-of-10 rule 2).
55pub fn geometric(p: f64, rng: &mut Pcg64Mcg) -> u64 {
56    if p >= 1.0 {
57        return 1;
58    }
59    if p <= 0.0 {
60        return u64::MAX; // "infinity" sentinel; callers guard p > 0
61    }
62    let mut r = uniform_f64(rng);
63    if r <= 0.0 {
64        r = f64::MIN_POSITIVE; // avoid log(0)
65    }
66    let g = (r.ln() / (1.0 - p).ln()).ceil();
67    let g = if g.is_finite() && g >= 1.0 {
68        g as u64
69    } else {
70        1
71    };
72    g.max(1)
73}
74
75/// Exact binomial coefficient `C(n, k)` (0 if `k > n`). Multiplicative form,
76/// integer-exact because the running product of `k` consecutive integers is
77/// divisible by `k!` at each step.
78///
79/// FINDING 2: the running product `acc * (n - i)` (computed BEFORE dividing by
80/// `(i + 1)`) can exceed `u64::MAX` even when the final `C(n, k)` itself fits
81/// in a `u64` (e.g. `comb(100, 16)` — see `test_comb_large_but_legal_does_not_panic_and_matches_oracle`).
82/// We accumulate in `u128` (headroom for any `n, k` we realistically see —
83/// XGI itself uses `scipy.special.comb(..., exact=True)`, i.e. Python
84/// bigints) and only narrow to `u64` once, at the end. If even the `u128`
85/// product overflows (astronomically large `n`/`k`) or the final value
86/// exceeds `u64::MAX`, we saturate to `u64::MAX` rather than panic/wrap: at
87/// that magnitude the geometric-skip callers (`fast_random_hypergraph`,
88/// `uniform_erdos_renyi_model`) would never exhaustively enumerate the
89/// combination space anyway, so a saturated `max_index` is a documented,
90/// harmless approximation, not a correctness hazard.
91pub fn comb(n: u64, k: u64) -> u64 {
92    if k > n {
93        return 0;
94    }
95    let k = k.min(n - k);
96    let mut acc: u128 = 1;
97    // Bounded loop: exactly k iterations.
98    for i in 0..k {
99        let numerator = match acc.checked_mul((n - i) as u128) {
100            Some(v) => v,
101            None => return u64::MAX,
102        };
103        acc = numerator / ((i + 1) as u128);
104    }
105    acc.min(u64::MAX as u128) as u64
106}
107
108/// Map a linear index to the `m`-combination of `0..n` at that index (sorted,
109/// strictly increasing). Port of `_index_to_edge_comb` (`uniform.py:457`).
110pub fn index_to_edge_comb(index: u64, n: u64, m: u64) -> Vec<usize> {
111    let mut c: Vec<usize> = Vec::with_capacity(m as usize);
112    let mut r = index as i128 + 1; // 1-indexed internally
113    let mut j: i128 = -1;
114    // Bounded loop: exactly m iterations.
115    for s in 1..=m {
116        let mut cs = j + 1;
117        // Bounded: cs climbs within 0..n, at most n steps.
118        loop {
119            let take = comb((n as i128 - 1 - cs) as u64, m - s) as i128;
120            if r - take > 0 {
121                r -= take;
122                cs += 1;
123            } else {
124                break;
125            }
126        }
127        c.push(cs as usize);
128        j = cs;
129    }
130    c
131}
132
133/// Map a linear index to an `m`-tuple over `0..n` with repetition (product order,
134/// last coordinate fastest). Port of `_index_to_edge_prod` (`uniform.py:405`).
135pub fn index_to_edge_prod(index: u64, n: u64, m: u64) -> Vec<usize> {
136    let mut out = Vec::with_capacity(m as usize);
137    // Bounded loop: exactly m iterations.
138    for r in (0..m).rev() {
139        let place = n.pow(r as u32);
140        out.push(((index / place) % n) as usize);
141    }
142    out
143}