Skip to main content

hypergraph_rs/algorithms/
properties.rs

1//! Structural properties of a hypergraph (`xgi/algorithms/properties.py`).
2
3use std::collections::BTreeSet;
4
5use crate::Hypergraph;
6
7/// Number of edges of order `d` (size `d+1`); all edges if `d` is `None`.
8/// XGI parity: `num_edges_order` (`properties.py:92-117`).
9pub fn num_edges_order<N, E, M>(h: &Hypergraph<N, E, M>, d: Option<usize>) -> usize {
10    match d {
11        None => h.num_edges(),
12        Some(order) => h
13            .edge_ids()
14            .iter()
15            .filter(|e| h.edge_size(e) == Some(order + 1))
16            .count(),
17    }
18}
19
20/// Maximum edge order (max size − 1). `None` for an empty hypergraph with no
21/// nodes; `Some(0)` when there are nodes but no edges. XGI parity:
22/// `max_edge_order` (`properties.py:120-141`), with one documented deviation
23/// (see below).
24pub fn max_edge_order<N, E, M>(h: &Hypergraph<N, E, M>) -> Option<usize> {
25    let sizes: Vec<usize> = h.edge_ids().iter().filter_map(|e| h.edge_size(e)).collect();
26    if sizes.is_empty() {
27        // No edges at all: XGI's `H._edge` is falsy, so `d_max = 0 if
28        // H._node else None`.
29        return if h.num_nodes() > 0 { Some(0) } else { None };
30    }
31    // D1-ripple: size-0 edges (constructible after D1) carry no order and are
32    // excluded from the order-stat, matching XGI's order = size - 1 semantics
33    // (a size-0 edge would otherwise underflow this usize subtraction).
34    //
35    // REV-2: if that filter leaves nothing, at least one edge exists, but
36    // every edge is size-0 (the largest edge is empty). XGI computes
37    // `max(len(edge) for edge in H._edge.values()) - 1 == -1` here
38    // (oracle-verified 2026-07-22: xgi 0.10.2, H.add_edge([]) ->
39    // xgi.max_edge_order(H) == -1, and this holds whether or not other nodes
40    // exist). usize cannot represent -1; None is the closest sane Rust
41    // rendering (deviation, oracle-verified 2026-07-22). This is distinct
42    // from the "no edges at all" case above, which XGI (and we) render as
43    // Some(0) when nodes are present.
44    sizes.into_iter().filter(|&s| s > 0).max().map(|s| s - 1)
45}
46
47/// Whether `d` is a possible order (0 ≤ d ≤ max order).
48/// XGI parity: `is_possible_order` (`properties.py:144-161`).
49pub fn is_possible_order<N, E, M>(h: &Hypergraph<N, E, M>, d: usize) -> bool {
50    matches!(max_edge_order(h), Some(dmax) if d <= dmax)
51}
52
53/// Unique edge sizes in ascending order. XGI parity: `unique_edge_sizes`
54/// (`properties.py:321-334`).
55pub fn unique_edge_sizes<N, E, M>(h: &Hypergraph<N, E, M>) -> Vec<usize> {
56    let set: BTreeSet<usize> = h.edge_ids().iter().filter_map(|e| h.edge_size(e)).collect();
57    set.into_iter().collect()
58}
59
60/// The order of uniformity if all non-singleton edges share one size, else
61/// `None`. XGI parity: `is_uniform` (`properties.py:164-197`) — returns
62/// `d = size − 1` on success, `False` otherwise (mapped to `None`), with one
63/// documented deviation (see below).
64pub fn is_uniform<N, E, M>(h: &Hypergraph<N, E, M>) -> Option<usize> {
65    let mut sizes: BTreeSet<usize> = unique_edge_sizes(h).into_iter().collect();
66    sizes.remove(&1); // discard singletons
67    if sizes.len() != 1 {
68        return None;
69    }
70    let s = *sizes.iter().next().expect("len checked == 1 above");
71    if s == 0 {
72        // REV-1: the only non-singleton edge size is 0 (constructible after
73        // D1). XGI computes `int(edge_sizes.pop() - 1) == -1` here — a
74        // truthy-but-negative "order" (oracle-verified 2026-07-22: xgi
75        // 0.10.2, H.add_edge([]) -> xgi.is_uniform(H) == -1). usize cannot
76        // represent -1; None ("not uniform") is the closest sane Rust
77        // rendering (deviation, oracle-verified 2026-07-22) — this is also
78        // what previously underflowed `s - 1` and panicked.
79        return None;
80    }
81    Some(s - 1)
82}
83
84/// Occurrences of each degree value, index = degree, from 0 to max degree.
85/// XGI parity: `degree_counts` (`properties.py:244-282`).
86pub fn degree_counts<N, E, M>(h: &Hypergraph<N, E, M>, order: Option<usize>) -> Vec<usize> {
87    let degs: Vec<usize> = h
88        .node_ids()
89        .iter()
90        .filter_map(|n| h.node_degree(n, order))
91        .collect();
92    let max_d = degs.iter().copied().max().unwrap_or(0);
93    let mut counts = vec![0usize; max_d + 1];
94    for d in degs {
95        counts[d] += 1;
96    }
97    counts
98}
99
100/// Observed degrees (ascending) and their counts.
101/// XGI parity: `degree_histogram` (`properties.py:285-318`).
102pub fn degree_histogram<N, E, M>(h: &Hypergraph<N, E, M>) -> (Vec<usize>, Vec<usize>) {
103    let mut counts: std::collections::BTreeMap<usize, usize> = std::collections::BTreeMap::new();
104    for n in h.node_ids() {
105        let d = h.node_degree(&n, None).unwrap_or(0);
106        *counts.entry(d).or_insert(0) += 1;
107    }
108    let degrees: Vec<usize> = counts.keys().copied().collect();
109    let heights: Vec<usize> = counts.values().copied().collect();
110    (degrees, heights)
111}
112
113/// The edge neighbourhood of a node: the members of each edge containing it,
114/// excluding the node itself (or including it if `include_self`).
115/// XGI parity: `edge_neighborhood` (`properties.py:200-241`).
116pub fn edge_neighborhood<N, E, M>(
117    h: &Hypergraph<N, E, M>,
118    n: &str,
119    include_self: bool,
120) -> Vec<Vec<String>> {
121    let memberships = match h.memberships(n) {
122        Some(m) => m,
123        None => return Vec::new(),
124    };
125    memberships
126        .iter()
127        .map(|e| {
128            let members = h.members(e).unwrap_or_default();
129            if include_self {
130                members
131            } else {
132                members.into_iter().filter(|m| m != n).collect()
133            }
134        })
135        .collect()
136}
137
138/// Binomial coefficient `n choose k` (exact, u128 to resist overflow at scale).
139fn comb(n: usize, k: usize) -> f64 {
140    if k > n {
141        return 0.0;
142    }
143    let k = k.min(n - k);
144    let mut num: u128 = 1;
145    let mut den: u128 = 1;
146    for i in 0..k {
147        num *= (n - i) as u128;
148        den *= (i + 1) as u128;
149    }
150    (num / den) as f64
151}
152
153/// Hypergraph density = existing edges / possible edges.
154/// XGI parity: `density` (`properties.py:337-425`). `order`/`max_order` are
155/// mutually exclusive (order wins); `ignore_singletons` drops order-0 edges.
156pub fn density<N, E, M>(
157    h: &Hypergraph<N, E, M>,
158    order: Option<usize>,
159    max_order: Option<usize>,
160    ignore_singletons: bool,
161) -> f64 {
162    let n = h.num_nodes();
163    assert!(n >= 1, "density is not defined for an empty hypergraph");
164    if h.num_edges() < 1 {
165        return 0.0;
166    }
167    let count_order = |d: usize| num_edges_order(h, Some(d));
168    let count_leq = |dmax: usize| (0..=dmax).map(count_order).sum::<usize>();
169
170    let (numer, denom): (f64, f64) = match (order, max_order) {
171        (None, None) => {
172            let mut numer = h.num_edges() as f64;
173            let mut denom = 2f64.powi(n as i32) - 1.0;
174            if ignore_singletons {
175                numer -= count_order(0) as f64;
176                denom -= n as f64;
177            }
178            (numer, denom)
179        }
180        (None, Some(mo)) => {
181            assert!(mo < n, "max_order must be smaller than the number of nodes");
182            let mut numer = count_leq(mo) as f64;
183            let mut denom: f64 = (0..=mo).map(|o| comb(n, o + 1)).sum();
184            if ignore_singletons {
185                numer -= count_order(0) as f64;
186                denom -= n as f64;
187            }
188            (numer, denom)
189        }
190        (Some(o), _) => {
191            assert!(o < n, "order must be smaller than the number of nodes");
192            if ignore_singletons && o == 0 {
193                return 0.0;
194            }
195            (count_order(o) as f64, comb(n, o + 1))
196        }
197    };
198    if denom == 0.0 {
199        0.0
200    } else {
201        numer / denom
202    }
203}
204
205/// Density of the incidence matrix = nnz / (n · num_edges_considered).
206/// XGI parity: `incidence_density` (`properties.py:428-494`).
207pub fn incidence_density<N, E, M>(
208    h: &Hypergraph<N, E, M>,
209    order: Option<usize>,
210    max_order: Option<usize>,
211    ignore_singletons: bool,
212) -> f64 {
213    let n = h.num_nodes();
214    assert!(
215        n >= 1,
216        "incidence density is not defined for an empty hypergraph"
217    );
218    if h.num_edges() < 1 {
219        return 0.0;
220    }
221    if let Some(mo) = max_order {
222        if order.is_none() {
223            assert!(mo < n, "max_order must be smaller than the number of nodes");
224        }
225    }
226    if let Some(o) = order {
227        assert!(o < n, "order must be smaller than the number of nodes");
228    }
229    let keep: Vec<String> = h
230        .edge_ids()
231        .into_iter()
232        .filter(|e| {
233            let size = h.edge_size(e).unwrap_or(0);
234            let ord = size.saturating_sub(1);
235            match (order, max_order) {
236                (Some(o), _) => {
237                    if ignore_singletons && o == 0 {
238                        false
239                    } else {
240                        ord == o
241                    }
242                }
243                (None, Some(mo)) => ord <= mo && (!ignore_singletons || ord > 0),
244                (None, None) => !ignore_singletons || ord > 0,
245            }
246        })
247        .collect();
248    let denom = (n * keep.len()) as f64;
249    let numer: f64 = keep.iter().filter_map(|e| h.edge_size(e)).sum::<usize>() as f64;
250    if denom == 0.0 {
251        0.0
252    } else {
253        numer / denom
254    }
255}