hypergraph_rs/core/
globalviews.rs1use std::collections::BTreeSet;
4
5use serde_json::Value;
6
7use super::hypergraph::Hypergraph;
8
9pub 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 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 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 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}