Skip to main content

hypergraph_rs/readwrite/
hif.rs

1//! Read/write the HIF standard (XGI `readwrite/hif.py` + `convert/hif_dict.py`).
2//! Undirected only; directed HIF requires DiHypergraph (deferred).
3
4use std::path::Path;
5
6use serde_json::{json, Map, Value};
7
8use super::ReadWriteError;
9use crate::Hypergraph;
10
11/// True if a serde object is present and non-empty.
12fn nonempty_obj(v: &Value) -> bool {
13    v.as_object().map(|o| !o.is_empty()).unwrap_or(false)
14}
15
16/// Serialize a hypergraph to the HIF dict. XGI `to_hif_dict` (undirected branch).
17pub fn to_hif_dict(h: &Hypergraph) -> Value {
18    // metadata from graph attrs — the FULL map (XGI: `data["metadata"].update(H._net_attr)`),
19    // not just "name" (see the Task 13 core-API note re: `graph_attrs()`).
20    let metadata = h.graph_attrs().clone();
21
22    // nodes: isolates OR nodes with attrs
23    let mut nodes = Vec::new();
24    for nid in h.node_ids() {
25        let attrs = h.node_attrs(&nid).cloned().unwrap_or(Value::Null);
26        let is_isolate = h.memberships(&nid).map(|m| m.is_empty()).unwrap_or(true);
27        if is_isolate || nonempty_obj(&attrs) {
28            let mut rec = Map::new();
29            rec.insert("node".to_string(), json!(nid));
30            if nonempty_obj(&attrs) {
31                rec.insert("attrs".to_string(), attrs);
32            }
33            nodes.push(Value::Object(rec));
34        }
35    }
36
37    // edges: empty edges OR edges with attrs
38    let mut edges = Vec::new();
39    let mut incidences = Vec::new();
40    for eid in h.edge_ids() {
41        let members = h.members(&eid).unwrap_or_default();
42        let attrs = h.edge_attrs(&eid).cloned().unwrap_or(Value::Null);
43        if members.is_empty() || nonempty_obj(&attrs) {
44            let mut rec = Map::new();
45            rec.insert("edge".to_string(), json!(eid));
46            if nonempty_obj(&attrs) {
47                rec.insert("attrs".to_string(), attrs);
48            }
49            edges.push(Value::Object(rec));
50        }
51        for node in members {
52            incidences.push(json!({"edge": eid, "node": node}));
53        }
54    }
55
56    // XGI parity: `to_hif_dict` (`convert/hif_dict.py:56-82`) builds `data["nodes"]`/
57    // `data["edges"]` via `data["nodes"].append(...)` inside a loop over isolates/attributed
58    // nodes (edges: empty/attributed edges) — if that loop body never runs, the key is never
59    // created at all (not present as an empty list). Reproduced here: omit the key when empty.
60    let mut obj = Map::new();
61    obj.insert("metadata".to_string(), Value::Object(metadata));
62    obj.insert("network-type".to_string(), json!("undirected"));
63    if !nodes.is_empty() {
64        obj.insert("nodes".to_string(), Value::Array(nodes));
65    }
66    if !edges.is_empty() {
67        obj.insert("edges".to_string(), Value::Array(edges));
68    }
69    obj.insert("incidences".to_string(), Value::Array(incidences));
70    Value::Object(obj)
71}
72
73/// Rebuild a hypergraph from a HIF dict. XGI `from_hif_dict` (undirected/asc branch).
74pub fn from_hif_dict(data: &Value) -> Result<Hypergraph, ReadWriteError> {
75    let network_type = data
76        .get("network-type")
77        .and_then(|v| v.as_str())
78        .unwrap_or("undirected");
79    if network_type == "directed" {
80        return Err(ReadWriteError::Format(
81            "directed HIF requires DiHypergraph (not supported in Phase 4)".into(),
82        ));
83    }
84
85    let mut h = Hypergraph::new();
86
87    if let Some(md) = data.get("metadata").and_then(|v| v.as_object()) {
88        for (k, v) in md {
89            h.set_graph_attr(k, v.clone());
90        }
91    }
92
93    let incidences = data
94        .get("incidences")
95        .and_then(|v| v.as_array())
96        .ok_or_else(|| ReadWriteError::Format("missing incidences".into()))?;
97    for rec in incidences {
98        let node = rec
99            .get("node")
100            .and_then(as_id)
101            .ok_or_else(|| ReadWriteError::Format("incidence missing node".into()))?;
102        let edge = rec
103            .get("edge")
104            .and_then(as_id)
105            .ok_or_else(|| ReadWriteError::Format("incidence missing edge".into()))?;
106        h.add_node_to_edge(&edge, &node)
107            .map_err(|e| ReadWriteError::Format(format!("incidence: {e}")))?;
108    }
109
110    if let Some(nodes) = data.get("nodes").and_then(|v| v.as_array()) {
111        for rec in nodes {
112            if let Some(nid) = rec.get("node").and_then(as_id) {
113                let attrs = rec.get("attrs").cloned();
114                if !h.has_node(&nid) {
115                    h.add_node(&nid, attrs.unwrap_or(Value::Null));
116                } else if let Some(a) = attrs {
117                    // Assign the attrs object wholesale rather than merging via
118                    // set_node_attributes: that merge calls `.as_object_mut()`
119                    // on the existing (Value::Null, from add_node_to_edge's
120                    // default) attrs, which returns None and silently no-ops
121                    // (P4-01 fix).
122                    if let Some(slot) = h.node_attrs_mut(&nid) {
123                        *slot = a;
124                    }
125                }
126            }
127        }
128    }
129
130    if let Some(edges) = data.get("edges").and_then(|v| v.as_array()) {
131        for rec in edges {
132            if let Some(eid) = rec.get("edge").and_then(as_id) {
133                let attrs = rec.get("attrs").cloned();
134                if h.has_edge(&eid) {
135                    if let Some(a) = attrs {
136                        // Same direct-assignment fix as above (P4-01).
137                        if let Some(slot) = h.edge_attrs_mut(&eid) {
138                            *slot = a;
139                        }
140                    }
141                } else {
142                    // Empty edge (in `edges` but no incidences) — Task 0's `add_empty_edge`
143                    // (the one sanctioned additive core method) represents exactly this XGI
144                    // deviation-shim case, which plain `add_edge` rejects.
145                    h.add_empty_edge(Some(eid), attrs.unwrap_or(Value::Null));
146                }
147            }
148        }
149    }
150
151    Ok(h)
152}
153
154/// Coerce a JSON id (string or number) to a String key.
155fn as_id(v: &Value) -> Option<String> {
156    match v {
157        Value::String(s) => Some(s.clone()),
158        Value::Number(n) => Some(n.to_string()),
159        _ => None,
160    }
161}
162
163/// Write a hypergraph to a HIF JSON file. XGI `write_hif`.
164pub fn write_hif(h: &Hypergraph, path: &Path) -> Result<(), ReadWriteError> {
165    let data = to_hif_dict(h);
166    std::fs::write(path, serde_json::to_string_pretty(&data)?)?;
167    Ok(())
168}
169
170/// Read a hypergraph from a HIF JSON file. XGI `read_hif`.
171pub fn read_hif(path: &Path) -> Result<Hypergraph, ReadWriteError> {
172    let s = std::fs::read_to_string(path)?;
173    let data: Value = serde_json::from_str(&s)?;
174    from_hif_dict(&data)
175}