-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmodel.rs
292 lines (280 loc) · 9.38 KB
/
model.rs
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
292
#[cfg(feature = "default")]
use pyo3::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use super::annotation::Annotation;
use super::base_types::{Compartment, Constraint, InitialAssignment, Parameter, Reaction, Species};
use super::list_of::*;
use super::{Unit, UnitSIdRef};
/// SBML model as defined in the [SBML Level 3 Version 2 core](http://sbml.org/Documents/Specifications).
///
/// Extended with [fbc plugin](http://sbml.org/Documents/Specifications/SBML_Level_3/Packages/fbc)
///
/// # Example
///
/// ```
/// use rust_sbml::ModelRaw;
/// use std::fs;
///
/// let ecoli = fs::read_to_string("examples/EcoliCore.xml").unwrap();
/// let raw_model = ModelRaw::parse(&ecoli).unwrap();
/// assert_eq!(
/// raw_model.list_of_unit_definitions.unit_definitions[0].id.to_owned().unwrap(),
/// "mmol_per_gDW_per_hr"
/// )
/// ```
#[derive(Deserialize, Serialize, Debug, Default, PartialEq, Clone)]
#[serde(rename = "model", rename_all = "camelCase")]
pub struct ModelRaw {
pub id: Option<String>,
pub metaid: Option<String>,
pub name: Option<String>,
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>,
#[serde(default)]
pub list_of_unit_definitions: ListOfUnitDefinitions,
#[serde(default)]
pub list_of_compartments: ListOfCompartments,
#[serde(default)]
pub list_of_species: ListOfSpecies,
#[serde(default)]
pub list_of_parameters: ListOfParameters,
#[serde(default)]
pub list_of_initial_assignments: ListOfInitialAssignments,
#[serde(default)]
pub list_of_reactions: ListOfReactions,
#[serde(default)]
pub list_of_constraints: ListOfConstraints,
#[serde(default)]
pub list_of_objectives: Option<ListOfObjectives>,
pub list_of_rules: Option<ListOfRules>,
pub list_of_function_definitions: Option<ListOfFunctionDefinitions>,
pub annotation: Option<Annotation>,
}
impl ModelRaw {
pub fn parse(doc: &str) -> Result<Self, quick_xml::DeError> {
let raw_model: Sbml = quick_xml::de::from_str(doc)?;
Ok(raw_model.model)
}
pub fn to_string(&self) -> Result<String, quick_xml::DeError> {
quick_xml::se::to_string(&Sbml {
model: (*self).clone(),
})
}
}
#[derive(Deserialize, Serialize, Debug, Default, PartialEq)]
struct Sbml {
model: ModelRaw,
}
/// Bucket struct to hold all units defined on the top level of
/// [`ModelRaw`].
#[derive(Debug, Default, PartialEq, Eq)]
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<&ModelRaw> for ModelUnits {
fn from(raw_model: &ModelRaw) -> Self {
Self {
substance_units: raw_model.substance_units.clone(),
time_units: raw_model.time_units.clone(),
extent_units: raw_model.extent_units.clone(),
volume_units: raw_model.volume_units.clone(),
area_units: raw_model.area_units.clone(),
length_units: raw_model.length_units.clone(),
conversion_factor: raw_model.conversion_factor.clone(),
}
}
}
type Hl<T> = HashMap<String, T>;
/// Abstraction over the SBML specification. It traverses each top-level
/// listOF_ and provides `HashMaps<id, object>` instead. In addition the model
/// units are gathered in an [`ModelUnits`] struct.
///
/// # Example
///
/// ```
/// use rust_sbml::Model;
/// use std::fs;
///
/// let ecoli = fs::read_to_string("examples/EcoliCore.xml").unwrap();
/// let document = Model::parse(&ecoli).unwrap();
/// println!("{:?}", document.objectives);
/// assert_eq!(
/// document
/// .objectives
/// .unwrap()
/// .iter()
/// .map(|reac_id| reac_id.to_owned())
/// .next(),
/// Some("R_BIOMASS_Ecoli_core_w_GAM".to_string())
/// );
/// ```
#[cfg_attr(feature = "default", pyclass)]
#[derive(Debug, Default, PartialEq)]
pub struct Model {
pub id: Option<String>,
pub metaid: Option<String>,
pub name: Option<String>,
pub model_units: ModelUnits,
pub initial_assignments: Hl<InitialAssignment>,
pub parameters: Hl<Parameter>,
pub species: Hl<Species>,
pub reactions: Hl<Reaction>,
pub compartments: Hl<Compartment>,
pub unit_definitions: Hl<HashMap<UnitSIdRef, Unit>>,
pub constraints: Vec<Constraint>,
pub objectives: Option<Vec<String>>,
pub annotation: Option<Annotation>,
}
impl Model {
/// Emulating the API of libSBML
///
/// # Example
///
/// ```
/// use rust_sbml::Model;
/// use std::fs;
///
/// let ecoli = fs::read_to_string("examples/EcoliCore.xml").unwrap();
/// let document = Model::parse(&ecoli).unwrap();
/// println!("{:?}", document.get_list_of_compartments())
/// ```
pub fn get_list_of_compartments(&self) -> Vec<&Compartment> {
self.compartments.values().collect()
}
/// Emulating the API of libSBML
///
/// # Example
///
/// ```
/// use rust_sbml::Model;
/// use std::fs;
///
/// let ecoli = fs::read_to_string("examples/EcoliCore.xml").unwrap();
/// let document = Model::parse(&ecoli).unwrap();
/// println!("{:?}", document.get_list_of_species())
/// ```
pub fn get_list_of_species(&self) -> Vec<&Species> {
self.species.values().collect()
}
/// Emulating the API of libSBML
///
/// # Example
///
/// ```
/// use rust_sbml::Model;
/// use std::fs;
///
/// let ecoli = fs::read_to_string("examples/EcoliCore.xml").unwrap();
/// let document = Model::parse(&ecoli).unwrap();
/// println!("{:?}", document.get_list_of_reactions())
/// ```
pub fn get_list_of_reactions(&self) -> Vec<&Reaction> {
self.reactions.values().collect()
}
/// Use [`ModelRaw`] to parse the SBML document
/// and then format it into `Model`.
pub fn parse(doc: &str) -> Result<Self, Box<dyn std::error::Error>> {
let raw_model = ModelRaw::parse(doc)?;
// Units used by the model itself
let model_units: ModelUnits = ModelUnits::from(&raw_model);
// Unit definitions
let unit_definitions: HashMap<String, HashMap<UnitSIdRef, Unit>> = raw_model
.list_of_unit_definitions
.unit_definitions
.iter()
.map(|unit_def| {
(
(*unit_def).to_owned().id.unwrap(),
unit_def
.list_of_units
.units
.iter()
.map(|unit| (unit.kind.to_owned(), unit.to_owned()))
.collect(),
)
})
.collect();
// Compartments
let compartments: HashMap<String, Compartment> = raw_model
.list_of_compartments
.compartments
.iter()
.map(|n| (n.id.to_owned(), n.to_owned()))
.collect();
// Species
let species: HashMap<String, Species> = raw_model
.list_of_species
.species
.iter()
.map(|n| (n.id.to_owned(), n.to_owned()))
.collect();
// Parameters
let parameters: HashMap<String, Parameter> = raw_model
.list_of_parameters
.parameters
.iter()
.map(|n| (n.id.to_owned(), n.to_owned()))
.collect();
// Initial assignments
let initial_assignments: HashMap<String, InitialAssignment> = raw_model
.list_of_initial_assignments
.initial_assignments
.iter()
.map(|n| (n.id.to_owned().unwrap(), (*n).to_owned()))
.collect();
// Reactions
let reactions: HashMap<String, Reaction> = raw_model
.list_of_reactions
.reactions
.iter()
.map(|n| (n.id.to_owned(), n.to_owned()))
.collect();
// Constraints
let constraints: Vec<Constraint> = raw_model.list_of_constraints.constraints;
let objectives: Option<Vec<String>> = match raw_model.list_of_objectives {
Some(objs) => Some(
objs.objectives
.iter()
.flat_map(|n| {
n.list_of_flux_objectives
.flux_objectives
.iter()
.map(|fr| fr.reaction.to_owned().unwrap())
})
.collect(),
),
None => None,
};
Ok(Model {
id: raw_model.id,
metaid: raw_model.metaid,
name: raw_model.name,
model_units,
parameters,
initial_assignments,
species,
reactions,
compartments,
unit_definitions,
constraints,
objectives,
annotation: raw_model.annotation,
})
}
}
/// Shortcut to [`Model::parse`](Model::parse).
pub fn parse_document(doc: &str) -> Result<Model, Box<dyn std::error::Error>> {
Model::parse(doc)
}