Skip to main content

hypergraph_rs/core/
globalviews.rs

1//! Read-only global views over a hypergraph.
2
3use std::collections::BTreeSet;
4
5use serde_json::Value;
6
7use super::hypergraph::Hypergraph;
8
9/// A frozen induced sub-hypergraph. Keeps `nodes` (default all) and the `edges`
10/// (default all) that are subsets of the kept nodes; optionally drops the
11/// resulting isolates. XGI parity: `xgi.subhypergraph(H, nodes, edges,
12/// keep_isolates)` (globalviews.py:19-74).
13pub fn subhypergraph(
14    h: &Hypergraph<Value, Value, Value>,
15    nodes: Option<&[String]>,
16    edges: Option<&[String]>,
17    keep_isolates: bool,
18) -> Hypergraph<Value, Value, Value> {
19    let node_set: BTreeSet<String> = match nodes {
20        None => h.node_ids().into_iter().collect(),
21        Some(ns) => ns.iter().filter(|n| h.has_node(n)).cloned().collect(),
22    };
23    let edge_set: BTreeSet<String> = match edges {
24        None => h.edge_ids().into_iter().collect(),
25        Some(es) => es.iter().filter(|e| h.has_edge(e)).cloned().collect(),
26    };
27
28    let mut new = Hypergraph::new();
29    for (k, val) in h.graph_attrs().clone() {
30        new.set_graph_attr(&k, val);
31    }
32    // Nodes in insertion order.
33    for nid in h.node_ids() {
34        if node_set.contains(&nid) {
35            let attrs = h.node_attrs(&nid).cloned().unwrap_or(Value::Null);
36            new.add_node(&nid, attrs);
37        }
38    }
39    // Edges that are subsets of the kept node set, in insertion order.
40    for eid in h.edge_ids() {
41        if !edge_set.contains(&eid) {
42            continue;
43        }
44        let members = h.members(&eid).unwrap_or_default();
45        // D1-ripple: an empty edge is a trivial subset of any node set and is
46        // retained (matches XGI subhypergraph, which does not special-case size-0).
47        if members.iter().all(|m| node_set.contains(m)) {
48            let attrs = h.edge_attrs(&eid).cloned().unwrap_or(Value::Null);
49            let _ = new.add_edge(members, Some(eid.clone()), attrs);
50        }
51    }
52
53    if !keep_isolates {
54        let isolates = new.isolate_node_ids();
55        let _ = new.remove_nodes_from(&isolates, false, true);
56    }
57    new.freeze();
58    new
59}