Skip to main content

hypergraph_rs/core/
simplicialcomplex.rs

1//! The simplicial complex data structure.
2//!
3//! A `SimplicialComplex` composes a [`Hypergraph`] and enforces closure under
4//! faces: adding a simplex also adds every missing subface of size >= 2. A
5//! lazily-computed [`FaceLattice`] caches the immediate-face relation; it is
6//! invalidated on every mutation. XGI parity: `xgi.SimplicialComplex`
7//! (simplicialcomplex.py).
8
9use std::cell::OnceCell;
10use std::collections::{BTreeMap, BTreeSet};
11
12use super::error::SimplexError;
13use super::hypergraph::Hypergraph;
14
15/// The cached immediate-face relation: each simplex id maps to the ids of the
16/// codimension-1 simplices present in the complex that are its faces.
17#[derive(Debug, Clone, Default)]
18pub struct FaceLattice {
19    /// simplex id -> ids of its codim-1 faces present in the complex.
20    pub immediate_faces: BTreeMap<String, Vec<String>>,
21}
22
23/// A simplicial complex (undirected, closed under faces).
24pub struct SimplicialComplex<N = serde_json::Value, E = serde_json::Value, M = serde_json::Value> {
25    inner: Hypergraph<N, E, M>,
26    face_lattice: OnceCell<FaceLattice>,
27}
28
29/// Deduplicate a Vec of ids into a sorted set-vector (deterministic order).
30fn as_sorted_set(items: &[String]) -> Vec<String> {
31    let set: BTreeSet<String> = items.iter().cloned().collect();
32    set.into_iter().collect()
33}
34
35/// All subsets of `set` of sizes from `set.len()-1` down to 2 (never
36/// singletons). XGI parity: `_subfaces` (simplicialcomplex.py:334-361).
37fn subfaces(set: &[String]) -> Vec<Vec<String>> {
38    let k = set.len();
39    let mut out: Vec<Vec<String>> = Vec::new();
40    // sizes k-1, k-2, ..., 2
41    let mut size = k.saturating_sub(1);
42    while size >= 2 {
43        combinations(set, size, &mut out);
44        size -= 1;
45    }
46    out
47}
48
49/// Push every `choose`-sized combination of `set` (sorted input -> sorted
50/// combos) into `out`. Bounded by `total = n_choose_k(set.len(), choose)`,
51/// computed BEFORE the loop (Power-of-10 rule 2 — 2026-07-19 preflight
52/// correction, defect P2-D2: the prior `loop { ... }` form terminated via an
53/// internal `return` after C(n,k) iterations, which is provably-but-not
54/// *statically* bounded; this form gives a checkable `for` bound instead).
55fn combinations(set: &[String], choose: usize, out: &mut Vec<Vec<String>>) {
56    let n = set.len();
57    if choose == 0 || choose > n {
58        return;
59    }
60    let total = n_choose_k(n, choose);
61    // index-based lexicographic combinations; bounded by n choose k.
62    let mut idx: Vec<usize> = (0..choose).collect();
63    for _ in 0..total {
64        out.push(idx.iter().map(|&i| set[i].clone()).collect());
65        // Advance to the next combination: find the rightmost index that can
66        // still be incremented (bounded by `choose`, known before this
67        // sub-loop starts).
68        let mut pivot: Option<usize> = None;
69        for i in (0..choose).rev() {
70            if idx[i] != i + n - choose {
71                pivot = Some(i);
72                break;
73            }
74        }
75        let i = match pivot {
76            Some(i) => i,
77            None => return, // exhausted (the final combination was just pushed)
78        };
79        idx[i] += 1;
80        for j in (i + 1)..choose {
81            idx[j] = idx[j - 1] + 1;
82        }
83    }
84}
85
86/// `n` choose `k`, via the multiplicative formula (no factorials — this
87/// crate's `n` is always small, but the formula avoids any needless overflow
88/// risk regardless).
89fn n_choose_k(n: usize, k: usize) -> usize {
90    if k > n {
91        return 0;
92    }
93    let k = k.min(n - k);
94    let mut result: usize = 1;
95    for i in 0..k {
96        result = result * (n - i) / (i + 1);
97    }
98    result
99}
100
101impl<N, E, M> Default for SimplicialComplex<N, E, M> {
102    fn default() -> Self {
103        Self::new()
104    }
105}
106
107impl<N, E, M> SimplicialComplex<N, E, M> {
108    /// Create an empty simplicial complex.
109    pub fn new() -> Self {
110        Self {
111            inner: Hypergraph::new(),
112            face_lattice: OnceCell::new(),
113        }
114    }
115
116    /// The id the next simplex added without an explicit id will get.
117    /// XGI parity: `S._edge_uid`.
118    pub fn next_edge_id(&self) -> u64 {
119        self.inner.next_edge_id()
120    }
121
122    /// Raise the counter past `idx` (see [`Hypergraph::update_uid_counter`]).
123    pub fn update_uid_counter(&mut self, idx: u64) {
124        self.inner.update_uid_counter(idx);
125    }
126
127    /// Rebuild a complex from its nodes and its simplices in id order, as
128    /// `node_ids()` and `edge_ids()` list them, adding no face: every subface
129    /// of size >= 2 of each simplex must be in the list. The first simplex
130    /// with a face missing gives `SimplexError::NotClosed { idx }`.
131    ///
132    /// An entry is skipped, and the first one kept, when its id is already
133    /// taken or when its member set is already in the complex: the two cases
134    /// in which `add_simplex` is a no-op. No complex built by `add_simplex`
135    /// can list such an entry, so a state pickled from a real complex never
136    /// loses one here; only a hand-made list can.
137    pub fn from_closed_simplices(
138        nodes: Vec<(String, N)>,
139        simplices: Vec<(String, Vec<String>, E)>,
140    ) -> Result<Self, SimplexError>
141    where
142        N: Default,
143        E: Default,
144        M: Default + Clone,
145    {
146        let present: BTreeSet<Vec<String>> = simplices
147            .iter()
148            .map(|(_, members, _)| as_sorted_set(members))
149            .collect();
150        for (id, members, _) in &simplices {
151            let set = as_sorted_set(members);
152            if subfaces(&set)
153                .iter()
154                .any(|face| !face.is_empty() && !present.contains(face))
155            {
156                return Err(SimplexError::NotClosed { idx: id.clone() });
157            }
158        }
159        let mut complex = Self::new();
160        complex.add_nodes_from(nodes);
161        let mut added: std::collections::HashSet<Vec<String>> = std::collections::HashSet::new();
162        for (id, members, attrs) in simplices {
163            let set = as_sorted_set(&members);
164            if added.contains(&set) || complex.inner.has_edge(&id) {
165                continue;
166            }
167            added.insert(set.clone());
168            complex
169                .inner
170                .add_edge(set, Some(id), attrs)
171                .expect("the id was checked free just above");
172        }
173        Ok(complex)
174    }
175
176    /// Number of nodes. XGI parity: `S.num_nodes`.
177    pub fn num_nodes(&self) -> usize {
178        self.inner.num_nodes()
179    }
180
181    /// Number of simplices. XGI parity: `S.num_edges`.
182    pub fn num_edges(&self) -> usize {
183        self.inner.num_edges()
184    }
185
186    /// Whether a node exists.
187    pub fn has_node(&self, node_id: &str) -> bool {
188        self.inner.has_node(node_id)
189    }
190
191    /// Whether a simplex id exists.
192    pub fn has_edge(&self, edge_id: &str) -> bool {
193        self.inner.has_edge(edge_id)
194    }
195
196    /// The members of a simplex (by id).
197    pub fn members(&self, edge_id: &str) -> Option<Vec<String>> {
198        self.inner.members(edge_id)
199    }
200
201    /// A node's attributes.
202    pub fn node_attrs(&self, node_id: &str) -> Option<&N> {
203        self.inner.node_attrs(node_id)
204    }
205
206    /// A simplex's attributes.
207    pub fn edge_attrs(&self, edge_id: &str) -> Option<&E> {
208        self.inner.edge_attrs(edge_id)
209    }
210
211    /// All node ids (insertion order).
212    pub fn node_ids(&self) -> Vec<String> {
213        self.inner.node_ids()
214    }
215
216    /// Add a node (no simplices). XGI parity: `S.add_node(id, **attr)`.
217    /// (Phase 4 Task 9 addition: the generator `random_simplicial_complex`
218    /// must add all `N` nodes up front regardless of which simplices are
219    /// sampled — XGI's own generator does `S.add_nodes_from(nodes)` before
220    /// `S.add_simplices_from(simplices)`. This method was not part of the
221    /// Phase-2 surface the Task-9 plan text assumed; it mirrors
222    /// `Hypergraph::add_node` exactly and required no other change.)
223    pub fn add_node(&mut self, node_id: &str, attrs: N) -> bool {
224        self.invalidate();
225        self.inner.add_node(node_id, attrs)
226    }
227
228    /// Add many nodes (no simplices). XGI parity: `S.add_nodes_from(nbunch)`.
229    pub fn add_nodes_from(&mut self, nodes: impl IntoIterator<Item = (String, N)>) {
230        for (node_id, attrs) in nodes {
231            self.add_node(&node_id, attrs);
232        }
233    }
234
235    /// All simplex ids (insertion order).
236    pub fn edge_ids(&self) -> Vec<String> {
237        self.inner.edge_ids()
238    }
239
240    /// The ids of the simplices a node is a member of, in insertion order. XGI parity:
241    /// `S.nodes.memberships(n)`.
242    pub fn memberships(&self, node_id: &str) -> Option<Vec<String>> {
243        self.inner.memberships(node_id)
244    }
245
246    /// Node ids with the same simplex-membership set, grouped over the whole complex: groups of two
247    /// or more, in order of first occurrence. XGI parity: `S.nodes.duplicate_groups()`.
248    pub fn node_duplicate_groups(&self) -> Vec<Vec<String>> {
249        self.inner.nodes().duplicate_groups()
250    }
251
252    /// Simplex ids with the same member set, grouped over the whole complex (empty for a valid
253    /// complex). XGI parity: `S.edges.duplicate_groups()`.
254    pub fn edge_duplicate_groups(&self) -> Vec<Vec<String>> {
255        self.inner.edges().duplicate_groups()
256    }
257
258    /// Whether a simplex with exactly these members is present (by member-set,
259    /// not id). XGI parity: `S.has_simplex(simplex)` (simplicialcomplex.py:783-806).
260    pub fn has_simplex(&self, members: &[String]) -> bool {
261        let want: BTreeSet<String> = members.iter().cloned().collect();
262        self.inner.edge_ids().iter().any(|e| {
263            let got: BTreeSet<String> = self
264                .inner
265                .members(e)
266                .unwrap_or_default()
267                .into_iter()
268                .collect();
269            got == want
270        })
271    }
272
273    /// Add a simplex and all its missing subfaces (size >= 2). XGI parity:
274    /// `S.add_simplex(members, idx, **attr)` (simplicialcomplex.py:252-332).
275    /// Duplicate members or a duplicate `idx` are silent no-ops (deviation #5).
276    pub fn add_simplex(
277        &mut self,
278        members: Vec<String>,
279        idx: Option<String>,
280        attrs: E,
281    ) -> Result<(), SimplexError>
282    where
283        N: Default,
284        E: Default,
285        M: Default + Clone,
286    {
287        let set = as_sorted_set(&members);
288        // A no-op add (duplicate members or duplicate idx) adds no faces either.
289        if !self.add_top_simplex(members, idx, attrs) {
290            return Ok(());
291        }
292        // Missing subfaces (size >= 2), attribute-free.
293        for face in subfaces(&set) {
294            if face.is_empty() || self.has_simplex(&face) {
295                continue;
296            }
297            let _ = self.inner.add_edge(face, None, E::default());
298        }
299        self.invalidate();
300        Ok(())
301    }
302
303    /// Add only the top simplex, leaving its subfaces out: the complex is not closed until
304    /// [`close`](Self::close) runs. XGI does this by accident: `add_simplices_from` collects the
305    /// subfaces and adds them after its loop, so an error inside the loop leaves the simplices read
306    /// so far without their faces; the Python bindings mirror that state. Same no-op rules as
307    /// [`add_simplex`](Self::add_simplex).
308    pub fn add_simplex_without_faces(
309        &mut self,
310        members: Vec<String>,
311        idx: Option<String>,
312        attrs: E,
313    ) -> Result<(), SimplexError>
314    where
315        N: Default,
316        E: Default,
317        M: Default + Clone,
318    {
319        self.add_top_simplex(members, idx, attrs);
320        Ok(())
321    }
322
323    /// Adds the top simplex; returns whether it was added (false for a no-op).
324    fn add_top_simplex(&mut self, members: Vec<String>, idx: Option<String>, attrs: E) -> bool
325    where
326        N: Default,
327        E: Default,
328        M: Default + Clone,
329    {
330        let set = as_sorted_set(&members);
331        // D1: XGI's docstring claims empty simplices cannot be added; the
332        // runtime CREATES one. A repeat empty add is a no-op via the
333        // has_simplex check below (an empty set is a member of itself).
334        if self.has_simplex(&set) {
335            return false;
336        }
337        if let Some(id) = &idx {
338            if self.inner.has_edge(id) {
339                return false; // duplicate idx -> no-op (XGI warns+returns)
340            }
341        }
342        // Top simplex. `add_edge` has no member-count floor to pass — it
343        // accepts an empty member list exactly as it accepts any other (see
344        // the documentation-defect fix on `Hypergraph::add_empty_edge`,
345        // same D1 register entry this function's own comment above cites);
346        // an empty `set` here (the empty-simplex case) succeeds the same way.
347        let _ = self.inner.add_edge(set, idx, attrs);
348        self.invalidate();
349        true
350    }
351
352    /// `add_edge` is not available on a simplicial complex.
353    /// XGI parity: raises XGIError (simplicialcomplex.py:135-139).
354    pub fn add_edge(
355        &mut self,
356        _members: Vec<String>,
357        _idx: Option<String>,
358        _attrs: E,
359    ) -> Result<(), SimplexError> {
360        Err(SimplexError::NotAvailable {
361            method: "add_edge".to_string(),
362            alternative: "add_simplex".to_string(),
363        })
364    }
365
366    /// `remove_edge` is not available on a simplicial complex.
367    /// XGI parity: raises XGIError (simplicialcomplex.py:153-157).
368    pub fn remove_edge(&mut self, _edge_id: &str) -> Result<(), SimplexError> {
369        Err(SimplexError::NotAvailable {
370            method: "remove_edge".to_string(),
371            alternative: "remove_simplex_id".to_string(),
372        })
373    }
374
375    /// The lazily-computed face lattice (immediate-face relation), rebuilt on
376    /// first access after a mutation.
377    pub fn face_lattice(&self) -> &FaceLattice {
378        self.face_lattice
379            .get_or_init(|| self.compute_face_lattice())
380    }
381
382    fn compute_face_lattice(&self) -> FaceLattice {
383        // Precompute each simplex's member-set.
384        let sets: Vec<(String, BTreeSet<String>)> = self
385            .inner
386            .edge_ids()
387            .into_iter()
388            .map(|e| {
389                let s: BTreeSet<String> = self
390                    .inner
391                    .members(&e)
392                    .unwrap_or_default()
393                    .into_iter()
394                    .collect();
395                (e, s)
396            })
397            .collect();
398        let mut immediate_faces: BTreeMap<String, Vec<String>> = BTreeMap::new();
399        for (eid, me) in &sets {
400            let faces: Vec<String> = sets
401                .iter()
402                .filter(|(fid, mf)| fid != eid && mf.len() + 1 == me.len() && mf.is_subset(me))
403                .map(|(fid, _)| fid.clone())
404                .collect();
405            immediate_faces.insert(eid.clone(), faces);
406        }
407        FaceLattice { immediate_faces }
408    }
409
410    /// Invalidate the cached face lattice (called after any mutation).
411    fn invalidate(&mut self) {
412        self.face_lattice = OnceCell::new();
413    }
414
415    /// Add many simplices (each via `add_simplex`, so each closes under faces).
416    /// XGI parity: `S.add_simplices_from(ebunch)` — 3-tuple form
417    /// (simplicialcomplex.py:373-636).
418    pub fn add_simplices_from(&mut self, simplices: Vec<(Vec<String>, Option<String>, E)>)
419    where
420        N: Default,
421        E: Default,
422        M: Default + Clone,
423    {
424        for (members, idx, attrs) in simplices {
425            let _ = self.add_simplex(members, idx, attrs);
426        }
427    }
428
429    /// Add all missing subfaces of every existing simplex.
430    /// XGI parity: `S.close()` (simplicialcomplex.py:638-662).
431    pub fn close(&mut self)
432    where
433        N: Default,
434        E: Default,
435        M: Default + Clone,
436    {
437        let existing: Vec<Vec<String>> = self
438            .inner
439            .edge_ids()
440            .iter()
441            .filter_map(|e| self.inner.members(e))
442            .collect();
443        for members in existing {
444            for face in subfaces(&as_sorted_set(&members)) {
445                if !face.is_empty() && !self.has_simplex(&face) {
446                    let _ = self.inner.add_edge(face, None, E::default());
447                }
448            }
449        }
450        self.invalidate();
451    }
452
453    /// Remove a simplex AND every simplex that strictly contains it (its
454    /// supfaces), preserving closure. XGI parity: `S.remove_simplex_id(idx)`
455    /// (simplicialcomplex.py:726-756).
456    pub fn remove_simplex_id(&mut self, idx: &str) -> Result<(), SimplexError> {
457        if !self.inner.has_edge(idx) {
458            return Err(SimplexError::NotFound {
459                idx: idx.to_string(),
460            });
461        }
462        let target: BTreeSet<String> = self
463            .inner
464            .members(idx)
465            .unwrap_or_default()
466            .into_iter()
467            .collect();
468        // Supfaces: simplices whose member-set is a strict superset of target.
469        let supfaces: Vec<String> = self
470            .inner
471            .edge_ids()
472            .into_iter()
473            .filter(|e| {
474                let m: BTreeSet<String> = self
475                    .inner
476                    .members(e)
477                    .unwrap_or_default()
478                    .into_iter()
479                    .collect();
480                m.len() > target.len() && target.is_subset(&m)
481            })
482            .collect();
483        for s in supfaces {
484            let _ = self.inner.remove_edge(&s);
485        }
486        let _ = self.inner.remove_edge(idx);
487        self.invalidate();
488        Ok(())
489    }
490
491    /// Remove several simplices by id (each with its supfaces).
492    pub fn remove_simplex_ids_from(&mut self, ids: &[String]) {
493        for idx in ids {
494            // A supface removal earlier may already have removed this id; skip.
495            if self.inner.has_edge(idx) {
496                let _ = self.remove_simplex_id(idx);
497            }
498        }
499    }
500
501    /// An independent deep copy (face lattice recomputed lazily).
502    /// XGI parity: `S.copy()`.
503    pub fn copy(&self) -> Self
504    where
505        N: Clone,
506        E: Clone,
507        M: Clone,
508    {
509        Self {
510            inner: self.inner.copy(),
511            face_lattice: OnceCell::new(),
512        }
513    }
514
515    /// Freeze against modification (via the inner hypergraph's frozen guard).
516    /// XGI parity: `S.freeze()`.
517    pub fn freeze(&mut self) {
518        self.inner.freeze();
519    }
520
521    /// Whether the complex is frozen. XGI parity: `S.is_frozen`.
522    pub fn is_frozen(&self) -> bool {
523        self.inner.is_frozen()
524    }
525}