mzcore 0.2.0

Core logic for handling massspectrometry in Rust.
Documentation
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use std::{cmp::Ordering, collections::BTreeSet};

use context_error::*;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{
    chemistry::{DiagnosticIon, MolecularFormula, NeutralLoss},
    parse_json::{ParseJson, use_serde},
    sequence::PlacementRule,
    space::{Space, UsedSpace},
};

/// Indicate the cross-link side, it contains a set of all placement rules that apply for the placed
/// location to find all possible ways of breaking and/or neutral losses. These numbers are the
/// index into the [`LinkerSpecificity`] rules.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum CrossLinkSide {
    /// The cross-link is symmetric, or if asymmetric it can be placed in both orientations
    Symmetric(BTreeSet<usize>),
    /// The cross-link is asymmetric and this is the 'left' side
    Left(BTreeSet<usize>),
    /// The cross-link is asymmetric and this is the 'right' side
    Right(BTreeSet<usize>),
}

impl PartialOrd for CrossLinkSide {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for CrossLinkSide {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (Self::Symmetric(_), Self::Symmetric(_)) | (Self::Left(_), Self::Left(_)) => {
                Ordering::Equal
            }
            (Self::Symmetric(_), _) => Ordering::Greater,
            (_, Self::Symmetric(_)) => Ordering::Less,
            (Self::Left(_), _) => Ordering::Greater,
            (_, Self::Left(_)) => Ordering::Less,
            (Self::Right(_), Self::Right(_)) => Ordering::Equal,
        }
    }
}

impl std::hash::Hash for CrossLinkSide {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        let (i, r) = match self {
            Self::Symmetric(r) => (0, r),
            Self::Left(r) => (1, r),
            Self::Right(r) => (2, r),
        };
        state.write_u8(i);
        state.write(&r.iter().sorted().flat_map(|r| r.to_ne_bytes()).collect_vec());
    }
}

impl ParseJson for CrossLinkSide {
    fn from_json_value(value: Value) -> Result<Self, BoxedError<'static, BasicKind>> {
        use_serde(value)
    }
}

impl Space for CrossLinkSide {
    fn space(&self) -> UsedSpace {
        match self {
            Self::Symmetric(d) | Self::Left(d) | Self::Right(d) => d.space(),
        }
        .set_total::<Self>()
    }
}

/// The name of a cross-link
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum CrossLinkName {
    /// A branch
    Branch,
    /// A cross-link
    Name(Box<str>),
}

impl Space for CrossLinkName {
    fn space(&self) -> UsedSpace {
        match self {
            Self::Branch => UsedSpace::default(),
            Self::Name(n) => n.space(),
        }
        .set_total::<Self>()
    }
}

impl ParseJson for CrossLinkName {
    fn from_json_value(value: Value) -> Result<Self, BoxedError<'static, BasicKind>> {
        use_serde(value)
    }
}

/// The linker position specificities for a linker
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum LinkerSpecificity {
    /// A symmetric specificity where both ends have the same specificity.
    Symmetric {
        /// The placement rules for both ends.
        rules: Vec<PlacementRule>,
        /// All stubs that can be left after cleaving or breaking of the cross-link.
        stubs: Vec<(MolecularFormula, MolecularFormula)>,
        /// All possible neutral losses from the intact cross-linker.
        neutral_losses: Vec<NeutralLoss>,
        /// All diagnostic ions from the cross-linker
        diagnostic: Vec<DiagnosticIon>,
    },
    /// An asymmetric specificity where both ends have a different specificity.
    Asymmetric {
        /// The placement rules for both ends, these can be asymmetric thus are provided for
        /// 'right' and 'left' separately.
        rules: (Vec<PlacementRule>, Vec<PlacementRule>),
        /// All stubs that can be left after cleaving or breaking of the cross-link. The stubs are
        /// specific for right and left in the same orientation as the rules.
        stubs: Vec<(MolecularFormula, MolecularFormula)>,
        /// All possible neutral losses from the intact cross-linker.
        neutral_losses: Vec<NeutralLoss>,
        /// All diagnostic ions from the cross-linker
        diagnostic: Vec<DiagnosticIon>,
    },
}

impl Space for LinkerSpecificity {
    fn space(&self) -> UsedSpace {
        (UsedSpace::stack(1)
            + match self {
                Self::Symmetric {
                    rules,
                    stubs,
                    neutral_losses,
                    diagnostic,
                } => rules.space() + stubs.space() + neutral_losses.space() + diagnostic.space(),
                Self::Asymmetric {
                    rules,
                    stubs,
                    neutral_losses,
                    diagnostic,
                } => rules.space() + stubs.space() + neutral_losses.space() + diagnostic.space(),
            })
        .set_total::<Self>()
    }
}

impl ParseJson for LinkerSpecificity {
    fn from_json_value(value: Value) -> Result<Self, BoxedError<'static, BasicKind>> {
        if let Value::Object(map) = value {
            let (key, value) = map.into_iter().next().unwrap();
            match key.as_str() {
                "Symmetric" => {
                    if let Value::Object(mut map) = value {
                        Ok(Self::Symmetric {
                            rules: Vec::<PlacementRule>::from_json_value(
                                map.remove("rules").ok_or_else(|| {
                                    BoxedError::new(
                                        BasicKind::Error,
                                        "Invalid LinkerSpecificity",
                                        "The required property 'rules' is missing",
                                        Context::default().lines(
                                            0,
                                            map.iter()
                                                .map(|(k, v)| format!("\"{k}\": {v}"))
                                                .join(","),
                                        ),
                                    )
                                })?,
                            )?,
                            stubs: Vec::<(MolecularFormula, MolecularFormula)>::from_json_value(
                                map.remove("stubs").ok_or_else(|| {
                                    BoxedError::new(
                                        BasicKind::Error,
                                        "Invalid LinkerSpecificity",
                                        "The required property 'stubs' is missing",
                                        Context::default().lines(
                                            0,
                                            map.iter()
                                                .map(|(k, v)| format!("\"{k}\": {v}"))
                                                .join(","),
                                        ),
                                    )
                                })?,
                            )?,
                            neutral_losses: Vec::<NeutralLoss>::from_json_value(
                                map.remove("neutral_losses").ok_or_else(|| {
                                    BoxedError::new(
                                        BasicKind::Error,
                                        "Invalid LinkerSpecificity",
                                        "The required property 'neutral_losses' is missing",
                                        Context::default().lines(
                                            0,
                                            map.iter()
                                                .map(|(k, v)| format!("\"{k}\": {v}"))
                                                .join(","),
                                        ),
                                    )
                                })?,
                            )?,
                            diagnostic: Vec::<DiagnosticIon>::from_json_value(
                                map.remove("diagnostic").ok_or_else(|| {
                                    BoxedError::new(
                                        BasicKind::Error,
                                        "Invalid LinkerSpecificity",
                                        "The required property 'diagnostic' is missing",
                                        Context::default().lines(
                                            0,
                                            map.iter()
                                                .map(|(k, v)| format!("\"{k}\": {v}"))
                                                .join(","),
                                        ),
                                    )
                                })?,
                            )?,
                        })
                    } else if let Value::Array(mut arr) = value {
                        if arr.len() == 3 {
                            let diagnostic =
                                Vec::<DiagnosticIon>::from_json_value(arr.pop().unwrap())?;
                            let stubs =
                                Vec::<(MolecularFormula, MolecularFormula)>::from_json_value(
                                    arr.pop().unwrap(),
                                )?;
                            let rules = Vec::<PlacementRule>::from_json_value(arr.pop().unwrap())?;

                            Ok(Self::Symmetric {
                                rules,
                                stubs,
                                neutral_losses: Vec::new(),
                                diagnostic,
                            })
                        } else {
                            Err(BoxedError::new(
                                BasicKind::Error,
                                "Invalid NeutralLoss",
                                "The Symmetric is a sequence but does not have 3 children",
                                Context::default().lines(0, arr.iter().join(",")),
                            ))
                        }
                    } else {
                        Err(BoxedError::new(
                            BasicKind::Error,
                            "Invalid LinkerSpecificity",
                            "The Symmetric value has to be a map or a sequence",
                            Context::default().lines(0, value.to_string()),
                        ))
                    }
                }
                "Asymmetric" => {
                    if let Value::Object(mut map) = value {
                        Ok(Self::Asymmetric {
                            rules: <(Vec<PlacementRule>, Vec<PlacementRule>)>::from_json_value(
                                map.remove("rules").ok_or_else(|| {
                                    BoxedError::new(
                                        BasicKind::Error,
                                        "Invalid LinkerSpecificity",
                                        "The required property 'rules' is missing",
                                        Context::default().lines(
                                            0,
                                            map.iter()
                                                .map(|(k, v)| format!("\"{k}\": {v}"))
                                                .join(","),
                                        ),
                                    )
                                })?,
                            )?,
                            stubs: Vec::<(MolecularFormula, MolecularFormula)>::from_json_value(
                                map.remove("stubs").ok_or_else(|| {
                                    BoxedError::new(
                                        BasicKind::Error,
                                        "Invalid LinkerSpecificity",
                                        "The required property 'stubs' is missing",
                                        Context::default().lines(
                                            0,
                                            map.iter()
                                                .map(|(k, v)| format!("\"{k}\": {v}"))
                                                .join(","),
                                        ),
                                    )
                                })?,
                            )?,
                            neutral_losses: Vec::<NeutralLoss>::from_json_value(
                                map.remove("neutral_losses").ok_or_else(|| {
                                    BoxedError::new(
                                        BasicKind::Error,
                                        "Invalid LinkerSpecificity",
                                        "The required property 'neutral_losses' is missing",
                                        Context::default().lines(
                                            0,
                                            map.iter()
                                                .map(|(k, v)| format!("\"{k}\": {v}"))
                                                .join(","),
                                        ),
                                    )
                                })?,
                            )?,
                            diagnostic: Vec::<DiagnosticIon>::from_json_value(
                                map.remove("diagnostic").ok_or_else(|| {
                                    BoxedError::new(
                                        BasicKind::Error,
                                        "Invalid LinkerSpecificity",
                                        "The required property 'diagnostic' is missing",
                                        Context::default().lines(
                                            0,
                                            map.iter()
                                                .map(|(k, v)| format!("\"{k}\": {v}"))
                                                .join(","),
                                        ),
                                    )
                                })?,
                            )?,
                        })
                    } else if let Value::Array(mut arr) = value {
                        if arr.len() == 3 {
                            let diagnostic =
                                Vec::<DiagnosticIon>::from_json_value(arr.pop().unwrap())?;
                            let stubs =
                                Vec::<(MolecularFormula, MolecularFormula)>::from_json_value(
                                    arr.pop().unwrap(),
                                )?;
                            let rules =
                                <(Vec<PlacementRule>, Vec<PlacementRule>)>::from_json_value(
                                    arr.pop().unwrap(),
                                )?;

                            Ok(Self::Asymmetric {
                                rules,
                                stubs,
                                neutral_losses: Vec::new(),
                                diagnostic,
                            })
                        } else {
                            Err(BoxedError::new(
                                BasicKind::Error,
                                "Invalid NeutralLoss",
                                "The Asymmetric is a sequence but does not have 3 children",
                                Context::default().lines(0, arr.iter().join(",")),
                            ))
                        }
                    } else {
                        Err(BoxedError::new(
                            BasicKind::Error,
                            "Invalid LinkerSpecificity",
                            "The Asymmetric value has to be a map or a sequence",
                            Context::default().lines(0, value.to_string()),
                        ))
                    }
                }
                _ => Err(BoxedError::new(
                    BasicKind::Error,
                    "Invalid LinkerSpecificity",
                    "The tag has to be Symmetric/Asymmetric",
                    Context::default().lines(0, key),
                )),
            }
        } else {
            Err(BoxedError::new(
                BasicKind::Error,
                "Invalid LinkerSpecificity",
                "The JSON value has to be a map",
                Context::default().lines(0, value.to_string()),
            ))
        }
    }
}

#[cfg(test)]
#[allow(clippy::missing_panics_doc)]
mod tests {
    use crate::{
        chemistry::{DiagnosticIon, NeutralLoss},
        molecular_formula,
        parse_json::ParseJson,
        sequence::{AminoAcid, LinkerSpecificity, PlacementRule, Position},
    };

    #[test]
    fn deserialise_json() {
        let old = r#"{"Asymmetric":[[[{"AminoAcid":[["Selenocysteine"],"AnyCTerm"]},{"AminoAcid":[["GlutamicAcid"],"Anywhere"]}],[{"AminoAcid":[["Selenocysteine"],"AnyNTerm"]}]],[[{"elements":[["U",null,1]],"additional_mass":0.0},{"elements":[["U",null,1]],"additional_mass":0.0}]],[{"elements":[["Te",null,1]],"additional_mass":0.0},{"elements":[["Ne",null,1]],"additional_mass":0.0},{"elements":[["H",null,2],["He",null,3]],"additional_mass":0.0},{"elements":[["H",null,1],["He",null,2]],"additional_mass":0.0},{"elements":[["I",null,1],["Er",null,1]],"additional_mass":0.0},{"elements":[["H",null,12],["C",null,12],["O",null,1]],"additional_mass":0.0}]]}"#;
        let current = LinkerSpecificity::Symmetric {
            rules: vec![
                PlacementRule::Position(Position::AnyNTerm),
                PlacementRule::AminoAcid(
                    vec![AminoAcid::Alanine, AminoAcid::Leucine].into(),
                    Position::Anywhere,
                ),
            ],
            stubs: vec![(molecular_formula!(H 2 O 1), molecular_formula!(H 2 O 1))],
            neutral_losses: vec![NeutralLoss::Gain(2, molecular_formula!(H 2 O 1))],
            diagnostic: vec![DiagnosticIon(molecular_formula!(H 2 O 1))],
        };
        let current_text =
            serde_json::to_string(&current).expect("Could not serialise linker specificity");

        let _old = LinkerSpecificity::from_json(old).expect("Could not deserialise old json");
        let current_back = LinkerSpecificity::from_json(&current_text)
            .expect("Could not deserialise current json");

        assert_eq!(current, current_back);
    }
}