Skip to main content

hypergraph_rs/generators/
classic.rs

1//! Classic hypergraph generators (XGI `xgi/generators/classic.py` port).
2
3use serde_json::Value;
4use thiserror::Error;
5
6use crate::Hypergraph;
7
8/// Error raised by a generator given invalid parameters.
9#[derive(Debug, Clone, Error, PartialEq)]
10pub enum GeneratorError {
11    /// A parameter was outside its valid range.
12    #[error("invalid parameter: {0}")]
13    InvalidParameter(String),
14}
15
16/// The empty hypergraph (0 nodes, 0 edges). XGI `empty_hypergraph()`.
17pub fn empty_hypergraph() -> Hypergraph {
18    Hypergraph::new()
19}
20
21/// A hypergraph with `n` nodes ("0".."n-1") and no edges. XGI `trivial_hypergraph(n)`.
22pub fn trivial_hypergraph(n: usize) -> Hypergraph {
23    let mut h = Hypergraph::new();
24    h.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));
25    h
26}
27
28/// Enumerate every strictly-increasing `k`-combination of `0..n` (lexicographic).
29/// Bounded: yields exactly `comb(n, k)` combinations.
30fn combinations(n: usize, k: usize) -> Vec<Vec<usize>> {
31    let mut result = Vec::new();
32    if k == 0 || k > n {
33        return result;
34    }
35    let mut idx: Vec<usize> = (0..k).collect();
36    loop {
37        result.push(idx.to_vec());
38        // advance to next combination
39        let mut i = k;
40        // Bounded: at most k steps.
41        while i > 0 {
42            i -= 1;
43            if idx[i] != i + n - k {
44                idx[i] += 1;
45                for j in (i + 1)..k {
46                    idx[j] = idx[j - 1] + 1;
47                }
48                break;
49            }
50            if i == 0 {
51                return result;
52            }
53        }
54        if k == 0 {
55            return result;
56        }
57    }
58}
59
60/// A complete hypergraph on `n` nodes. Exactly one of `order` / `max_order` must
61/// be `Some`. XGI `complete_hypergraph`.
62pub fn complete_hypergraph(
63    n: usize,
64    order: Option<usize>,
65    max_order: Option<usize>,
66    include_singletons: bool,
67) -> Result<Hypergraph, GeneratorError> {
68    match (order, max_order) {
69        (None, None) => {
70            return Err(GeneratorError::InvalidParameter(
71                "at least one of order and max_order must be specified".into(),
72            ))
73        }
74        (Some(_), Some(_)) => {
75            return Err(GeneratorError::InvalidParameter(
76                "order and max_order cannot both be specified".into(),
77            ))
78        }
79        _ => {}
80    }
81
82    let mut h = Hypergraph::new();
83    h.add_nodes_from((0..n).map(|i| (i.to_string(), Value::Null)));
84
85    let mut edges: Vec<Vec<usize>> = Vec::new();
86    if let Some(order) = order {
87        edges.extend(combinations(n, order + 1));
88    } else if let Some(max_order) = max_order {
89        let start = if include_singletons { 1 } else { 2 };
90        // FINDING 5 (deliberate deviation, documentation only): XGI asserts
91        // `end >= start` here (xgi/generators/classic.py:264, `end = max_order
92        // + 1`), so `complete_hypergraph(n, None, Some(0), include_singletons=False)`
93        // raises `AssertionError` (start=2, end=1; verified against the
94        // oracle: `complete_hypergraph(4, max_order=0)` raises). Rust's
95        // `start..=(max_order + 1)` with `start > max_order + 1` is simply an
96        // empty range (no panic), so we return an empty hypergraph instead of
97        // erroring — a deliberate improvement (no assertion-based control
98        // flow), not a bug-for-bug port.
99        // Bounded: sizes start..=max_order+1.
100        for r in start..=(max_order + 1) {
101            edges.extend(combinations(n, r));
102        }
103    }
104
105    for e in edges {
106        let members: Vec<String> = e.iter().map(|i| i.to_string()).collect();
107        // Non-empty by construction; auto-id.
108        let _ = h.add_edge(members, None, Value::Null);
109    }
110    Ok(h)
111}
112
113/// The complement of `h`: same nodes, every possible edge (size 1..=maxsize)
114/// EXCEPT those present in `h`. XGI `complement(H)`.
115pub fn complement(h: &Hypergraph) -> Hypergraph {
116    let nodes = h.node_ids();
117    let n = nodes.len();
118    let mut hc = Hypergraph::new();
119    if n == 0 {
120        return hc;
121    }
122    hc.add_nodes_from(nodes.iter().map(|nid| (nid.clone(), Value::Null)));
123
124    // node id -> dense index 0..n
125    let index: std::collections::HashMap<&str, usize> = nodes
126        .iter()
127        .enumerate()
128        .map(|(i, nid)| (nid.as_str(), i))
129        .collect();
130
131    // existing edges as sorted index-tuples
132    let mut existing: std::collections::HashSet<Vec<usize>> = std::collections::HashSet::new();
133    let mut max_size = 0usize;
134    for e in h.edge_ids() {
135        let mut idxs: Vec<usize> = h
136            .members(&e)
137            .unwrap()
138            .iter()
139            .map(|m| index[m.as_str()])
140            .collect();
141        idxs.sort_unstable();
142        max_size = max_size.max(idxs.len());
143        existing.insert(idxs);
144    }
145    if max_size == 0 {
146        max_size = 1;
147    }
148
149    // every possible edge of size 1..=max_size not in `existing`
150    // Bounded: sizes 1..=max_size, each a finite combination set.
151    for size in 1..=max_size {
152        for combo in combinations(n, size) {
153            if !existing.contains(&combo) {
154                let members: Vec<String> = combo.iter().map(|&i| nodes[i].clone()).collect();
155                let _ = hc.add_edge(members, None, Value::Null);
156            }
157        }
158    }
159    hc
160}