1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
use mathml::MathNode;
use roxmltree::Attribute;
use roxmltree::Node;
use serde_derive::Deserialize;
use std::collections::HashMap;

fn unwrap_optional_str(value: Node<'_, '_>, attribute: &'_ str) -> Option<String> {
    match value.attribute(attribute) {
        Some(s) => Some(s.to_owned()),
        _ => None,
    }
}

#[derive(Debug, Deserialize, PartialEq)]
pub enum UnitSidRef {
    SIUnit(UnitSId),
    CustomUnit(String),
}
impl<T: AsRef<str> + ToString> From<&T> for UnitSidRef {
    fn from(r: &T) -> Self {
        match serde_plain::from_str(r.as_ref()) {
            Ok(r) => Self::SIUnit(r),
            Err(_) => Self::CustomUnit(r.to_string()),
        }
    }
}
#[derive(Debug, Hash, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum UnitSId {
    Ampere,
    Avogadro,
    Coulomb,
    Gray,
    Joule,
    Litre,
    Mole,
    Radian,
    Steradian,
    Weber,
    Dimensionless,
    Henry,
    Katal,
    Lumen,
    Newton,
    Tesla,
    Becquerel,
    Farad,
    Hertz,
    Kelvin,
    Lux,
    Ohm,
    Siemens,
    Volt,
    Candela,
    Gram,
    Item,
    Kilogram,
    Metre,
    Pascal,
    Sievert,
    Watt,
    Second,
}
#[derive(Debug, Default, PartialEq)]

pub struct ModelUnits {
    pub substance_units: Option<UnitSidRef>,
    pub time_units: Option<UnitSidRef>,
    pub extent_units: Option<UnitSidRef>,
    pub volume_units: Option<UnitSidRef>,
    pub area_units: Option<UnitSidRef>,
    pub length_units: Option<UnitSidRef>,
    pub conversion_factor: Option<UnitSidRef>,
}

impl From<&[Attribute<'_>]> for ModelUnits {
    fn from(value: &[Attribute<'_>]) -> Self {
        let hmap: HashMap<String, String> = value
            .iter()
            .map(|a| (a.name().to_owned(), a.value().to_owned()))
            .collect();
        ModelUnits {
            substance_units: hmap.get("substanceUnits").map(|p| p.into()),
            time_units: hmap.get("timeUnits").map(|p| p.into()),
            extent_units: hmap.get("extentUnits").map(|p| p.into()),
            volume_units: hmap.get("volumeUnits").map(|p| p.into()),
            area_units: hmap.get("areaUnits").map(|p| p.into()),
            length_units: hmap.get("lengthUnits").map(|p| p.into()),
            conversion_factor: hmap.get("conversionFactor").map(|p| p.into()),
        }
    }
}
#[derive(Debug, PartialEq)]
pub struct Unit {
    exponent: f64,
    scale: i64,
    multiplier: f64,
}
impl From<Node<'_, '_>> for Unit {
    fn from(value: Node<'_, '_>) -> Self {
        Unit {
            exponent: value.attribute("exponent").unwrap().parse().unwrap(),
            scale: value.attribute("scale").unwrap().parse().unwrap(),
            multiplier: value.attribute("multiplier").unwrap().parse().unwrap(),
        }
    }
}
#[derive(Debug, PartialEq)]
pub struct Compartment {
    units: Option<UnitSidRef>,
    pub id: String,
    pub name: Option<String>,
    spatial_dimensions: Option<f64>,
    size: Option<f64>,
    constant: bool,
}
impl From<Node<'_, '_>> for Compartment {
    fn from(value: Node<'_, '_>) -> Self {
        Compartment {
            spatial_dimensions: value
                .attribute("spatialDimensions")
                .map(|p| p.parse().unwrap()),
            id: value.attribute("id").unwrap().to_owned(),
            name: unwrap_optional_str(value, "name"),
            size: value.attribute("size").map(|p| p.parse().unwrap()),
            constant: value.attribute("constant").unwrap().parse().unwrap(),
            units: value.attribute("units").map(|p| UnitSidRef::from(&p)),
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct Specie {
    pub compartment: String,
    initial_concentration: Option<f64>,
    initial_amount: Option<f64>,
    pub id: String,
    substance_units: Option<UnitSidRef>,
    has_only_substance_units: bool,
    pub boundary_condition: bool,
    pub constant: bool,
    conversion_factor: Option<String>,
}
impl<'a> From<Node<'a, 'a>> for Specie {
    fn from(value: Node<'a, 'a>) -> Self {
        Specie {
            compartment: value.attribute("compartment").unwrap().to_owned(),
            id: value.attribute("id").unwrap().to_owned(),
            initial_concentration: value
                .attribute("initialConcentration")
                .map(|p| p.parse().unwrap()),
            initial_amount: value.attribute("initialAmount").map(|p| p.parse().unwrap()),
            substance_units: value
                .attribute("substanceUnits")
                .map(|p| UnitSidRef::from(&p)),
            has_only_substance_units: value
                .attribute("hasOnlySubstanceUnits")
                .unwrap()
                .parse()
                .unwrap(),
            boundary_condition: value
                .attribute("boundaryCondition")
                .unwrap()
                .parse()
                .unwrap(),
            constant: value.attribute("constant").unwrap().parse().unwrap(),
            conversion_factor: value.attribute("conversionFactor").map(|r| r.to_owned()),
        }
    }
}
#[derive(Debug, PartialEq)]
pub struct SpeciesReference {
    pub species: String,
    pub constant: bool,
    pub sbo_term: Option<String>,
    pub id: Option<String>,
    pub name: Option<String>,
    pub stoichiometry: Option<f64>,
}
impl<'a> From<Node<'a, 'a>> for SpeciesReference {
    fn from(value: Node<'a, 'a>) -> Self {
        SpeciesReference {
            species: value.attribute("species").unwrap().to_string(),
            constant: value.attribute("constant").unwrap().parse().unwrap(),
            sbo_term: unwrap_optional_str(value, "sboTerm"),
            id: unwrap_optional_str(value, "id"),
            name: unwrap_optional_str(value, "name"),
            stoichiometry: match value.attribute("stoichiometry") {
                Some(s) => Some(s.parse().unwrap()),
                None => None,
            },
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct Parameter {
    value: Option<f64>,
    units: Option<UnitSidRef>,
    constant: bool,
}
impl<'a> From<Node<'a, 'a>> for Parameter {
    fn from(value: Node<'a, 'a>) -> Self {
        Parameter {
            value: value.attribute("value").map(|p| p.parse().unwrap()),
            units: value.attribute("units").map(|p| UnitSidRef::from(&p)),
            constant: value.attribute("constant").unwrap().parse().unwrap(),
        }
    }
}
#[derive(Debug, PartialEq)]
pub struct InitialAssignment {
    pub symbol: String,
}
#[derive(Debug, PartialEq)]
pub struct ListOfSpecies(pub Vec<SpeciesReference>);
impl<'a> From<Node<'a, 'a>> for ListOfSpecies {
    fn from(value: Node<'a, 'a>) -> Self {
        ListOfSpecies(
            value
                .document()
                .descendants()
                .filter(|n| n.tag_name().name() == "speciesReference")
                .map(SpeciesReference::from)
                .collect(),
        )
    }
}

/// Reaction object as defined by SBML
/// TODO: implement KineticLaw
///
/// # Example
///
/// ```
/// use roxmltree;
/// use rust_sbml::Reaction;
///
/// let reactions: Vec<Reaction> = roxmltree::Document::parse(
///     "<model id='example'><listOfReactions>
///         <reaction id='J1' reversible='false'>
///             <listOfReactants>
///                 <speciesReference species='X0' stoichiometry='2' constant='true'/>
///     </listOfReactants></reaction></listOfReactions></model>",
/// )
/// .unwrap()
/// .descendants()
/// .filter(|n| n.tag_name().name() == "reaction")
/// .map(|n| Reaction::from(n))
/// .collect();
/// assert!(
///     reactions.iter().any(|reaction| reaction
///         .list_of_species
///         .0
///         .iter()
///         .any(|specref| specref.species == "X0"))
/// );
/// ```
#[derive(Debug, PartialEq)]
pub struct Reaction {
    pub list_of_species: ListOfSpecies,
    pub reversible: bool,
    pub compartment: Option<String>,
    pub sbo_term: Option<String>,
}
impl<'a> From<Node<'a, 'a>> for Reaction {
    fn from(value: Node<'a, 'a>) -> Self {
        Reaction {
            list_of_species: ListOfSpecies::from(value),
            reversible: value.attribute("reversible").unwrap().parse().unwrap(),
            compartment: unwrap_optional_str(value, "compartment"),
            sbo_term: unwrap_optional_str(value, "sboTerm"),
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct Function {
    math: MathNode,
}
// #[derive(Debug, PartialEq)]
// pub enum Rule<'a> {
//     AlgebraicRule { math: MathNode },
//     AssignmentRule { math: MathNode, variable: &'a str },
//     RateRule { math: MathNode, variable: &'a str },
// }
#[derive(Debug, PartialEq)]
pub struct Constraint {
    pub math: Option<MathNode>,
    pub message: String,
}