Skip to main content

hypergraph_rs/utils/
mod.rs

1//! Pure utility functions ported from `xgi/utils/` (non-Python-machinery only).
2//!
3//! Ported: `dual_dict`, `powerset`, `subfaces`, `get_network_type`,
4//! `convert_labels_to_integers`. See the Phase-6 plan header for the exclusion list.
5
6use crate::Hypergraph;
7use indexmap::IndexMap;
8use serde_json::{json, Value};
9use thiserror::Error;
10
11/// Errors raised by utility functions.
12#[derive(Debug, Clone, Error, PartialEq)]
13pub enum UtilError {
14    /// `subfaces` was asked for an order larger than the max order of the input edges.
15    #[error("order {order} exceeds the maximum edge order {max_order}")]
16    OrderTooLarge { order: i64, max_order: i64 },
17}
18
19/// Reverse an id→members map into a member→ids map.
20///
21/// XGI parity: `xgi.dual_dict` (`utils/utilities.py:65-94`). XGI returns
22/// `defaultdict(set)` (hash-ordered); we return an insertion-ordered `IndexMap`
23/// keyed by node first-seen order (a III.7 determinism improvement). Per-node edge
24/// lists preserve the order in which edges were encountered.
25pub fn dual_dict(edge_dict: &IndexMap<String, Vec<String>>) -> IndexMap<String, Vec<String>> {
26    let mut node_dict: IndexMap<String, Vec<String>> = IndexMap::new();
27    for (edge_id, members) in edge_dict {
28        for node in members {
29            node_dict
30                .entry(node.clone())
31                .or_default()
32                .push(edge_id.clone());
33        }
34    }
35    node_dict
36}
37
38/// All `r`-length index-combinations of `items`, in lexicographic-by-index order.
39///
40/// Matches Python `itertools.combinations` ordering. Bounded: at most `C(n, r)`
41/// combinations, each built by a fixed-length inner loop.
42fn combinations(items: &[String], r: usize) -> Vec<Vec<String>> {
43    let n = items.len();
44    let mut out: Vec<Vec<String>> = Vec::new();
45    if r == 0 {
46        out.push(Vec::new());
47        return out;
48    }
49    if r > n {
50        return out;
51    }
52    let mut idx: Vec<usize> = (0..r).collect();
53    loop {
54        out.push(idx.iter().map(|&i| items[i].clone()).collect());
55        // Advance the index vector (odometer over strictly-increasing indices).
56        let mut i = r; // position to bump, scanned from the right
57        while i > 0 {
58            i -= 1;
59            if idx[i] != i + n - r {
60                idx[i] += 1;
61                for j in (i + 1)..r {
62                    idx[j] = idx[j - 1] + 1;
63                }
64                break;
65            }
66            if i == 0 {
67                return out; // all positions maxed out
68            }
69        }
70    }
71}
72
73/// All subsets of `items`, with XGI's option flags.
74///
75/// XGI parity: `xgi.powerset` (`utils/utilities.py:97-151`).
76/// `include_empty` overrides `include_singletons` when true; `max_size` caps the
77/// largest subset returned. Order is by ascending size, then lexicographic-by-index.
78///
79/// **Flag order differs from XGI.** Python's positional signature is
80/// `powerset(iterable, include_empty, include_full, include_singletons, max_size)`; this
81/// Rust signature is `(items, include_empty, include_singletons, include_full, max_size)`
82/// — `include_full` and `include_singletons` are swapped. A future PyO3 binding that
83/// mirrors Python's positional call order must remap these two arguments, not pass them
84/// straight through.
85pub fn powerset(
86    items: &[String],
87    include_empty: bool,
88    include_singletons: bool,
89    include_full: bool,
90    max_size: Option<usize>,
91) -> Vec<Vec<String>> {
92    let n = items.len();
93    let mut start = if include_singletons { 1 } else { 2 };
94    if include_empty {
95        start = 0;
96    }
97    let max = match max_size {
98        Some(m) => m.min(n),
99        None => {
100            if include_full {
101                n
102            } else {
103                n.saturating_sub(1)
104            }
105        }
106    };
107    let mut out: Vec<Vec<String>> = Vec::new();
108    let mut r = start;
109    while r <= max {
110        out.extend(combinations(items, r));
111        r += 1;
112    }
113    out
114}
115
116/// Subfaces of a list of hyperedges.
117///
118/// XGI parity: `xgi.subfaces` (`utils/utilities.py:310-374`). Faces are NOT deduplicated
119/// (a face may appear once per parent edge), matching XGI. Singleton and empty edges
120/// contribute nothing.
121pub fn subfaces(edges: &[Vec<String>], order: Option<i64>) -> Result<Vec<Vec<String>>, UtilError> {
122    let max_order: i64 = edges.iter().map(|e| e.len() as i64 - 1).max().unwrap_or(-1);
123    if let Some(o) = order {
124        if o > max_order {
125            return Err(UtilError::OrderTooLarge {
126                order: o,
127                max_order,
128            });
129        }
130    }
131    let mut faces: Vec<Vec<String>> = Vec::new();
132    for edge in edges {
133        let size = edge.len();
134        if size <= 1 {
135            continue;
136        }
137        let to_add = match order {
138            None => powerset(edge, false, true, false, None),
139            Some(-1) => combinations(edge, size - 1),
140            Some(o) if o >= 0 => combinations(edge, (o + 1) as usize),
141            Some(_) => Vec::new(), // order < -1 is undefined in XGI; treat as empty
142        };
143        faces.extend(to_add);
144    }
145    Ok(faces)
146}
147
148/// The lowercased network type name.
149///
150/// XGI parity: `xgi.get_network_type` (`utils/utilities.py:560-561`). For the undirected
151/// `Hypergraph` this is the constant `"hypergraph"` (matching XGI's
152/// `type(H).__name__.lower()` for `Hypergraph`).
153pub fn get_network_type(_h: &Hypergraph) -> String {
154    "hypergraph".to_string()
155}
156
157/// Relabel node and edge ids to sequential integer strings, stashing the old ids.
158///
159/// XGI parity: `xgi.convert_labels_to_integers` (`utils/utilities.py:377-452`). Nodes and
160/// edges are mapped to `"0".."n-1"` / `"0".."m-1"` in insertion order; the old id is
161/// written to `label_attribute` on each. Graph-level attrs are carried over. Returns a
162/// new `Hypergraph` (we rebuild rather than clear-in-place; see the Phase-6 plan header).
163pub fn convert_labels_to_integers(h: &Hypergraph, label_attribute: &str) -> Hypergraph {
164    let node_index: IndexMap<String, usize> = h
165        .node_ids()
166        .into_iter()
167        .enumerate()
168        .map(|(i, id)| (id, i))
169        .collect();
170    let edge_index: IndexMap<String, usize> = h
171        .edge_ids()
172        .into_iter()
173        .enumerate()
174        .map(|(i, id)| (id, i))
175        .collect();
176
177    let mut out = Hypergraph::new();
178
179    // Carry over graph-level attributes.
180    for (k, v) in h.graph_attrs() {
181        out.set_graph_attr(k, v.clone());
182    }
183
184    // Nodes: new integer id + old id under label_attribute.
185    for (old_id, &i) in &node_index {
186        let mut obj = h
187            .node_attrs(old_id)
188            .and_then(|v| v.as_object().cloned())
189            .unwrap_or_default();
190        obj.insert(label_attribute.to_string(), json!(old_id));
191        out.add_node(&i.to_string(), Value::Object(obj));
192    }
193
194    // Edges: remap members, new integer id + old id under label_attribute.
195    for (old_edge, &j) in &edge_index {
196        let members: Vec<String> = h
197            .members(old_edge)
198            .unwrap_or_default()
199            .iter()
200            .map(|m| node_index[m].to_string())
201            .collect();
202        let mut obj = h
203            .edge_attrs(old_edge)
204            .and_then(|v| v.as_object().cloned())
205            .unwrap_or_default();
206        obj.insert(label_attribute.to_string(), json!(old_edge));
207        out.add_edge(members, Some(j.to_string()), Value::Object(obj))
208            .expect("relabeled edge has non-empty members and a fresh unique id");
209    }
210
211    out
212}