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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! Code to handle the PSI-MOD ontology
use std::{borrow::Cow, str::FromStr};

use context_error::{
    BoxedError, Context, CreateError, FullErrorContent, StaticErrorContent, combine_error,
};
use itertools::Itertools;
use mzcv::{
    AccessionCode, CVData, CVError, CVFile, CVSource, CVVersion, HashBufReader, OboIdentifier,
    OboOntology, OboStanzaType, SynonymScope,
};
use thin_vec::ThinVec;

use crate::{
    chemistry::MolecularFormula,
    helper_functions::{UnwrapInfallible, explain_number_error},
    ontology::{
        Ontology,
        ontology_modification::{ModData, OntologyModification},
    },
    sequence::{
        LinkerSpecificity, ModificationId, PlacementRule, Position, SimpleModification,
        SimpleModificationInner,
    },
};

/// PSI-MOD modifications
#[allow(missing_copy_implementations, missing_debug_implementations)]
pub struct PsiMod {}

impl CVData for SimpleModificationInner {
    type Index = AccessionCode;

    fn index(&self) -> Option<AccessionCode> {
        self.description().map(ModificationId::id)
    }

    fn curie(&self) -> Option<mzcv::Curie> {
        self.description().map(|d| mzcv::Curie {
            cv: d.ontology.cv(),
            accession: d.id(),
        })
    }

    fn name(&self) -> Option<Cow<'_, str>> {
        self.description().map(|d| Cow::Borrowed(d.name.as_ref()))
    }

    fn synonyms(&self) -> impl Iterator<Item = &str> {
        self.description().into_iter().flat_map(|d| {
            d.synonyms
                .iter()
                .filter(|(s, _)| *s == SynonymScope::Exact)
                .map(|(_, s)| s.as_ref())
        })
    }

    fn parents(&self) -> impl Iterator<Item = &Self::Index> {
        self.description().into_iter().flat_map(|id| id.parents.iter())
    }

    fn children(&self) -> impl Iterator<Item = &Self::Index> {
        self.description().into_iter().flat_map(|id| id.children.iter())
    }
}

impl CVSource for PsiMod {
    type Data = SimpleModificationInner;
    type Structure = Vec<SimpleModification>;

    fn cv_label() -> &'static str {
        "MOD"
    }

    fn cv_name() -> &'static str {
        "PSI-MOD"
    }

    fn files() -> &'static [CVFile] {
        &[CVFile {
            name: "PSI-MOD",
            extension: "obo",
            url: Some(
                "https://raw.githubusercontent.com/HUPO-PSI/psi-mod-CV/refs/heads/master/PSI-MOD.obo",
            ),
            compression: mzcv::CVCompression::None,
        }]
    }

    fn static_data() -> Option<(CVVersion, Self::Structure)> {
        #[cfg(not(feature = "internal-no-data"))]
        {
            use bincode::config::Configuration;
            let cache = bincode::decode_from_slice::<(CVVersion, Self::Structure), Configuration>(
                include_bytes!("../databases/psimod.dat"),
                Configuration::default(),
            )
            .unwrap()
            .0;
            Some(cache)
        }
        #[cfg(feature = "internal-no-data")]
        None
    }

    fn parse(
        mut reader: impl Iterator<Item = HashBufReader<Box<dyn std::io::Read>, impl sha2::Digest>>,
    ) -> Result<
        (
            CVVersion,
            Self::Structure,
            Vec<BoxedError<'static, CVError>>,
        ),
        Vec<BoxedError<'static, CVError>>,
    > {
        let reader = reader.next().ok_or_else(|| {
            vec![BoxedError::new(
                CVError::MissingReader,
                "Missing reader",
                "One file reader should be given for parsing PSI-MOD files",
                Context::default(),
            )]
        })?;
        let obo = OboOntology::from_raw(reader).map_err(|e| {
            vec![
                BoxedError::small(
                    CVError::FileCouldNotBeParsed,
                    e.get_short_description(),
                    e.get_long_description(),
                )
                .add_contexts(e.get_contexts().iter().cloned()),
            ]
        })?;
        let mut mods: Vec<OntologyModification> = Vec::new();
        let mut errors = Vec::new();

        'stanza: for obj in &obo.objects {
            if obj.stanza_type != OboStanzaType::Term
                || obj.id == (Some("MOD".into()), "00000".into())
                || obj.id == (Some("MOD".into()), "00004".into())
                || obj.id == (Some("MOD".into()), "00008".into())
            {
                continue;
            }
            let Ok(id) = obj.id.1.parse() else {
                combine_error(
                    &mut errors,
                    BoxedError::new(
                        CVError::ItemError,
                        "Invalid ID",
                        "A PSI-MOD ID should be numerical",
                        Context::default().lines(0, obj.id.1.to_string()),
                    ),
                );
                continue;
            };
            let mut modification = OntologyModification {
                id,
                name: obj.lines["name"][0].0.clone(),
                ontology: Ontology::Psimod,
                obsolete: obj.obsolete,
                ..OntologyModification::default()
            };
            modification.add_relationships(&obj.relationship);
            if let Some((description, cross_ids, ..)) = &obj.definition {
                modification.description = description.clone();
                match cross_ids
                    .iter()
                    .map(|v| v.clone().try_into())
                    .collect::<Result<ThinVec<_>, _>>()
                {
                    Ok(ids) => modification.cross_ids.extend_from_slice(&ids),
                    Err(err) => combine_error(&mut errors, err.convert(|_| CVError::ItemError)),
                }
            }
            for synonym in &obj.synonyms {
                modification.synonyms.push((synonym.scope, synonym.synonym.clone()));
            }

            let mut origins = Vec::new();
            let mut term = None;
            let mut charge = None;
            for (id, _values, _comment) in &obj.xref {
                match (id.0.as_deref(), &id.1) {
                    (Some("DiffFormula"), s) if s.as_ref() != "\"none\"" => {
                        match MolecularFormula::psi_mod(s.trim_matches('\"')) {
                            Ok(formula) => modification.formula = formula,
                            Err(err) => combine_error(
                                &mut errors,
                                BoxedError::new(
                                    CVError::ItemError,
                                    "Invalid formula",
                                    "The formula was invalid",
                                    Context::default().lines(0, obj.id.to_string()),
                                )
                                .add_underlying_error(
                                    err.to_owned()
                                        .convert::<CVError, BoxedError<'static, CVError>>(|_| {
                                            CVError::ItemError
                                        }),
                                ),
                            ),
                        }
                    }
                    (Some("FormalCharge"), s) if s.as_ref() != "\"none\"" => {
                        let v = s.trim_matches('\"');
                        if v.len() >= 2 {
                            let num = match v[..v.len() - 1].parse::<u8>() {
                                Ok(v) => v,
                                Err(err) => {
                                    combine_error(
                                        &mut errors,
                                        BoxedError::new(
                                            CVError::ItemError,
                                            "Invalid formal charge",
                                            format!("The charge is {}", explain_number_error(&err)),
                                            Context::default().lines(0, obj.id.to_string()),
                                        ),
                                    );
                                    continue;
                                }
                            };
                            let num = match &v[v.len() - 1..] {
                                "+" => num as isize,
                                "-" => -(num as isize),
                                _ => {
                                    combine_error(
                                        &mut errors,
                                        BoxedError::new(
                                            CVError::ItemError,
                                            "Invalid formal charge",
                                            "The sign needs to be at the end of the charge and can only be '+' or '-'",
                                            Context::default().lines(0, obj.id.to_string()),
                                        ),
                                    );
                                    continue;
                                }
                            };
                            charge = Some(num);
                        } else {
                            combine_error(
                                &mut errors,
                                BoxedError::new(
                                    CVError::ItemError,
                                    "Invalid formal charge",
                                    "A formal charge should contain the charge itself followed by the sign",
                                    Context::default().lines(0, obj.id.to_string()),
                                ),
                            );
                        }
                    }
                    (Some("Origin"), value) => {
                        let commas = value.chars().filter(|c| *c == ',').count();
                        let cross_link_numbers = obj.lines.get("comment").map_or(Vec::new(), |v| {
                            v[0].0
                                .split(';')
                                .flat_map(|s| s.split('.'))
                                .filter_map(|tag| {
                                    tag.trim().to_ascii_lowercase().strip_prefix("cross-link").map(
                                        |v| {
                                            v.trim()
                                                .trim_end_matches('.')
                                                .parse::<usize>()
                                                .map_err(|e| {
                                                    format!("Could not parse '{tag}': {e}")
                                                })
                                                .unwrap()
                                        },
                                    )
                                })
                                .collect()
                        });
                        if cross_link_numbers.len() > 1 {
                            combine_error(
                                &mut errors,
                                BoxedError::new(
                                    CVError::ItemError,
                                    "Multiple cross-link numbers",
                                    format!(
                                        "This modification was defined to be a cross-linker with the following number of sites: {}",
                                        cross_link_numbers.iter().join(", ")
                                    ),
                                    Context::default().lines(0, obj.id.to_string()),
                                ),
                            );
                            continue 'stanza;
                        }

                        if let Some(amount) = cross_link_numbers.first() {
                            if commas + 1 != *amount {
                                combine_error(
                                    &mut errors,
                                    BoxedError::new(
                                        CVError::ItemError,
                                        "Different cross-link numbers",
                                        format!(
                                            "This modification was defined be a cross-linker with {amount} sites, but has {} orgins",
                                            commas + 1
                                        ),
                                        Context::default().lines(0, obj.id.to_string()),
                                    ),
                                );
                                continue 'stanza;
                            }
                        } else if value.contains(',') {
                            combine_error(
                                &mut errors,
                                BoxedError::new(
                                    CVError::ItemError,
                                    "Missing cross-link number",
                                    format!(
                                        "This modification has {} orgins, but is not defined to be a cross-linker in the comment",
                                        commas + 1
                                    ),
                                    Context::default().lines(0, obj.id.to_string()),
                                ),
                            );
                            continue 'stanza;
                        }
                        if value.as_ref() != "\"none\"" {
                            origins = value
                                .trim_start_matches('\"')
                                .trim_end_matches('\"')
                                .split(',')
                                .map(|s| s.trim().to_string())
                                .collect();
                        }
                    }
                    (Some("TermSpec"), value) => {
                        let v = value.trim_start_matches('\"').trim_end_matches('\"');
                        if v == "N-term" {
                            term = Some(Position::AnyNTerm);
                        } else if v == "C-term" {
                            term = Some(Position::AnyCTerm);
                        } else if v == "none" {
                            term = Some(Position::Anywhere);
                        } else {
                            combine_error(
                                &mut errors,
                                BoxedError::new(
                                    CVError::ItemError,
                                    "Invalid TermSpec",
                                    "The termSpec should be 'N-term', 'C-term', or 'none'",
                                    Context::default().lines(0, format!("{}: '{v}'", obj.id)),
                                ),
                            );
                            continue 'stanza;
                        }
                    }
                    _ => (), // ignore
                }
            }

            if let Some(charge) = charge {
                modification.formula.set_charge(crate::system::isize::Charge::new::<
                    crate::system::e,
                >(charge));
            }

            if origins.len() <= 1 {
                let mut rules = Vec::new();
                if let Some(origin) = origins.first() {
                    match parse_rule(origin, term) {
                        Ok(rule) => rules.push((vec![rule], Vec::new(), Vec::new())),
                        Err(err) => {
                            combine_error(&mut errors, err);
                            continue;
                        }
                    }
                } else if let Some(term) = term {
                    rules.push((vec![PlacementRule::Position(term)], Vec::new(), Vec::new()));
                }
                modification.data = ModData::Mod {
                    specificities: rules,
                };
            } else if origins.len() == 2 {
                let left = match parse_rule(&origins[0], term) {
                    Ok(rule) => rule,
                    Err(err) => {
                        combine_error(&mut errors, err);
                        continue;
                    }
                };
                let right = match parse_rule(&origins[1], term) {
                    Ok(rule) => rule,
                    Err(err) => {
                        combine_error(&mut errors, err);
                        continue;
                    }
                };
                modification.data = ModData::Linker {
                    length: crate::sequence::LinkerLength::Unknown,
                    specificities: vec![LinkerSpecificity::Asymmetric {
                        rules: (vec![left], vec![right]),
                        stubs: Vec::new(),
                        neutral_losses: Vec::new(),
                        diagnostic: Vec::new(),
                    }],
                };
            } else {
                combine_error(
                    &mut errors,
                    BoxedError::new(
                        CVError::ItemWarning,
                        "Higher order cross-linker",
                        format!(
                            "This cross-linker links {} sites, but only cross-linkers with two sites are supported for now, this modification will be ignored",
                            origins.len()
                        ),
                        Context::default().lines(0, obj.id.to_string()),
                    ),
                );
            }
            mods.push(modification);
        }

        Ok((obo.version(), OntologyModification::finish(mods), errors))
    }
}

/// Parse a Origin rule, either a single amino acid, or a PSI-MOD ID
/// # Errors
/// If this is not a valid rule
fn parse_rule(
    rule: &str,
    term: Option<Position>,
) -> Result<PlacementRule, BoxedError<'static, CVError>> {
    if rule.len() == 1 {
        if rule == "X" {
            Ok(term.map_or_else(
                || PlacementRule::Position(Position::Anywhere),
                PlacementRule::Position,
            ))
        } else if let Ok(aa) = rule.try_into() {
            Ok(PlacementRule::AminoAcid(
                vec![aa].into(),
                term.unwrap_or(Position::Anywhere),
            ))
        } else {
            Err(BoxedError::new(
                CVError::ItemError,
                "Invalid amino acid",
                "A single letter origin is assumed to be an amino acid but this is not",
                Context::default().lines(0, rule.to_string()),
            ))
        }
    } else {
        let id = OboIdentifier::from_str(rule).unwrap_infallible();

        if id.0.is_none_or(|ns| ns.as_ref() != "MOD") {
            Err(BoxedError::new(
                CVError::ItemError,
                "Invalid ID",
                "A modification as an origin should come from within PSI-MOD",
                Context::default().lines(0, rule.to_string()),
            ))
        } else if let Ok(id) = id.1.parse() {
            Ok(PlacementRule::PsiModification(
                id,
                term.unwrap_or(Position::Anywhere),
            ))
        } else {
            Err(BoxedError::new(
                CVError::ItemError,
                "Invalid ID",
                "The ID should be numeric",
                Context::default().lines(0, rule.to_string()),
            ))
        }
    }
}