hypergraph_rs/generators/simplicial.rs
1//! Simplicial-complex generators (XGI `generators/simplicial_complexes.py`).
2//!
3//! Only `random_simplicial_complex` is ported here; the `flag_complex` family
4//! consumes NetworkX graphs and belongs to the `convert` slice (Phase 6).
5
6use serde_json::Value;
7
8use super::classic::GeneratorError;
9use super::rng::{seeded_rng, uniform_f64};
10use crate::SimplicialComplex;
11
12/// Enumerate strictly-increasing `k`-combinations of `0..n`.
13fn all_combinations(n: usize, k: usize) -> Vec<Vec<usize>> {
14 let mut out = Vec::new();
15 if k == 0 || k > n {
16 return out;
17 }
18 let mut idx: Vec<usize> = (0..k).collect();
19 loop {
20 out.push(idx.clone());
21 let mut i = k;
22 while i > 0 {
23 i -= 1;
24 if idx[i] != i + n - k {
25 idx[i] += 1;
26 for j in (i + 1)..k {
27 idx[j] = idx[j - 1] + 1;
28 }
29 break;
30 }
31 if i == 0 {
32 return out;
33 }
34 }
35 }
36}
37
38/// Random simplicial complex: connect any `d+1` nodes with a simplex with prob
39/// `ps[d-1]`; all subfaces are added. XGI `random_simplicial_complex(N, ps)`.
40///
41/// Note (Phase 4 Task 9): the plan's assumed `SimplicialComplex` API
42/// (`add_nodes_from(impl IntoIterator<Item=(String, Value)>)`,
43/// `add_simplices_from(impl IntoIterator<Item = Vec<String>>)`) does not
44/// match the landed Phase-2 surface exactly — `add_simplices_from` takes
45/// 3-tuples `(members, idx, attrs)`, and `add_node`/`add_nodes_from` did not
46/// exist at all (added to `core/simplicialcomplex.rs` alongside this task,
47/// mirroring `Hypergraph::add_node`/`add_nodes_from`) so that all `N` nodes
48/// can be registered up front, matching XGI's `S.add_nodes_from(nodes)`
49/// before `S.add_simplices_from(simplices)`.
50pub fn random_simplicial_complex(
51 n: usize,
52 ps: &[f64],
53 seed: Option<u64>,
54) -> Result<SimplicialComplex, GeneratorError> {
55 if ps.iter().any(|&p| !(0.0..=1.0).contains(&p)) {
56 return Err(GeneratorError::InvalidParameter(
57 "all elements of ps must be between 0 and 1".into(),
58 ));
59 }
60 let mut rng = seeded_rng(seed);
61
62 let mut simplices: Vec<(Vec<String>, Option<String>, Value)> = Vec::new();
63 for (i, &p) in ps.iter().enumerate() {
64 let d = i + 1; // ps[0] is prob of edges (d=1)
65 for combo in all_combinations(n, d + 1) {
66 if uniform_f64(&mut rng) <= p {
67 simplices.push((
68 combo.iter().map(|x| x.to_string()).collect(),
69 None,
70 Value::Null,
71 ));
72 }
73 }
74 }
75
76 let mut s = SimplicialComplex::new();
77 s.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));
78 s.add_simplices_from(simplices);
79 Ok(s)
80}