Skip to main content

hypergraph_rs/algorithms/
simpliciality.rs

1//! Simpliciality measures (`xgi/algorithms/simpliciality.py`).
2//!
3//! A face's subfaces are its powerset for sizes `min_size..len-1`. Edge
4//! membership is tested against a set of canonicalized (sorted) member lists.
5
6use std::collections::HashSet;
7
8use crate::Hypergraph;
9
10/// Sorted-member set of all edges, for O(1) subface presence queries.
11struct FaceSet {
12    faces: HashSet<Vec<String>>,
13}
14
15impl FaceSet {
16    fn build<N, E, M>(h: &Hypergraph<N, E, M>) -> Self {
17        let mut faces = HashSet::new();
18        for e in h.edge_ids() {
19            let mut m = h.members(&e).unwrap_or_default();
20            m.sort();
21            faces.insert(m);
22        }
23        FaceSet { faces }
24    }
25    fn contains(&self, face: &[String]) -> bool {
26        let mut key = face.to_vec();
27        key.sort();
28        self.faces.contains(&key)
29    }
30}
31
32/// Subfaces of `face` for sizes in `min_size..=max_size`.
33fn powerset(face: &[String], min_size: usize, max_size: usize) -> Vec<Vec<String>> {
34    let mut out = Vec::new();
35    let n = face.len();
36    // Bounded: 2^n subsets, filtered by size (n is a single edge's arity).
37    // The bound is only statically provable for n < 64 (u64 shift overflow
38    // above that) — see the Task 11 "Bound note".
39    debug_assert!(n < 64, "powerset: edge arity must be < 64");
40    for mask in 0u64..(1u64 << n) {
41        let size = mask.count_ones() as usize;
42        if size >= min_size && size <= max_size {
43            let subset: Vec<String> = (0..n)
44                .filter(|i| mask & (1 << i) != 0)
45                .map(|i| face[i].clone())
46                .collect();
47            out.push(subset);
48        }
49    }
50    out
51}
52
53/// Number of subfaces (sizes `min_size..len-1`) of `face` absent from the set.
54fn count_missing_subfaces(fs: &FaceSet, face: &[String], min_size: usize) -> usize {
55    if face.len() < min_size + 1 {
56        return 0;
57    }
58    powerset(face, min_size, face.len() - 1)
59        .into_iter()
60        .filter(|sub| !fs.contains(sub))
61        .count()
62}
63
64/// Maximum possible subfaces of a face of `max_size`, sizes ≥ `min_size`,
65/// excluding the face itself and the empty set. XGI: `_max_number_of_subfaces`.
66fn max_number_of_subfaces(min_size: usize, max_size: usize) -> usize {
67    let mut d: i128 = 2i128.pow(max_size as u32) - 2;
68    for i in 1..min_size {
69        d -= comb(max_size, i) as i128;
70    }
71    d.max(0) as usize
72}
73
74fn comb(n: usize, k: usize) -> usize {
75    if k > n {
76        return 0;
77    }
78    let k = k.min(n - k);
79    let mut num: u128 = 1;
80    let mut den: u128 = 1;
81    for i in 0..k {
82        num *= (n - i) as u128;
83        den *= (i + 1) as u128;
84    }
85    (num / den) as usize
86}
87
88/// Edge IDs whose member sets are maximal (not a subset of another edge).
89fn maximal_edges<N, E, M>(h: &Hypergraph<N, E, M>) -> Vec<String> {
90    let all: Vec<(String, HashSet<String>)> = h
91        .edge_ids()
92        .into_iter()
93        .map(|e| {
94            let set: HashSet<String> = h.members(&e).unwrap_or_default().into_iter().collect();
95            (e, set)
96        })
97        .collect();
98    all.iter()
99        .filter(|(_id, set)| {
100            !all.iter()
101                .any(|(_oid, other)| other.len() > set.len() && set.is_subset(other))
102        })
103        .map(|(id, _)| id.clone())
104        .collect()
105}
106
107/// Whether an edge is a simplex: every subface (size ≥ min_size) is present.
108fn is_simplex(fs: &FaceSet, edge: &[String], min_size: usize) -> bool {
109    if edge.len() < min_size {
110        return true;
111    }
112    powerset(edge, min_size, edge.len())
113        .into_iter()
114        .all(|sub| fs.contains(&sub))
115}
116
117/// Simplicial fraction: what fraction of potential-simplex edges are simplices.
118/// XGI parity: `simplicial_fraction` (`simpliciality.py:325-383`).
119pub fn simplicial_fraction<N, E, M>(
120    h: &Hypergraph<N, E, M>,
121    min_size: usize,
122    exclude_min_size: bool,
123) -> f64 {
124    let fs = FaceSet::build(h);
125    let floor = min_size + exclude_min_size as usize;
126    let candidates: Vec<Vec<String>> = h
127        .edge_ids()
128        .into_iter()
129        .filter_map(|e| h.members(&e))
130        .filter(|m| m.len() >= floor)
131        .collect();
132    let ps = candidates.len();
133    if ps == 0 {
134        return f64::NAN;
135    }
136    let ns = candidates
137        .iter()
138        .filter(|e| is_simplex(&fs, e, min_size))
139        .count();
140    ns as f64 / ps as f64
141}
142
143/// Simplicial edit distance (normalized): fraction of missing subfaces needed
144/// to make `H` a simplicial complex. XGI parity: `simplicial_edit_distance`
145/// (`simpliciality.py:79-182`), including the redundant-missing-face
146/// correction (`:156-172`): a missing subface that is a subset of two or
147/// more maximal faces is otherwise double-counted once per maximal face that
148/// contains it. For each maximal face (in our own `maximal_edges()` order),
149/// XGI subtracts the *union* (deduplicated) of missing subfaces of its
150/// intersection with every EARLIER maximal face — by XGI's own linear scan
151/// order — whenever that intersection has `>= min_size` members.
152///
153/// We reuse `maximal_edges()`'s order rather than reproducing XGI's exact
154/// edge-insertion order. This is safe because the correction's *total*
155/// across the whole hypergraph is order-independent: consider a missing
156/// subface `s` (size `>= min_size`) that is a common subface of exactly `k`
157/// maximal faces. Any two of those `k` faces automatically intersect in a
158/// superset of `s` (so the `>= min_size` gate always fires for that pair,
159/// regardless of ordering). Visiting the `k` faces in ANY linear order, the
160/// first one contributes no subtraction for `s` (no earlier face to pair
161/// with), and each of the remaining `k - 1` faces contributes exactly one
162/// subtraction for `s` — the per-face union dedups repeated contributions
163/// from multiple earlier faces sharing `s`, so it's never subtracted twice
164/// from the same face. The total subtraction for `s` is therefore always
165/// `k - 1`, independent of which of the `k` faces is visited first, second,
166/// etc. — i.e. independent of the linear order chosen. `s`'s raw
167/// (uncorrected) count is exactly `k` (once per containing maximal face), so
168/// the corrected count is `k - (k - 1) = 1`, matching XGI's total regardless
169/// of maximal-face ordering.
170pub fn simplicial_edit_distance<N, E, M>(
171    h: &Hypergraph<N, E, M>,
172    min_size: usize,
173    exclude_min_size: bool,
174    normalize: bool,
175) -> f64 {
176    let fs = FaceSet::build(h);
177    let floor = min_size + exclude_min_size as usize;
178    let max_faces: Vec<Vec<String>> = maximal_edges(h)
179        .into_iter()
180        .filter_map(|e| h.members(&e))
181        .filter(|m| m.len() >= floor)
182        .collect();
183    if max_faces.is_empty() {
184        return f64::NAN;
185    }
186    let mut ms: i128 = 0;
187    for (i, e) in max_faces.iter().enumerate() {
188        let mf = count_missing_subfaces(&fs, e, min_size) as i128;
189        let e_set: HashSet<&String> = e.iter().collect();
190        let mut redundant: HashSet<Vec<String>> = HashSet::new();
191        for e2 in &max_faces[..i] {
192            let e2_set: HashSet<&String> = e2.iter().collect();
193            let inter: Vec<String> = e_set.intersection(&e2_set).map(|s| (*s).clone()).collect();
194            // XGI: `maxH.edges.neighbors(id1)` (share >= 1 node) gated by
195            // `len(c) >= min_size` (simpliciality.py:158-161).
196            if inter.is_empty() || inter.len() < min_size {
197                continue;
198            }
199            // Missing subfaces of the intersection, sizes min_size..=len —
200            // i.e. `_missing_subfaces` (strict subsets) plus the intersection
201            // itself if absent (simpliciality.py:162,167-168), in one pass.
202            for sub in powerset(&inter, min_size, inter.len()) {
203                if !fs.contains(&sub) {
204                    let mut key = sub;
205                    key.sort();
206                    redundant.insert(key);
207                }
208            }
209        }
210        ms += mf - redundant.len() as i128;
211    }
212    if !normalize {
213        return ms as f64;
214    }
215    let s = h
216        .edge_ids()
217        .into_iter()
218        .filter(|e| h.edge_size(e).map(|sz| sz >= min_size).unwrap_or(false))
219        .count();
220    let mf = max_faces.len();
221    let denom = s as i128 - mf as i128 + ms;
222    if denom > 0 {
223        ms as f64 / denom as f64
224    } else {
225        f64::NAN
226    }
227}
228
229/// Edit simpliciality = 1 − simplicial_edit_distance.
230/// XGI parity: `edit_simpliciality` (`simpliciality.py:17-76`).
231pub fn edit_simpliciality<N, E, M>(
232    h: &Hypergraph<N, E, M>,
233    min_size: usize,
234    exclude_min_size: bool,
235) -> f64 {
236    1.0 - simplicial_edit_distance(h, min_size, exclude_min_size, true)
237}
238
239/// Mean face edit distance over maximal faces.
240/// XGI parity: `mean_face_edit_distance` (`simpliciality.py:248-322`).
241pub fn mean_face_edit_distance<N, E, M>(
242    h: &Hypergraph<N, E, M>,
243    min_size: usize,
244    exclude_min_size: bool,
245    normalize: bool,
246) -> f64 {
247    let fs = FaceSet::build(h);
248    let floor = min_size + exclude_min_size as usize;
249    let max_faces: Vec<Vec<String>> = maximal_edges(h)
250        .into_iter()
251        .filter_map(|e| h.members(&e))
252        .filter(|m| m.len() >= floor)
253        .collect();
254    if max_faces.is_empty() {
255        return 0.0;
256    }
257    let count = max_faces.len() as f64;
258    let mut avg = 0.0;
259    for e in &max_faces {
260        if e.len() >= min_size {
261            let mut d = count_missing_subfaces(&fs, e, min_size) as f64;
262            let m = max_number_of_subfaces(min_size, e.len());
263            if normalize && m != 0 {
264                d /= m as f64;
265            }
266            avg += d / count;
267        }
268    }
269    avg
270}
271
272/// Face edit simpliciality = 1 − mean_face_edit_distance.
273/// XGI parity: `face_edit_simpliciality` (`simpliciality.py:185-245`).
274pub fn face_edit_simpliciality<N, E, M>(
275    h: &Hypergraph<N, E, M>,
276    min_size: usize,
277    exclude_min_size: bool,
278) -> f64 {
279    1.0 - mean_face_edit_distance(h, min_size, exclude_min_size, true)
280}