Skip to main content

hypergraph_rs/readwrite/
bigg.rs

1//! BIGG metabolic-network parsing (XGI `readwrite/bigg_data.py`).
2//!
3//! Offline dict → DiHypergraph. The HTTP fetch (`load_bigg_data`) is behind the
4//! `network` feature and unimplemented (see the plan).
5
6use serde_json::Value;
7
8use super::ReadWriteError;
9use crate::DiHypergraph;
10
11/// Convert a BIGG model dict (optionally with the index dict for organism metadata)
12/// into a DiHypergraph. XGI `_bigg_to_dihypergraph`.
13pub fn bigg_dict_to_dihypergraph(
14    model: &Value,
15    index: Option<&Value>,
16) -> Result<DiHypergraph, ReadWriteError> {
17    let mut dh = DiHypergraph::new();
18
19    let id = model
20        .get("id")
21        .and_then(|v| v.as_str())
22        .ok_or_else(|| ReadWriteError::Format("BIGG model missing id".into()))?;
23    dh.set_graph_attr("name", Value::String(id.to_string()));
24
25    if let Some(idx) = index {
26        if let Some(results) = idx.get("results").and_then(|v| v.as_array()) {
27            if let Some(info) = results
28                .iter()
29                .find(|it| it.get("bigg_id").and_then(|v| v.as_str()) == Some(id))
30            {
31                if let Some(org) = info.get("organism") {
32                    dh.set_graph_attr("organism", org.clone());
33                }
34            }
35        }
36    }
37
38    // metabolites -> nodes
39    let metabolites = model
40        .get("metabolites")
41        .and_then(|v| v.as_array())
42        .ok_or_else(|| ReadWriteError::Format("BIGG model missing metabolites".into()))?;
43    for m in metabolites {
44        if let Some(mid) = m.get("id").and_then(|v| v.as_str()) {
45            let name = m.get("name").cloned().unwrap_or(Value::Null);
46            dh.add_node(mid, serde_json::json!({ "name": name }));
47        }
48    }
49
50    // reactions -> directed edges
51    let reactions = model
52        .get("reactions")
53        .and_then(|v| v.as_array())
54        .ok_or_else(|| ReadWriteError::Format("BIGG model missing reactions".into()))?;
55    for r in reactions {
56        let rid = r.get("id").and_then(|v| v.as_str()).unwrap_or("");
57        let l = r.get("lower_bound").and_then(|v| v.as_f64()).unwrap_or(0.0);
58        let u = r.get("upper_bound").and_then(|v| v.as_f64()).unwrap_or(0.0);
59        // XGI: `DH.add_edge(..., idx=r["id"], name=r["name"])` — every reaction
60        // edge (forward/reverse/reversible, incl. the `_reverse` twin) carries
61        // this same `name` attr (bigg_data.py:129,142,156,159).
62        let edge_attrs =
63            serde_json::json!({ "name": r.get("name").cloned().unwrap_or(Value::Null) });
64        let coeffs = match r.get("metabolites").and_then(|v| v.as_object()) {
65            Some(o) => o,
66            None => continue,
67        };
68
69        let split = |positive_is_product: bool| -> (Vec<String>, Vec<String>) {
70            let mut reactants = Vec::new();
71            let mut products = Vec::new();
72            for (met, val) in coeffs {
73                let v = val.as_f64().unwrap_or(0.0);
74                let is_product = if positive_is_product {
75                    v > 0.0
76                } else {
77                    v >= 0.0
78                };
79                if is_product {
80                    products.push(met.clone());
81                } else {
82                    reactants.push(met.clone());
83                }
84            }
85            (reactants, products)
86        };
87
88        // forward: l>=0 && u>0
89        if l >= 0.0 && u > 0.0 {
90            let (reactants, products) = split(true);
91            if !(reactants.is_empty() && products.is_empty()) {
92                let _ = dh.add_edge(
93                    reactants,
94                    products,
95                    Some(rid.to_string()),
96                    edge_attrs.clone(),
97                );
98            }
99        }
100        // reverse: l<0 && u<=0  (positive coeff -> reactant)
101        if l < 0.0 && u <= 0.0 {
102            let (products, reactants) = {
103                // positive_is_product=false flips roles per XGI's reverse branch
104                let mut reactants = Vec::new();
105                let mut products = Vec::new();
106                for (met, val) in coeffs {
107                    let v = val.as_f64().unwrap_or(0.0);
108                    if v >= 0.0 {
109                        reactants.push(met.clone());
110                    } else {
111                        products.push(met.clone());
112                    }
113                }
114                (products, reactants)
115            };
116            if !(reactants.is_empty() && products.is_empty()) {
117                let _ = dh.add_edge(
118                    reactants,
119                    products,
120                    Some(rid.to_string()),
121                    edge_attrs.clone(),
122                );
123            }
124        }
125        // reversible: l<0 && u>0 -> forward + <id>_reverse
126        // XGI's reversible branch classifies only val>0 -> product, val<0 ->
127        // reactant, DROPPING any metabolite with coefficient exactly 0 — unlike
128        // the forward/reverse branches (and `split`), it does not lump v==0 into
129        // reactants. Mirror that exactly here instead of reusing split(true).
130        if l < 0.0 && u > 0.0 {
131            let mut reactants = Vec::new();
132            let mut products = Vec::new();
133            for (met, val) in coeffs {
134                let v = val.as_f64().unwrap_or(0.0);
135                if v > 0.0 {
136                    products.push(met.clone());
137                } else if v < 0.0 {
138                    reactants.push(met.clone());
139                }
140                // v == 0.0: dropped, matching XGI's reversible branch.
141            }
142            if !(reactants.is_empty() && products.is_empty()) {
143                let _ = dh.add_edge(
144                    reactants.clone(),
145                    products.clone(),
146                    Some(rid.to_string()),
147                    edge_attrs.clone(),
148                );
149                let _ = dh.add_edge(
150                    products,
151                    reactants,
152                    Some(format!("{rid}_reverse")),
153                    edge_attrs.clone(),
154                );
155            }
156        }
157    }
158    Ok(dh)
159}
160
161/// Fetch a BIGG dataset over HTTP. Behind the `network` feature (OFF by default).
162#[cfg(feature = "network")]
163pub fn load_bigg_data(_dataset: &str) -> Result<DiHypergraph, ReadWriteError> {
164    Err(ReadWriteError::Format(
165        "load_bigg_data HTTP fetch not implemented in Phase 4".into(),
166    ))
167}