hypergraph-rs 0.3.0

Hypergraphs for Rust: a port of XGI built on rustworkx-core, with a value on every membership
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Random (non-uniform) hypergraph generators (XGI `generators/random.py`).

use std::collections::{BTreeSet, HashSet};

use indexmap::IndexMap;
use serde_json::Value;

use super::classic::GeneratorError;
use super::lattice::{ring_lattice, ring_lattice_edges};
use super::rng::{
    choice_without_replacement, comb, geometric, index_to_edge_comb, random_below, seeded_rng,
    uniform_f64,
};
use rand_pcg::Pcg64Mcg;

use crate::Hypergraph;

/// Resolve `(ps, order)` per XGI `_check_input_args`: default `order = 1..=len(ps)`;
/// validate every `p in [0, 1]` and lengths match.
fn check_input_args(ps: &[f64], order: Option<&[usize]>) -> Result<Vec<usize>, GeneratorError> {
    let order: Vec<usize> = match order {
        None => (0..ps.len()).map(|i| i + 1).collect(),
        Some(o) => {
            if o.len() != ps.len() {
                return Err(GeneratorError::InvalidParameter(
                    "the length of ps must match the length of order".into(),
                ));
            }
            o.to_vec()
        }
    };
    if ps.iter().any(|&p| !(0.0..=1.0).contains(&p)) {
        return Err(GeneratorError::InvalidParameter(
            "all elements of ps must be between 0 and 1".into(),
        ));
    }
    Ok(order)
}

/// Enumerate strictly-increasing `k`-combinations of `0..n`.
fn all_combinations(n: usize, k: usize) -> Vec<Vec<usize>> {
    let mut out = Vec::new();
    if k == 0 || k > n {
        return out;
    }
    let mut idx: Vec<usize> = (0..k).collect();
    loop {
        out.push(idx.clone());
        let mut i = k;
        while i > 0 {
            i -= 1;
            if idx[i] != i + n - k {
                idx[i] += 1;
                for j in (i + 1)..k {
                    idx[j] = idx[j - 1] + 1;
                }
                break;
            }
            if i == 0 {
                return out;
            }
        }
    }
}

/// Fast random hypergraph via geometric skip-sampling. XGI `fast_random_hypergraph`.
pub fn fast_random_hypergraph(
    n: usize,
    ps: &[f64],
    order: Option<&[usize]>,
    seed: Option<u64>,
) -> Result<Hypergraph, GeneratorError> {
    let order = check_input_args(ps, order)?;
    let mut rng = seeded_rng(seed);

    let mut h = Hypergraph::new();
    h.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));

    for (d, &p) in order.iter().zip(ps.iter()) {
        let d = *d;
        if p == 1.0 {
            for combo in all_combinations(n, d + 1) {
                let members: Vec<String> = combo.iter().map(|i| i.to_string()).collect();
                let _ = h.add_edge(members, None, Value::Null);
            }
        } else if p > 0.0 {
            let count = comb(n as u64, (d + 1) as u64);
            // FINDING 1: when the requested edge size (d+1) exceeds n, comb == 0
            // and there is no valid combination index at all — XGI's
            // `comb(n, d+1, exact=True) - 1` is -1 (a signed bigint) so its
            // `while index <= max_index` loop never runs. Our `max_index` is
            // unsigned, so skip the order entirely instead of computing a
            // saturated (wrong) max_index of 0, which would otherwise let
            // `index_to_edge_comb` run once on an out-of-range index and drive
            // `comb`'s accumulator into overflow (see rng.rs `comb`).
            if count > 0 {
                let max_index = count - 1;
                // -1 for zero-indexing (geometric >= 1 here)
                let mut index = geometric(p, &mut rng) - 1;
                // Bounded: index strictly increases by >= 1 each step, capped by max_index.
                while index <= max_index {
                    let combo = index_to_edge_comb(index, n as u64, (d + 1) as u64);
                    let members: Vec<String> = combo.iter().map(|i| i.to_string()).collect();
                    let _ = h.add_edge(members, None, Value::Null);
                    index += geometric(p, &mut rng);
                }
            }
        }
    }
    Ok(h)
}

/// Random hypergraph via Bernoulli over every combination. XGI `random_hypergraph`.
pub fn random_hypergraph(
    n: usize,
    ps: &[f64],
    order: Option<&[usize]>,
    seed: Option<u64>,
) -> Result<Hypergraph, GeneratorError> {
    let order = check_input_args(ps, order)?;
    let mut rng = seeded_rng(seed);

    let mut h = Hypergraph::new();
    h.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));

    for (d, &p) in order.iter().zip(ps.iter()) {
        for combo in all_combinations(n, *d + 1) {
            if uniform_f64(&mut rng) <= p {
                let members: Vec<String> = combo.iter().map(|i| i.to_string()).collect();
                let _ = h.add_edge(members, None, Value::Null);
            }
        }
    }
    Ok(h)
}

/// Chung–Lu hypergraph from node-degree and edge-size sequences.
/// XGI `chung_lu_hypergraph(k1, k2)`.
///
/// `k1`: node id -> degree; `k2`: edge id -> size. Determinism: nodes/edges are
/// sorted by value descending with a stable tiebreak on the (insertion-ordered)
/// key, so the traversal is reproducible.
pub fn chung_lu_hypergraph(
    k1: &IndexMap<String, f64>,
    k2: &IndexMap<String, f64>,
    seed: Option<u64>,
) -> Hypergraph {
    let mut rng = seeded_rng(seed);

    // sort by value desc; stable tiebreak preserves IndexMap insertion order
    let mut node_labels: Vec<&String> = k1.keys().collect();
    node_labels.sort_by(|a, b| k2_cmp(k1[*b], k1[*a]));
    let mut edge_labels: Vec<&String> = k2.keys().collect();
    edge_labels.sort_by(|a, b| k2_cmp(k2[*b], k2[*a]));

    let m = k2.len();
    let s: f64 = k1.values().sum();

    let mut h = Hypergraph::new();
    for &nid in &node_labels {
        h.add_node(nid, Value::Null);
    }

    for &u in &node_labels {
        let mut j = 0usize;
        if m == 0 {
            continue;
        }
        let mut v = edge_labels[0];
        let mut p = ((k1[u] * k2[v]) / s).min(1.0);
        // Bounded: j strictly increases toward m.
        while j < m {
            if p != 1.0 {
                if p <= 0.0 {
                    // geometric(p<=0) returns the u64::MAX "infinity" sentinel;
                    // XGI relies on Python float `j += inf` to end the loop for
                    // this node. Break instead of adding the sentinel, which
                    // would overflow `j` (a real panic risk when j > 0).
                    break;
                }
                j += geometric(p, &mut rng) as usize;
            }
            if j < m {
                v = edge_labels[j];
                let q = ((k1[u] * k2[v]) / s).min(1.0);
                let r = uniform_f64(&mut rng);
                if p > 0.0 && r < q / p {
                    let _ = h.add_node_to_edge(v, u);
                }
                p = q;
                j += 1;
            }
        }
    }
    h
}

/// Total order on f64 for descending sort (NaN sinks last). Not exported.
fn k2_cmp(a: f64, b: f64) -> std::cmp::Ordering {
    a.partial_cmp(&b).unwrap_or(std::cmp::Ordering::Equal)
}

/// Watts–Strogatz hypergraph: a ring lattice with each edge rewired with prob `p`,
/// as XGI 1.1 rewrote `watts_strogatz_hypergraph(n, d, k, l, p)`.
///
/// Each edge of the lattice is visited in order. With probability `p`, its farthest node (the last
/// one) is replaced by a node chosen uniformly among the nodes that do not share an edge with the
/// originating node (the first member of the lattice edge) in the current, partly rewired hypergraph.
/// The edge keeps its id and its size; it is left alone when no such node exists. The same seed gives
/// the same hypergraph; the draws are not XGI's.
///
/// # Errors
///
/// `GeneratorError::InvalidParameter` when `n == 0` or `d == 0`.
pub fn watts_strogatz_hypergraph(
    n: usize,
    d: usize,
    k: usize,
    l: usize,
    p: f64,
    seed: Option<u64>,
) -> Result<Hypergraph, GeneratorError> {
    /// Rejection sampling gives up after this many draws and picks from the explicit candidates.
    const MAX_DRAWS: usize = 64;

    let mut rng = seeded_rng(seed);
    let mut h = ring_lattice(n, d, k, l, false)?;
    let lattice = ring_lattice_edges(n, d, k, l);

    for (e, members) in lattice.iter().enumerate() {
        if uniform_f64(&mut rng) >= p {
            continue;
        }
        let node = members[0];
        let node_id = node.to_string();
        let neighbors: HashSet<usize> = h
            .node_neighbors(&node_id)
            .unwrap_or_default()
            .iter()
            .filter_map(|s| s.parse::<usize>().ok())
            .collect();
        let candidates = n.saturating_sub(neighbors.len() + 1);
        if candidates == 0 {
            continue;
        }
        let mut chosen: Option<usize> = None;
        if 2 * candidates >= n {
            for _ in 0..MAX_DRAWS {
                let z = random_below(&mut rng, n as u64) as usize;
                if z != node && !neighbors.contains(&z) {
                    chosen = Some(z);
                    break;
                }
            }
        }
        let z = chosen.unwrap_or_else(|| {
            let pool: Vec<usize> = (0..n)
                .filter(|z| *z != node && !neighbors.contains(z))
                .collect();
            pool[random_below(&mut rng, pool.len() as u64) as usize]
        });
        let id = e.to_string();
        let mut new_edge: Vec<String> = members[..d - 1].iter().map(ToString::to_string).collect();
        new_edge.push(z.to_string());
        let _ = h.remove_edge(&id);
        let _ = h.add_edge(new_edge, Some(id), Value::Null);
    }
    Ok(h)
}

/// Draw one index with probability proportional to its weight, from the running sums of the weights.
fn weighted_index(rng: &mut Pcg64Mcg, cumulative: &[f64]) -> usize {
    let total = *cumulative.last().expect("at least one weight");
    let target = uniform_f64(rng) * total;
    cumulative
        .partition_point(|&c| c <= target)
        .min(cumulative.len() - 1)
}

/// `k` node indices drawn with replacement, proportionally to `cumulative`'s weights; repeats collapse.
fn chung_lu_draw(rng: &mut Pcg64Mcg, cumulative: &[f64], k: usize) -> BTreeSet<usize> {
    (0..k).map(|_| weighted_index(rng, cumulative)).collect()
}

/// Simplicial Chung-Lu hypergraph (Kim et al. 2023). XGI 1.1 `simplicial_chung_lu_hypergraph(k1, k2, p, seed)`.
///
/// `k1`: node -> degree; `k2`: edge -> size. The sizes are taken in a random order. For each, with
/// probability `p` the new edge is made from an earlier edge of another size, picked uniformly: a random
/// subset of it when it is larger, or it plus Chung-Lu nodes when it is smaller (a plain Chung-Lu edge when
/// there is no such earlier edge); otherwise the new edge is a plain Chung-Lu edge, its members drawn with
/// replacement with probability proportional to their degree. Members drawn with replacement collapse, so an
/// edge may be smaller than its drawn size, as in XGI.
///
/// Nodes of `k1` are added first, in `k1`'s order. Edges are added in the order they are made; a repeated
/// member set is a second edge (XGI's `add_edges_from` of a list keeps multi-edges). All degrees zero gives
/// the nodes of `k1` and no edge. The same seed gives the same hypergraph; the draws are not XGI's.
///
/// # Errors
///
/// `GeneratorError::InvalidParameter` when `p` is outside [0, 1].
pub fn simplicial_chung_lu_hypergraph(
    k1: &IndexMap<String, usize>,
    k2: &IndexMap<String, usize>,
    p: f64,
    seed: Option<u64>,
) -> Result<Hypergraph, GeneratorError> {
    if !(0.0..=1.0).contains(&p) {
        return Err(GeneratorError::InvalidParameter(
            "p must be between 0 and 1.".into(),
        ));
    }
    let mut rng = seeded_rng(seed);
    let labels: Vec<&String> = k1.keys().collect();
    let mut h = Hypergraph::new();
    for label in &labels {
        h.add_node(label, Value::Null);
    }
    let cumulative: Vec<f64> = k1
        .values()
        .scan(0.0, |running, &d| {
            *running += d as f64;
            Some(*running)
        })
        .collect();
    if cumulative.last().copied().unwrap_or(0.0) <= 0.0 {
        return Ok(h);
    }

    let sizes: Vec<usize> = k2.values().copied().collect();
    let order = choice_without_replacement(&mut rng, sizes.len(), sizes.len());
    let mut edges: Vec<BTreeSet<usize>> = Vec::with_capacity(sizes.len());
    for k in order.into_iter().map(|i| sizes[i]) {
        let new_edge = if uniform_f64(&mut rng) < p {
            let others: Vec<&BTreeSet<usize>> = edges.iter().filter(|e| e.len() != k).collect();
            if others.is_empty() {
                chung_lu_draw(&mut rng, &cumulative, k)
            } else {
                let prime = others[random_below(&mut rng, others.len() as u64) as usize];
                let members: Vec<usize> = prime.iter().copied().collect();
                if members.len() > k {
                    choice_without_replacement(&mut rng, members.len(), k)
                        .into_iter()
                        .map(|i| members[i])
                        .collect()
                } else {
                    let mut grown = prime.clone();
                    grown.extend(chung_lu_draw(&mut rng, &cumulative, k - members.len()));
                    grown
                }
            }
        } else {
            chung_lu_draw(&mut rng, &cumulative, k)
        };
        edges.push(new_edge);
    }
    for edge in edges {
        let members = edge.into_iter().map(|i| labels[i].clone()).collect();
        let _ = h.add_edge(members, None, Value::Null);
    }
    Ok(h)
}

/// The rewiring probabilities of [`random_nested_hypergraph`]: one for every edge size below `d`, or one
/// per size, `PerSize[t - 2]` for size `t`.
#[derive(Debug, Clone, PartialEq)]
pub enum NestedEpsilon {
    /// The same value for every size.
    Scalar(f64),
    /// One value per size from 2 to `d - 1`.
    PerSize(Vec<f64>),
}

/// Random nested hypergraph (Kim et al. 2023). XGI 1.1 `random_nested_hypergraph(n, m, d, epsilon, seed)`.
///
/// Draws `m` distinct facets of `d` of the `n` nodes, adds every subset of size 2 to `d` of each facet, then
/// keeps each subset of size `t < d` with probability `epsilon` for `t`, and otherwise rewires it: one of its
/// nodes is kept and the others are replaced by `t - 1` nodes drawn without replacement. The final edges are a
/// set, as in XGI: a repeated member set collapses. Edges are added in ascending order of their sorted members,
/// so ids never depend on a hash order. The same seed gives the same hypergraph; the draws are not XGI's.
///
/// # Errors
///
/// `GeneratorError::InvalidParameter` when `m > C(n, d)` or `epsilon` has fewer than `d - 2` values.
pub fn random_nested_hypergraph(
    n: usize,
    m: usize,
    d: usize,
    epsilon: &NestedEpsilon,
    seed: Option<u64>,
) -> Result<Hypergraph, GeneratorError> {
    let num_facets = comb(n as u64, d as u64);
    if m as u64 > num_facets {
        return Err(GeneratorError::InvalidParameter(
            "m cannot exceed the number of possible facets.".into(),
        ));
    }
    let eps: Vec<f64> = match epsilon {
        NestedEpsilon::Scalar(e) => vec![*e; d.saturating_sub(2)],
        NestedEpsilon::PerSize(v) if v.len() < d.saturating_sub(2) => {
            return Err(GeneratorError::InvalidParameter(format!(
                "epsilon must hold one value per edge size from 2 to d - 1 ({}), not {}",
                d.saturating_sub(2),
                v.len()
            )))
        }
        NestedEpsilon::PerSize(v) => v.clone(),
    };
    let mut rng = seeded_rng(seed);

    // Step 1: m distinct facets of size d, drawn uniformly (the complement when the facets are dense).
    let draw_facet = |rng: &mut Pcg64Mcg| -> Vec<usize> {
        let mut f = choice_without_replacement(rng, n, d);
        f.sort_unstable();
        f
    };
    let dense = m as u64 > num_facets / 2;
    let target = if dense { num_facets as usize - m } else { m };
    let mut drawn: BTreeSet<Vec<usize>> = BTreeSet::new();
    // Each draw is new with probability at least 1/2, so the cap is never reached in practice; past it, the
    // rest are picked from the explicit candidates, which gives the same distribution.
    let max_draws = 64 * (target + 1);
    for _ in 0..max_draws {
        if drawn.len() >= target {
            break;
        }
        drawn.insert(draw_facet(&mut rng));
    }
    if drawn.len() < target {
        let pool: Vec<Vec<usize>> = all_combinations(n, d)
            .into_iter()
            .filter(|f| !drawn.contains(f))
            .collect();
        let need = target - drawn.len();
        for i in choice_without_replacement(&mut rng, pool.len(), need) {
            drawn.insert(pool[i].clone());
        }
    }
    let facets: BTreeSet<Vec<usize>> = if dense {
        all_combinations(n, d)
            .into_iter()
            .filter(|f| !drawn.contains(f))
            .collect()
    } else {
        drawn
    };

    // Step 2: every subset of size 2..=d of each facet.
    let mut all_edges: BTreeSet<Vec<usize>> = BTreeSet::new();
    for facet in &facets {
        for size in 2..=facet.len() {
            for positions in all_combinations(facet.len(), size) {
                all_edges.insert(positions.into_iter().map(|i| facet[i]).collect());
            }
        }
    }

    // Step 3: rewire the edges smaller than d.
    let mut final_edges: BTreeSet<Vec<usize>> = BTreeSet::new();
    for edge in all_edges {
        let t = edge.len();
        if t < d && uniform_f64(&mut rng) > eps[t - 2] {
            let pivot = edge[random_below(&mut rng, t as u64) as usize];
            let others: Vec<usize> = (0..n).filter(|&v| v != pivot).collect();
            let mut rewired: Vec<usize> = choice_without_replacement(&mut rng, others.len(), t - 1)
                .into_iter()
                .map(|i| others[i])
                .collect();
            rewired.push(pivot);
            rewired.sort_unstable();
            final_edges.insert(rewired);
        } else {
            final_edges.insert(edge);
        }
    }

    let mut h = Hypergraph::new();
    h.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));
    for edge in final_edges {
        let members = edge.iter().map(ToString::to_string).collect();
        let _ = h.add_edge(members, None, Value::Null);
    }
    Ok(h)
}