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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! Code to handle the XL-MOD ontology
use std::collections::HashMap;
use context_error::{
BoxedError, Context, CreateError, FullErrorContent, StaticErrorContent, combine_error,
combine_errors,
};
use mzcv::{
CVError, CVFile, CVSource, CVVersion, Comment, HashBufReader, Modifier, OboIdentifier,
OboOntology, OboStanzaType, OboValue, RelationType,
};
use thin_vec::ThinVec;
use crate::{
chemistry::{DiagnosticIon, MolecularFormula, NeutralLoss},
helper_functions::explain_number_error,
ontology::{
Ontology,
ontology_modification::{ModData, OntologyModification},
},
sequence::{
AminoAcid, CrossId, LinkerLength, LinkerSpecificity, PlacementRule, Position,
SimpleModification, SimpleModificationInner,
},
};
/// XL-MOD modifications
#[allow(missing_copy_implementations, missing_debug_implementations)]
pub struct XlMod {}
impl CVSource for XlMod {
type Data = SimpleModificationInner;
type Structure = Vec<SimpleModification>;
fn cv_name() -> &'static str {
"XLMOD"
}
fn files() -> &'static [CVFile] {
&[CVFile {
name: "XLMOD",
extension: "obo",
url: Some(
"https://raw.githubusercontent.com/HUPO-PSI/xlmod-CV/refs/heads/main/XLMOD.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/xlmod.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().unwrap();
let mut errors = Vec::new();
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()),
]
})
.map(|obo| {
(
obo.version(),
{
let mut mods: Vec<OntologyModification> = Vec::new();
for obj in &obo.objects {
if obj.stanza_type != OboStanzaType::Term {
continue;
}
let id: u32 = match obj
.id
.1
.parse() {
Ok(v) => v,
Err(err) => {
combine_error(&mut errors, BoxedError::new(CVError::ItemError, "Invalid XLMOD", format!("The ID is {}", explain_number_error(&err)), Context::default().lines(0, obj.id.1.to_string())));
continue;
}
};
let name = obj.lines["name"][0].0.clone();
let description = obj
.definition
.as_ref()
.map_or_else(Box::default, |d| d.0.clone());
let cross_ids = obj
.definition
.as_ref()
.map_or_else(ThinVec::new, |d| d.1.iter().filter(|c| !(c.0.as_ref().is_some_and(|c| c.eq_ignore_ascii_case("psi") || c.eq_ignore_ascii_case("pxi")) && c.1.eq_ignore_ascii_case("XL"))).cloned().collect());
let synonyms = obj
.synonyms
.iter()
.map(|s| (s.scope, s.synonym.clone()))
.collect();
// Get all properties from any ancestors in the tree then get all properties from this definition
let mut properties = Properties::default();
let mut stack = Vec::new();
stack.extend(obj.relationship.clone());
let is_homo_functional = obj.relationship.iter().any(|r| r.0 == RelationType::IsA && r.1 == OboIdentifier(Some("XLMOD".into()), "00005".into()));
while let Some((ty, id, _, _)) = stack.pop() {
if (ty == RelationType::IsA || is_homo_functional && ty == RelationType::Other("has_reactive_group".into())) && let Some(obj) = obo.objects.iter().find(|o| o.id == id) {
combine_errors(
&mut errors,
parse_property_values(
&obj.property_values,
&mut properties,
id,
),
);
stack.extend(obj.relationship.clone());
}
}
combine_errors(
&mut errors,
parse_property_values(
&obj.property_values,
&mut properties,
obj.id.clone(),
),
);
if properties.origins.0.is_empty() {
properties.origins.0 = vec![PlacementRule::Position(Position::Anywhere)];
}
let cross_ids = match cross_ids
.iter()
.map(|v| v.clone().try_into())
.collect::<Result<ThinVec<CrossId>, _>>()
{
Ok(ids) => ids,
Err(err) => {combine_error(&mut errors, err.convert(|_| CVError::ItemError)); continue},
};
if properties.sites == Some(2) {
let mut m =
OntologyModification {
formula: properties.formula.unwrap_or_default(),
name,
description,
cross_ids,
synonyms,
id: mzcv::AccessionCode::Numeric(id),
ontology: Ontology::Xlmod,
obsolete: obj.obsolete,
data: ModData::Linker {
length: properties.length,
specificities: vec![
if properties.origins.1.is_empty() {
LinkerSpecificity::Symmetric {
rules: properties.origins.0,
stubs: properties.stubs,
neutral_losses: properties.neutral_losses,
diagnostic: properties.diagnostic_ions,
}
} else {
LinkerSpecificity::Asymmetric {
rules: (
properties.origins.0,
properties.origins.1,
),
stubs: properties.stubs,
neutral_losses: properties.neutral_losses,
diagnostic: properties.diagnostic_ions,
}
},
],
},
parents: ThinVec::default(),
};
m.add_relationships(&obj.relationship);
mods.push(m);
} else if properties.sites == Some(1) {
let mut m =
OntologyModification {
formula: properties.formula.unwrap_or_default(),
name,
description,
cross_ids,
synonyms,
ontology: Ontology::Xlmod,
obsolete: obj.obsolete,
id: mzcv::AccessionCode::Numeric(id),
data: ModData::Mod {
specificities: vec![(
properties.origins.0,
properties.neutral_losses,
properties.diagnostic_ions,
)],
},
parents: ThinVec::default(),
};
m.add_relationships(&obj.relationship);
mods.push(m);
} else if !properties.dna_linker && !obj.property_values.is_empty() {
if let Some(sites) = properties.sites {
combine_error(&mut errors, BoxedError::new(
CVError::ItemWarning,
"Higher order cross-linker",
format!("This cross-linker links {sites} sites, but only cross-linkers with two sites are supported for now, this modification will be ignored"),
Context::default().lines(0, format!("XLMOD:{id:05}"))));
} else {
combine_error(&mut errors, BoxedError::new(
CVError::ItemWarning,
"Undefined modification",
"This modification has no definition of the number of sites it links, this modification will be ignored",
Context::default().lines(0, format!("XLMOD:{id:05}"))));
}
}
}
OntologyModification::finish(mods)
},
errors,
)
})
}
}
#[derive(Default)]
struct Properties {
dna_linker: bool,
sites: Option<u8>,
length: LinkerLength,
formula: Option<MolecularFormula>,
origins: (Vec<PlacementRule>, Vec<PlacementRule>),
diagnostic_ions: Vec<DiagnosticIon>,
neutral_losses: Vec<NeutralLoss>,
stubs: Vec<(MolecularFormula, MolecularFormula)>,
}
fn parse_property_values(
property_values: &HashMap<Box<str>, Vec<(OboValue, Vec<Modifier>, Comment)>>,
properties: &mut Properties,
id: OboIdentifier,
) -> Vec<BoxedError<'static, CVError>> {
let mut mass = None;
let mut errors = Vec::new();
for (property, value) in property_values {
match property.as_ref() {
"reactionSites" => {
if value.len() > 1 {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemWarning,
"Multiple reaction sites",
"More than 1 'reactionSites` definitions for this entry",
Context::default().lines(0, id.to_string()),
),
);
}
properties.sites = if let OboValue::Integer(n, _) = value[0].0 {
u8::try_from(n).map_or_else(
|_| {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemError,
"Out of range number of sites",
"The number of sites can only be in range 0—255",
Context::default().lines(0, value[0].0.to_string()).to_owned(),
),
);
None
},
Some,
)
} else {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemError,
"Invalid type",
"Invalid item type",
Context::default().lines(
0,
format!(
"{id}: reactionSites: type: {}, expected: integer",
value[0].0.datatype()
),
),
),
);
None
}
}
"spacerLength" => {
for (def, ..) in value {
let length = if let OboValue::Float(n, ..) = def {
*n
} else {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemError,
"Invalid type",
"Invalid item type",
Context::default().lines(
0,
format!(
"{id}: spacerLength: type: {}, expected: float",
def.datatype()
),
),
),
);
0.0
};
match &mut properties.length {
LinkerLength::Discrete(options) => {
options.push(length.into());
}
l => *l = LinkerLength::Discrete(vec![length.into()]),
}
}
}
"minSpacerLength" => {
if value.len() > 1 {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemWarning,
"Multiple minSpacerLength",
"More than 1 'minSpacerLength` definitions for this entry",
Context::default().lines(0, id.to_string()),
),
);
}
let length = if let OboValue::Float(n, ..) = value[0].0 {
n
} else {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemError,
"Invalid type",
"Invalid item type",
Context::default().lines(
0,
format!(
"{id}: minSpacerLength: type: {}, expected: float",
value[0].0.datatype()
),
),
),
);
0.0
};
match &mut properties.length {
LinkerLength::InclusiveRange(start, _) => {
*start = length.into();
}
l => {
*l = LinkerLength::InclusiveRange(length.into(), length.into());
}
}
}
"maxSpacerLength" => {
if value.len() > 1 {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemWarning,
"Multiple maxSpacerLength",
"More than 1 'maxSpacerLength` definitions for this entry",
Context::default().lines(0, id.to_string()),
),
);
}
let length = if let OboValue::Float(n, ..) = value[0].0 {
n
} else {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemError,
"Invalid type",
"Invalid item type",
Context::default().lines(
0,
format!(
"{id}: maxSpacerLength: type: {}, expected: float",
value[0].0.datatype()
),
),
),
);
0.0
};
match &mut properties.length {
LinkerLength::InclusiveRange(_, end) => {
*end = length.into();
}
l => {
*l = LinkerLength::InclusiveRange(length.into(), length.into());
}
}
}
"monoIsotopicMass" => {
if value.len() > 1 {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemWarning,
"Multiple monoIsotopicMass",
"More than 1 'monoIsotopicMass` definitions for this entry",
Context::default().lines(0, id.to_string()),
),
);
}
mass = if let OboValue::Float(n, ..) = value[0].0 {
Some(ordered_float::OrderedFloat(n))
} else {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemError,
"Invalid type",
"Invalid item type",
Context::default().lines(
0,
format!(
"{id}: monoIsotopicMass: type: {}, expected: float",
value[0].0.datatype()
),
),
),
);
None
}
}
"deadEndFormula" => {
if value.len() > 1 {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemWarning,
"Multiple deadEndFormula",
"More than 1 'deadEndFormula` definitions for this entry",
Context::default().lines(0, id.to_string()),
),
);
}
properties.sites = Some(1);
properties.formula = MolecularFormula::xlmod(&value[0].0.to_string())
.map_err(|e| {
combine_error(&mut errors, e.to_owned().convert(|_| CVError::ItemError));
})
.ok();
}
"neutralLossFormula" => {
for (def, ..) in value {
match MolecularFormula::xlmod(&def.to_string()) {
Ok(v) => properties.neutral_losses.push(v.into()),
Err(err) => combine_error(
&mut errors,
err.to_owned().convert::<CVError, BoxedError<'static, CVError>>(|_| {
CVError::ItemError
}),
),
}
}
}
"bridgeFormula" => {
if value.len() > 1 {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemWarning,
"Multiple bridgeFormula",
"More than 1 'bridgeFormula` definitions for this entry",
Context::default().lines(0, id.to_string()),
),
);
}
properties.sites = properties.sites.or(Some(2));
properties.formula = MolecularFormula::xlmod(&value[0].0.to_string())
.map_err(|e| {
combine_error(&mut errors, e.to_owned().convert(|_| CVError::ItemError));
})
.ok();
}
"specificities" => {
// specificities: "(C,U)" xsd:string
// specificities: "(K,N,Q,R,Protein N-term)&(E,D,Protein C-term)" xsd:string
if value.len() > 1 {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemWarning,
"Multiple specificities",
"More than 1 'specificities` definitions for this entry",
Context::default().lines(0, id.to_string()),
),
);
}
if let Some((l, r)) = value[0].0.to_string().split_once('&') {
properties.sites = properties.sites.or(Some(2));
properties
.origins
.0
.extend(l.trim_matches(['(', ')']).split(',').filter_map(|s| {
read_placement_rule(s.trim())
.map_err(|err| combine_error(&mut errors, err))
.ok()
}));
properties
.origins
.1
.extend(r.trim_matches(['(', ')']).split(',').filter_map(|s| {
read_placement_rule(s.trim())
.map_err(|err| combine_error(&mut errors, err))
.ok()
}));
} else {
properties.origins.0.extend(
value[0].0.to_string().trim_matches(['(', ')']).split(',').filter_map(
|s| {
read_placement_rule(s.trim())
.map_err(|err| combine_error(&mut errors, err))
.ok()
},
),
);
}
}
"secondarySpecificities" => {
// TODO: keep track that these are 'secondary' somewhere, similarly to the Unimod
// hidden state secondarySpecificities: "(S,T,Y)" xsd:string
if value.len() > 1 {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemWarning,
"Multiple secondarySpecificities",
"More than 1 'secondarySpecificities` definitions for this entry",
Context::default().lines(0, id.to_string()),
),
);
}
properties.origins.0.extend(
value[0].0.to_string().trim_matches(['(', ')']).split(',').filter_map(|s| {
read_placement_rule(s.trim())
.map_err(|err| combine_error(&mut errors, err))
.ok()
}),
);
}
"baseSpecificities" | "secondarybaseSpecificities" => {
properties.dna_linker = true;
}
"reporterMass" | "CID_Fragment" => {
// reporterMass: "555.2481" xsd:double
// CID_Fragment: "828.5" xsd:double
for (def, ..) in value {
properties.diagnostic_ions.push(DiagnosticIon(
MolecularFormula::with_additional_mass(
if let OboValue::Float(n, ..) = def {
*n
} else {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemError,
"Invalid type",
"Invalid item type",
Context::default().lines(
0,
format!(
"{id}: {property}: type: {}, expected: float",
value[0].0.datatype()
),
),
),
);
0.0
},
),
));
}
}
"reporterFormula" => {
for (def, ..) in value {
match MolecularFormula::xlmod(&def.to_string()) {
Ok(v) => properties.diagnostic_ions.push(v.into()),
Err(err) => combine_error(
&mut errors,
err.to_owned().convert::<CVError, BoxedError<'static, CVError>>(|_| {
CVError::ItemError
}),
),
}
}
}
"stubDefinition" | "stubFormula" => {
// CID = H4 C3 O2 S1, -H2 -O1 : H2 C3 O1
// ETD = -H1 :
// TODO: Extend the stub logic to handle the techniques and neutral losses
for (def, ..) in value {
if let OboValue::String(definition) = &def {
let (_techniques, definition) = definition.split_once('=').unwrap();
let (first, second) = definition.split_once(':').unwrap();
let mut split_first = first.split(',');
let mut split_second = second.split(',');
let formula_first =
split_first.next().map_or_else(MolecularFormula::default, |v| {
MolecularFormula::xlmod(v).unwrap()
});
let _losses_first: Vec<NeutralLoss> = split_first
.map(|v| MolecularFormula::xlmod(v).unwrap().into())
.collect();
let formula_second =
split_second.next().map_or_else(MolecularFormula::default, |v| {
MolecularFormula::xlmod(v).unwrap()
});
let _losses_second: Vec<NeutralLoss> = split_second
.map(|v| MolecularFormula::xlmod(v).unwrap().into())
.collect();
properties.stubs.push((formula_first, formula_second));
} else {
combine_error(
&mut errors,
BoxedError::new(
CVError::ItemError,
"Invalid type",
"Invalid item type",
Context::default().lines(
0,
format!(
"{id}: {property}: type: {}, expected: string",
value[0].0.datatype()
),
),
),
);
}
}
}
_ => {} // TODO: handle: hydrophilicPEGchain?, maxAbsorption?, waveLengthRange?
}
}
// Ignore the mass if a formula is set
properties.formula = properties
.formula
.clone()
.or_else(|| mass.map(|v| MolecularFormula::with_additional_mass(v.0)));
errors
}
/// Read a placement rule
/// # Errors
/// If not a valid placement rule
fn read_placement_rule(brick: &str) -> Result<PlacementRule, BoxedError<'static, CVError>> {
if brick.len() == 1
&& let Ok(aa) = AminoAcid::try_from(brick)
{
Ok(PlacementRule::AminoAcid(
vec![aa].into(),
Position::Anywhere,
))
} else if brick.eq_ignore_ascii_case("Protein N-term") {
Ok(PlacementRule::Position(Position::ProteinNTerm))
} else if brick.eq_ignore_ascii_case("Protein C-term") {
Ok(PlacementRule::Position(Position::ProteinCTerm))
} else {
Err(BoxedError::new(
CVError::ItemError,
"Invalid placement rule",
"Placement rule has to be an amino acid, protein N-term, or protein C-term.",
Context::default().lines(0, brick).to_owned(),
))
}
}