Skip to main content

hypergraph_rs/raster/ingest/
edges.rs

1//! Edge ingest: `kind` dispatch into `Community` / `Extraction` / `Industry`
2//! (Phase I, Task 3). See the [`super`] module doc for the normative
3//! attribute contract this file implements.
4
5use std::collections::HashMap;
6
7use serde_json::Value;
8
9use crate::raster::algebra::Industry;
10use crate::raster::deck::{Community, Extraction};
11use crate::Hypergraph;
12
13use super::{
14    AttrContract, IngestError, DEFAULT_COMMUNITY_NAME, DEFAULT_LANE, DEFAULT_MASS, KIND_COMMUNITY,
15    KIND_EXTRACTION, KIND_INDUSTRY,
16};
17
18/// The three edge collections ingest can produce from one `Hypergraph`, plus
19/// the edges it could not classify and whether any industry's `lane`
20/// defaulted.
21#[derive(Debug, Clone, PartialEq)]
22pub struct IngestedEdges {
23    pub communities: Vec<Community>,
24    pub extraction: Vec<Extraction>,
25    pub industries: Vec<Industry>,
26    /// Edge ids whose `kind` was missing or unrecognised — reported, never
27    /// an error (a real hypergraph may carry edges the instruments have no
28    /// use for).
29    pub skipped: Vec<String>,
30    pub lane_defaulted: bool,
31}
32
33/// Read a required, finite `f64` edge attribute. `key` absent ⇒
34/// [`IngestError::MissingEdgeAttr`]; present but not a finite number ⇒
35/// [`IngestError::BadAttrType`].
36fn read_required_edge_f64(
37    attrs: &Value,
38    key: &str,
39    edge: &str,
40    kind: &str,
41) -> Result<f64, IngestError> {
42    let v = attrs.get(key).ok_or_else(|| IngestError::MissingEdgeAttr {
43        edge: edge.to_string(),
44        kind: kind.to_string(),
45        key: key.to_string(),
46    })?;
47    let f = v.as_f64().ok_or_else(|| IngestError::BadAttrType {
48        owner: edge.to_string(),
49        key: key.to_string(),
50    })?;
51    if !f.is_finite() {
52        return Err(IngestError::BadAttrType {
53            owner: edge.to_string(),
54            key: key.to_string(),
55        });
56    }
57    Ok(f)
58}
59
60/// Read an optional, finite `f64` edge attribute: absent ⇒ `default`;
61/// present but not a finite number ⇒ [`IngestError::BadAttrType`].
62fn read_optional_edge_f64(
63    attrs: &Value,
64    key: &str,
65    edge: &str,
66    default: f64,
67) -> Result<f64, IngestError> {
68    match attrs.get(key) {
69        None => Ok(default),
70        Some(v) => {
71            let f = v.as_f64().ok_or_else(|| IngestError::BadAttrType {
72                owner: edge.to_string(),
73                key: key.to_string(),
74            })?;
75            if !f.is_finite() {
76                return Err(IngestError::BadAttrType {
77                    owner: edge.to_string(),
78                    key: key.to_string(),
79                });
80            }
81            Ok(f)
82        }
83    }
84}
85
86/// Read an optional string edge attribute: absent ⇒ `None`; present but not
87/// a string ⇒ [`IngestError::BadAttrType`].
88fn read_optional_str<'a>(
89    attrs: &'a Value,
90    key: &str,
91    edge: &str,
92) -> Result<Option<&'a str>, IngestError> {
93    match attrs.get(key) {
94        None => Ok(None),
95        Some(v) => v
96            .as_str()
97            .map(Some)
98            .ok_or_else(|| IngestError::BadAttrType {
99                owner: edge.to_string(),
100                key: key.to_string(),
101            }),
102    }
103}
104
105/// Read the required `head` string attribute for an extraction edge.
106fn read_head(attrs: &Value, key: &str, edge: &str) -> Result<String, IngestError> {
107    let v = attrs.get(key).ok_or_else(|| IngestError::MissingEdgeAttr {
108        edge: edge.to_string(),
109        kind: KIND_EXTRACTION.to_string(),
110        key: key.to_string(),
111    })?;
112    v.as_str()
113        .map(str::to_string)
114        .ok_or_else(|| IngestError::BadAttrType {
115            owner: edge.to_string(),
116            key: key.to_string(),
117        })
118}
119
120/// Read `lane`: absent ⇒ [`DEFAULT_LANE`] (and the caller flags
121/// `lane_defaulted`); present ⇒ must be a `u8` in `0..=3`, else
122/// [`IngestError::BadAttrType`].
123fn read_lane(
124    attrs: &Value,
125    key: &str,
126    edge: &str,
127    lane_defaulted: &mut bool,
128) -> Result<u8, IngestError> {
129    match attrs.get(key) {
130        None => {
131            *lane_defaulted = true;
132            Ok(DEFAULT_LANE)
133        }
134        Some(v) => {
135            let n = v.as_u64().ok_or_else(|| IngestError::BadAttrType {
136                owner: edge.to_string(),
137                key: key.to_string(),
138            })?;
139            if n > 3 {
140                return Err(IngestError::BadAttrType {
141                    owner: edge.to_string(),
142                    key: key.to_string(),
143                });
144            }
145            Ok(n as u8)
146        }
147    }
148}
149
150/// Resolve a node id string to its dense render-space index, or
151/// [`IngestError::UnknownNode`] if it is not in the hypergraph. This cannot
152/// normally trigger for edge members (`add_edge` auto-creates them), but the
153/// check is cheap and the alternative is an out-of-bounds index downstream.
154fn resolve(index: &HashMap<&str, usize>, edge: &str, node: &str) -> Result<usize, IngestError> {
155    index
156        .get(node)
157        .copied()
158        .ok_or_else(|| IngestError::UnknownNode {
159            edge: edge.to_string(),
160            node: node.to_string(),
161        })
162}
163
164/// Read `links`: absent ⇒ `[]`; present ⇒ must be an array of 2-element
165/// arrays of node-id strings, each drawn from `members` (this edge's own
166/// members), else [`IngestError::LinkOutsideCommunity`]. Any other JSON
167/// shape ⇒ [`IngestError::BadAttrType`]. Bounded by the number of links
168/// present.
169fn read_links(
170    attrs: &Value,
171    key: &str,
172    edge: &str,
173    members: &[String],
174    index: &HashMap<&str, usize>,
175) -> Result<Vec<(usize, usize)>, IngestError> {
176    let raw = match attrs.get(key) {
177        None => return Ok(Vec::new()),
178        Some(v) => v,
179    };
180    let arr = raw.as_array().ok_or_else(|| IngestError::BadAttrType {
181        owner: edge.to_string(),
182        key: key.to_string(),
183    })?;
184    let mut links = Vec::with_capacity(arr.len());
185    for item in arr {
186        let pair = item.as_array().ok_or_else(|| IngestError::BadAttrType {
187            owner: edge.to_string(),
188            key: key.to_string(),
189        })?;
190        if pair.len() != 2 {
191            return Err(IngestError::BadAttrType {
192                owner: edge.to_string(),
193                key: key.to_string(),
194            });
195        }
196        let a = pair[0].as_str().ok_or_else(|| IngestError::BadAttrType {
197            owner: edge.to_string(),
198            key: key.to_string(),
199        })?;
200        let b = pair[1].as_str().ok_or_else(|| IngestError::BadAttrType {
201            owner: edge.to_string(),
202            key: key.to_string(),
203        })?;
204        for node in [a, b] {
205            if !members.iter().any(|m| m == node) {
206                return Err(IngestError::LinkOutsideCommunity {
207                    edge: edge.to_string(),
208                    node: node.to_string(),
209                });
210            }
211        }
212        links.push((resolve(index, edge, a)?, resolve(index, edge, b)?));
213    }
214    Ok(links)
215}
216
217/// Ingest every edge into `communities` / `extraction` / `industries`,
218/// dispatched on `kind`; unrecognised or missing `kind` is skipped and
219/// reported, never an error. Order within each output vec follows
220/// [`Hypergraph::edge_ids`] relative order — load-bearing for `industries`
221/// (`algebra::transform` and `build_sankey` iterate it in slice order).
222///
223/// Bounded: one pass over `h.edge_ids()` (edge count); each edge's own
224/// `members`/`links` loops are bounded by that edge's member/link count.
225///
226/// **Deviation from the plan's `pub(crate)` sketch**, matching Task 2's
227/// `ingest_nodes` precedent: `tests/test_ingest.rs` is an external
228/// integration-test crate, which cannot name a `pub(crate)` type or call a
229/// `pub(crate)` function, so both `ingest_edges` and [`IngestedEdges`] are
230/// `pub` (re-exported from [`super`]) exactly as `ingest_nodes` already is.
231pub fn ingest_edges(
232    h: &Hypergraph<Value, Value, Value>,
233    c: &AttrContract,
234    index: &HashMap<&str, usize>,
235) -> Result<IngestedEdges, IngestError> {
236    let edge_ids = h.edge_ids();
237    static EMPTY: Value = Value::Null;
238
239    let mut communities = Vec::new();
240    let mut extraction = Vec::new();
241    let mut industries = Vec::new();
242    let mut skipped = Vec::new();
243    let mut lane_defaulted = false;
244
245    for edge in &edge_ids {
246        let attrs = h.edge_attrs(edge).unwrap_or(&EMPTY);
247        let members = h.members(edge).unwrap_or_default();
248
249        let kind = match attrs.get(&c.kind).and_then(Value::as_str) {
250            Some(k) => k,
251            None => {
252                skipped.push(edge.clone());
253                continue;
254            }
255        };
256
257        match kind {
258            KIND_COMMUNITY => {
259                let name = read_optional_str(attrs, &c.name, edge)?
260                    .map(str::to_string)
261                    .unwrap_or_else(|| format!("{DEFAULT_COMMUNITY_NAME}{edge}"));
262                let links = read_links(attrs, &c.links, edge, &members, index)?;
263                let mut member_idxs = Vec::with_capacity(members.len());
264                for m in &members {
265                    member_idxs.push(resolve(index, edge, m)?);
266                }
267                communities.push(Community {
268                    name,
269                    members: member_idxs,
270                    links,
271                });
272            }
273            KIND_EXTRACTION => {
274                let head = read_head(attrs, &c.head, edge)?;
275                if !members.iter().any(|m| m == &head) {
276                    return Err(IngestError::HeadNotMember {
277                        edge: edge.clone(),
278                        node: head,
279                    });
280                }
281                let mass = read_optional_edge_f64(attrs, &c.mass, edge, DEFAULT_MASS)?;
282                let head_idx = resolve(index, edge, &head)?;
283                let mut tails = Vec::with_capacity(members.len());
284                for m in &members {
285                    if m == &head {
286                        continue;
287                    }
288                    tails.push(resolve(index, edge, m)?);
289                }
290                extraction.push(Extraction {
291                    tails,
292                    head: head_idx,
293                    mass,
294                });
295            }
296            KIND_INDUSTRY => {
297                let name = read_optional_str(attrs, &c.name, edge)?
298                    .map(str::to_string)
299                    .unwrap_or_else(|| edge.clone());
300                let cval = read_required_edge_f64(attrs, &c.c, edge, KIND_INDUSTRY)?;
301                let v = read_required_edge_f64(attrs, &c.v, edge, KIND_INDUSTRY)?;
302                let e = read_required_edge_f64(attrs, &c.e, edge, KIND_INDUSTRY)?;
303                if v == 0.0 {
304                    return Err(IngestError::DegenerateIndustry { edge: edge.clone() });
305                }
306                let lane = read_lane(attrs, &c.lane, edge, &mut lane_defaulted)?;
307                industries.push(Industry {
308                    name,
309                    lane,
310                    c: cval,
311                    v,
312                    e,
313                });
314            }
315            _ => {
316                skipped.push(edge.clone());
317            }
318        }
319    }
320
321    Ok(IngestedEdges {
322        communities,
323        extraction,
324        industries,
325        skipped,
326        lane_defaulted,
327    })
328}