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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
//! Handle modification related issues, access provided if you want to dive deeply into modifications in your own code.
use std::{
collections::{BTreeSet, HashMap, HashSet},
fmt::{Display, Write},
path::Path,
sync::Arc,
};
use context_error::*;
use itertools::Itertools;
use mzcv::SynonymScope;
use ordered_float::OrderedFloat;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thin_vec::ThinVec;
use crate::{
chemistry::{AmbiguousLabel, Chemical, DiagnosticIon, MolecularFormula, NeutralLoss},
glycan::{BackboneFragmentKind, GlycanAttachement, GlycanStructure, MonoSaccharide},
helper_functions::merge_hashmap,
molecular_formula,
ontology::{CustomDatabase, Ontology},
parse_json::ParseJson,
quantities::Multi,
sequence::{
AminoAcid, CrossLinkName, CrossLinkSide, Linked, LinkerSpecificity, MUPSettings,
Peptidoform, PlacementRule, SequenceElement, SequencePosition, SimpleModification,
SimpleModificationInner,
},
space::{Space, UsedSpace},
system::OrderedMass,
};
/// A modification on an amino acid
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum Modification {
/// Any of the simple modifications
Simple(SimpleModification),
/// A cross link to another (or the same) peptide, a branch is also seen as a cross-link but then the name is None.
CrossLink {
/// The index of the peptide this cross-link is bound to (can be the index for this peptide if it is an intra link)
peptide: usize,
/// The sequence index where this cross-link is bound to
sequence_index: SequencePosition,
/// The linker that defines the chemical structure that is the actual linker
linker: SimpleModification,
/// The name of the cross-linker, if [`CrossLinkName::Branch`] it is a branch instead of cross-link
name: CrossLinkName,
/// To determine if the cross-link is placed symmetrically or if asymmetrically if this is the left or right side
side: CrossLinkSide,
},
/// An ambiguous modification, that can be placed at multiple locations
Ambiguous {
/// The name of the group
group: String,
/// The id to compare be able to find the other locations where this modifications can be placed
id: usize,
/// The modification itself
modification: SimpleModification,
/// If present the localisation score, meaning the chance/ratio for this modification to show up on this exact spot
localisation_score: Option<OrderedFloat<f64>>,
/// If this is the preferred location or not
preferred: bool,
},
}
/// A modification id/name
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct ModificationId {
/// The ontology where this linker is defined
pub ontology: Ontology,
/// The name
pub name: Box<str>,
/// The ID, `u32::MAX` is defined as not having an ID
id: u32,
/// The description or definition
pub description: Box<str>,
/// Any synonyms
pub synonyms: ThinVec<(SynonymScope, Box<str>)>,
/// Cross reference IDs
pub cross_ids: ThinVec<(Option<Box<str>>, Box<str>)>,
/// Indicate if this modification is marked as obsolete
pub obsolete: bool,
}
impl ModificationId {
/// Create a new Modification ID
/// # Panics
/// If the id is equal to `u32::MAX` (only in debug mode, in release mode this is silently ignored and the id is set to None)
pub fn new(
ontology: Ontology,
name: Box<str>,
id: Option<u32>,
description: Box<str>,
synonyms: ThinVec<(SynonymScope, Box<str>)>,
cross_ids: ThinVec<(Option<Box<str>>, Box<str>)>,
obsolete: bool,
) -> Self {
debug_assert!(
id.is_none_or(|i| i != u32::MAX),
"Modification ID cannot be u32::MAX"
);
Self {
ontology,
name,
id: id.unwrap_or(u32::MAX),
description,
synonyms,
cross_ids,
obsolete,
}
}
/// Get the ID of this modification
pub fn id(&self) -> Option<u32> {
(self.id != u32::MAX).then_some(self.id)
}
/// Set the ID of this modification
/// # Panics
/// If the id is equal to `u32::MAX` (only in debug mode, in release mode this is silently ignored and the id is set to None)
pub fn set_id(&mut self, id: Option<u32>) {
debug_assert!(
id.is_none_or(|i| i != u32::MAX),
"Modification ID cannot be u32::MAX"
);
self.id = id.unwrap_or(u32::MAX);
}
}
impl Space for ModificationId {
fn space(&self) -> UsedSpace {
(self.ontology.space()
+ self.name.space()
+ self.id.space()
+ self.description.space()
+ self.synonyms.space()
+ self.cross_ids.space()
+ self.obsolete.space())
.set_total::<Self>()
}
}
impl ParseJson for ModificationId {
fn from_json_value(value: Value) -> Result<Self, BoxedError<'static, BasicKind>> {
if let Value::Object(mut map) = value {
let context = |map: &serde_json::Map<String, Value>| {
Context::show(map.iter().map(|(k, v)| format!("\"{k}\": {v}")).join(","))
};
Ok(Self {
ontology: Ontology::from_json_value(map.remove("ontology").ok_or_else(|| {
BoxedError::new(
BasicKind::Error,
"Invalid ModificationID",
"The required property 'ontology' is missing",
context(&map),
)
})?)?,
name: Box::from_json_value(map.remove("name").ok_or_else(|| {
BoxedError::new(
BasicKind::Error,
"Invalid ModificationID",
"The required property 'name' is missing",
context(&map),
)
})?)?,
id: u32::from_json_value(map.remove("id").ok_or_else(|| {
BoxedError::new(
BasicKind::Error,
"Invalid ModificationID",
"The required property 'id' is missing",
context(&map),
)
})?)?,
description: Box::from_json_value(map.remove("description").ok_or_else(|| {
BoxedError::new(
BasicKind::Error,
"Invalid ModificationID",
"The required property 'description' is missing",
context(&map),
)
})?)?,
synonyms: {
let element = map.remove("synonyms").ok_or_else(|| {
BoxedError::new(
BasicKind::Error,
"Invalid ModificationID",
"The required property 'synonyms' is missing",
context(&map),
)
})?;
if let Value::Array(arr) = element {
let mut output = ThinVec::with_capacity(arr.len());
for el in arr {
match el {
Value::String(str) => {
output.push((SynonymScope::Exact, str.into_boxed_str()));
}
Value::Array(mut tup) if tup.len() == 2 => {
let b = Box::from_json_value(tup.pop().unwrap())?;
let a = SynonymScope::from_json_value(tup.pop().unwrap())?;
output.push((a, b));
}
el => {
return Err(BoxedError::new(
BasicKind::Error,
"Invalid ModificationID",
"A synonym could not be parsed, it has to be either a string or a tuple with two elements",
Context::show(el.to_string()),
));
}
}
}
output
} else {
return Err(BoxedError::new(
BasicKind::Error,
"Invalid ModificationID",
"Synonyms should be an array",
Context::show(element.to_string()),
));
}
},
cross_ids: ThinVec::from_json_value(map.remove("cross_ids").ok_or_else(|| {
BoxedError::new(
BasicKind::Error,
"Invalid ModificationID",
"The required property 'cross_ids' is missing",
context(&map),
)
})?)?,
obsolete: map
.remove("obsolete")
.map_or(Ok(false), |v| bool::from_json_value(v))?,
})
} else {
Err(BoxedError::new(
BasicKind::Error,
"Invalid ModificationID",
"The JSON value has to be a map",
Context::show(value.to_string()),
))
}
}
}
/// All possible compositions in the GNO ontology
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum GnoComposition {
/// Only the mass is known
Weight(OrderedMass),
/// The composition,
Composition(Vec<(MonoSaccharide, isize)>),
/// The (full) structure is known
Topology(GlycanStructure),
}
impl Space for GnoComposition {
fn space(&self) -> UsedSpace {
(UsedSpace::stack(1)
+ match self {
Self::Weight(w) => w.space(),
Self::Composition(c) => c.space(),
Self::Topology(t) => t.space(),
})
.set_total::<Self>()
}
}
/// All possible subsumption levels in the GNOme database indicating different levels of description for a glycan species
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Serialize, Deserialize,
)]
pub enum GnoSubsumption {
/// Indicates only the average weight is defined
#[default]
AverageWeight,
/// Indicates the basic composition, without isomeric information
BaseComposition,
/// Indicates the composition, with isomeric information
Composition,
/// Indicates the topology, without linkage and anomeric information
Topology,
/// Indicates the topology, without reducing end ring and anomeric information
Saccharide,
}
impl Display for GnoSubsumption {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::AverageWeight => write!(f, "Average weight"),
Self::BaseComposition => write!(f, "Base composition (no isomeric information)"),
Self::Composition => write!(f, "Composition"),
Self::Topology => write!(f, "Topology (no linkage)"),
Self::Saccharide => write!(f, "Saccharide"),
}
}
}
impl ModificationId {
/// Get the accession number name for the ontology
pub fn url(&self) -> Option<String> {
match self.ontology {
Ontology::Unimod => Some(format!(
"https://www.unimod.org/modifications_view.php?editid1={}",
self.id
)),
Ontology::Psimod => Some(format!(
"https://ontobee.org/ontology/MOD?iri=http://purl.obolibrary.org/obo/MOD_{:05}",
self.id
)),
Ontology::Gnome => Some(format!(
"http://glytoucan.org/Structures/Glycans/{}",
self.name.to_ascii_uppercase()
)),
Ontology::Resid => Some(format!(
"https://proteininformationresource.org/cgi-bin/resid?id=AA{:04}",
self.id
)),
Ontology::Xlmod | Ontology::Custom => None,
}
}
}
impl Display for ModificationId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.ontology == Ontology::Gnome {
write!(
f,
"{}:{}",
self.ontology.char(),
self.name.to_ascii_uppercase()
)
} else if self.ontology == Ontology::Xlmod
&& let Some(id) = self.id()
&& (id == 1711 || id == 9070)
{
write!(f, "{}:{id}", self.ontology.name())
} else {
write!(f, "{}:{}", self.ontology.char(), self.name)
}
}
}
/// The result of checking if a modification can be placed somewhere.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum RulePossible {
/// This modification cannot be placed
No,
/// This modification can be placed and if it is a cross-link it can be placed on both ends
Symmetric(BTreeSet<usize>),
/// This modification can be placed and if it is a cross-link it can only be placed on the 'left' side of the cross-link
AsymmetricLeft(BTreeSet<usize>),
/// This modification can be placed and if it is a cross-link it can only be placed on the 'right' side of the cross-link
AsymmetricRight(BTreeSet<usize>),
}
impl RulePossible {
/// Flatten this into a bool, check if the rule is not [`Self::No`]
pub fn any_possible(self) -> bool {
self != Self::No
}
}
impl std::ops::Add for RulePossible {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
match (self, rhs) {
(Self::Symmetric(a), _) | (_, Self::Symmetric(a)) => Self::Symmetric(a),
(Self::AsymmetricLeft(l), Self::AsymmetricRight(r))
| (Self::AsymmetricRight(l), Self::AsymmetricLeft(r)) => {
let overlap: BTreeSet<usize> = l.intersection(&r).copied().collect();
if overlap.is_empty() {
Self::No
} else {
Self::Symmetric(overlap)
}
}
(Self::AsymmetricLeft(l), _) | (_, Self::AsymmetricLeft(l)) => Self::AsymmetricLeft(l),
(Self::AsymmetricRight(r), _) | (_, Self::AsymmetricRight(r)) => {
Self::AsymmetricRight(r)
}
_ => Self::No,
}
}
}
impl std::iter::Sum for RulePossible {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self::No, |acc, i| acc + i)
}
}
impl CrossLinkSide {
/// Get all allowed placement rules with all applicable neutral losses, stubs, and diagnostic ions.
pub(crate) fn allowed_rules(
&self,
linker: &SimpleModification,
) -> (
Vec<NeutralLoss>,
Vec<(MolecularFormula, MolecularFormula)>,
Vec<DiagnosticIon>,
) {
let selected_rules = match self {
Self::Left(r) | Self::Right(r) | Self::Symmetric(r) => r,
};
let mut all_neutral = Vec::new();
let mut all_stubs = Vec::new();
let mut all_diagnostic = Vec::new();
match &**linker {
SimpleModificationInner::Linker { specificities, .. } => {
for rule in specificities
.iter()
.enumerate()
.filter_map(|(i, r)| selected_rules.contains(&i).then_some(r))
{
match rule {
LinkerSpecificity::Asymmetric {
diagnostic,
stubs,
neutral_losses,
..
} => {
all_neutral.extend_from_slice(neutral_losses);
all_diagnostic.extend_from_slice(diagnostic);
match self {
Self::Left(_) => all_stubs.extend(stubs.iter().cloned()),
Self::Right(_) => {
all_stubs
.extend(stubs.iter().map(|(l, r)| (r.clone(), l.clone())));
}
Self::Symmetric(_) => {
all_stubs.extend(stubs.iter().flat_map(|(l, r)| {
vec![(l.clone(), r.clone()), (r.clone(), l.clone())]
}));
}
}
}
LinkerSpecificity::Symmetric {
stubs,
neutral_losses,
diagnostic,
..
} => {
all_stubs.extend_from_slice(stubs);
all_neutral.extend_from_slice(neutral_losses);
all_diagnostic.extend_from_slice(diagnostic);
}
}
}
}
SimpleModificationInner::Database { specificities, .. } => {
for rule in specificities
.iter()
.enumerate()
.filter_map(|(i, r)| selected_rules.contains(&i).then_some(r))
{
all_neutral.extend_from_slice(&rule.1);
all_diagnostic.extend_from_slice(&rule.2);
}
}
_ => (),
}
(all_neutral, all_stubs, all_diagnostic)
}
}
impl Modification {
/// Check if this modification is a simple modification.
pub const fn is_simple(&self) -> bool {
matches!(self, Self::Simple(_))
}
/// Check if this modification is a cross-link.
pub const fn is_cross_link(&self) -> bool {
matches!(self, Self::CrossLink { .. })
}
/// Check if this modification is an ambiguous modification.
pub const fn is_ambiguous(&self) -> bool {
matches!(self, Self::Ambiguous { .. })
}
/// Get the formula for the whole addition (or subtraction) for this modification
#[doc(hidden)]
pub fn formula_inner(
&self,
all_peptides: &[Peptidoform<Linked>],
visited_peptides: &[usize],
applied_cross_links: &mut Vec<CrossLinkName>,
allow_ms_cleavable: bool,
sequence_index: SequencePosition,
peptidoform_index: usize,
peptidoform_ion_index: usize,
glycan_model: &impl GlycanAttachement,
attachment: Option<AminoAcid>,
) -> (
Multi<MolecularFormula>,
HashMap<BackboneFragmentKind, Multi<MolecularFormula>>,
HashSet<CrossLinkName>,
) {
match self {
Self::Simple(modification) | Self::Ambiguous { modification, .. } => {
match &**modification {
// A linker that is not cross-linked is hydrolysed
SimpleModificationInner::Linker { formula, .. } => (
(formula.clone() + molecular_formula!(H 2 O 1)).into(),
HashMap::new(),
HashSet::new(),
),
s => {
let default_rules = glycan_model.get_default_fragments(attachment);
let specific_rules = glycan_model.get_specific_fragments(attachment);
let f = s.formula_inner(
sequence_index,
peptidoform_index,
default_rules,
attachment,
);
let specific = specific_rules
.into_iter()
.map(|(k, settings)| {
(
k,
s.formula_inner(
sequence_index,
peptidoform_index,
settings,
attachment,
),
)
})
.collect();
(f, specific, HashSet::new())
}
}
}
Self::CrossLink {
peptide: other_peptide,
linker,
name,
side,
..
} => {
if applied_cross_links.contains(name) {
(Multi::default(), HashMap::new(), HashSet::default())
} else if visited_peptides.contains(other_peptide) {
applied_cross_links.push(name.clone());
(
linker
.formula_inner(
sequence_index,
peptidoform_index,
glycan_model.get_default_fragments(attachment),
attachment,
)
.with_label(&AmbiguousLabel::CrossLinkBound(name.clone())),
HashMap::new(),
HashSet::from([name.clone()]),
)
} else {
applied_cross_links.push(name.clone());
let link = linker.formula_inner(
sequence_index,
peptidoform_index,
glycan_model.get_default_fragments(attachment),
attachment,
);
let (_, stubs, _) = side.allowed_rules(linker);
if allow_ms_cleavable && !stubs.is_empty() {
let mut options: Vec<MolecularFormula> = stubs
.iter()
.map(|s| {
s.0.clone().with_label(AmbiguousLabel::CrossLinkBroken(
name.clone(),
s.0.clone(),
))
})
.unique()
.collect();
let mut seen_peptides = HashSet::from([name.clone()]);
let mut specific = HashMap::new();
options.extend_from_slice(&{
let (f, f_specific, seen) = all_peptides[*other_peptide]
.formulas_inner(
*other_peptide,
peptidoform_ion_index,
all_peptides,
visited_peptides,
applied_cross_links,
false,
glycan_model,
);
seen_peptides.extend(seen);
specific = merge_hashmap(specific, &f_specific, &link, &f);
(f * link)
.with_label(&AmbiguousLabel::CrossLinkBound(name.clone()))
.to_vec()
});
(options.into(), specific, seen_peptides)
} else {
let (f, specific, mut seen) = all_peptides[*other_peptide].formulas_inner(
*other_peptide,
peptidoform_ion_index,
all_peptides,
visited_peptides,
applied_cross_links,
false,
glycan_model,
);
seen.insert(name.clone());
(
(f * link).with_label(&AmbiguousLabel::CrossLinkBound(name.clone())),
specific,
seen,
)
}
}
}
}
}
/// Get the formula for a modification, if it is a cross linked modification only get the cross link
pub fn formula(&self) -> MolecularFormula {
match self {
Self::Simple(s) => s.formula(),
Self::CrossLink { linker, .. } => linker.formula(),
Self::Ambiguous { modification, .. } => modification.formula(),
}
}
/// Check if this is a simple modification
pub const fn simple(&self) -> Option<&SimpleModification> {
match self {
Self::Simple(sim) => Some(sim),
Self::CrossLink { .. } | Self::Ambiguous { .. } => None,
}
}
/// Check if this is a simple modification
pub fn into_simple(self) -> Option<SimpleModification> {
match self {
Self::Simple(sim) => Some(sim),
Self::CrossLink { .. } | Self::Ambiguous { .. } => None,
}
}
/// Get a url for more information on this modification. Only defined for modifications from ontologies.
pub fn ontology_url(&self) -> Option<String> {
match self {
Self::Simple(modification)
| Self::Ambiguous { modification, .. }
| Self::CrossLink {
linker: modification,
..
} => modification.ontology_url(),
}
}
/// Check to see if this modification can be placed on the specified element
pub fn is_possible<T>(
&self,
seq: &SequenceElement<T>,
position: SequencePosition,
) -> RulePossible {
self.simple()
.map_or(RulePossible::Symmetric(BTreeSet::new()), |s| {
s.is_possible(seq, position)
})
}
/// Get the name if this is an Unimod modification (for use in mzPAF)
pub fn unimod_name(&self) -> Option<&str> {
match self {
Self::Simple(s)
| Self::CrossLink { linker: s, .. }
| Self::Ambiguous {
modification: s, ..
} => match &**s {
SimpleModificationInner::Database {
id:
ModificationId {
ontology: Ontology::Unimod,
name,
..
},
..
} => Some(name),
_ => None,
},
}
}
}
/// The structure to lookup ambiguous modifications, with a list of all modifications (the order is fixed) with for each modification their name and the actual modification itself (if already defined)
pub type AmbiguousLookup = Vec<AmbiguousLookupEntry>;
/// An entry in the ambiguous lookup
#[derive(Clone, Debug)]
pub struct AmbiguousLookupEntry {
/// The name of the modification
pub name: String,
/// The group of the modification
pub group: Option<usize>,
/// The modification itself
pub modification: Option<SimpleModification>,
/// The allowed locations, the actual allowed locations is the intersection of this set with the ruleset from the modification
position: Option<Vec<PlacementRule>>,
/// The maximal number of this modification on one place
limit: Option<usize>,
/// Determines if this modification can colocalise with placed modifications eg if the modification of unknown position is allowed at the second M '[Oxidation]?MM[Dioxidation]M'
colocalise_placed_modifications: bool,
/// Determines if this modification can colocalise with other modifications of unknown position
colocalise_modifications_of_unknown_position: bool,
}
impl AmbiguousLookupEntry {
/// Create a new ambiguous lookup entry
pub const fn new(name: String, modification: Option<SimpleModification>) -> Self {
Self {
name,
group: None,
modification,
limit: None,
position: None,
colocalise_placed_modifications: true,
colocalise_modifications_of_unknown_position: true,
}
}
/// Copy settings into this lookup entry
pub fn copy_settings(&mut self, settings: &MUPSettings) {
self.position.clone_from(&settings.position);
self.limit = settings.limit;
self.colocalise_placed_modifications = settings.colocalise_placed_modifications;
self.colocalise_modifications_of_unknown_position =
settings.colocalise_modifications_of_unknown_position;
}
/// Get the settings for this modification of unknown position
pub fn as_settings(&self) -> MUPSettings {
MUPSettings {
position: self.position.clone(),
limit: self.limit,
colocalise_placed_modifications: self.colocalise_placed_modifications,
colocalise_modifications_of_unknown_position: self
.colocalise_modifications_of_unknown_position,
}
}
}
/// The structure to lookup cross-links, with a list of all linkers (the order is fixed) with for each linker their name or None if it is a branch and the actual linker itself (if already defined)
pub type CrossLinkLookup = Vec<(CrossLinkName, Option<SimpleModification>)>;
impl Modification {
/// Display a modification either normalised to the internal representation or as fully valid ProForma
/// (no glycan structure or custom modifications). `display_ambiguous` shows or hides the modification
/// definition of any ambiguous modifications (eg true results in '+1#1' false in '#1').
/// # Errors
/// When the given writer errors.
pub fn display(
&self,
f: &mut impl Write,
specification_compliant: bool,
display_ambiguous: bool,
) -> std::fmt::Result {
match self {
Self::Simple(sim) => sim.display(f, specification_compliant),
Self::CrossLink { name, linker, .. } => {
linker.display(f, specification_compliant)?;
write!(f, "{name}")?;
Ok(())
}
Self::Ambiguous {
group,
modification,
localisation_score,
..
} => {
if display_ambiguous {
modification.display(f, specification_compliant)?;
}
write!(
f,
"\x23{group}{}",
localisation_score
.map(|v| format!("({v})"))
.unwrap_or_default()
)?;
Ok(())
}
}
}
}
impl Display for Modification {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.display(f, true, true)
}
}
impl From<SimpleModification> for Modification {
fn from(value: SimpleModification) -> Self {
Self::Simple(value)
}
}
impl From<SimpleModificationInner> for Modification {
fn from(value: SimpleModificationInner) -> Self {
Self::Simple(Arc::new(value))
}
}
impl Display for CrossLinkName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Branch => write!(f, "#BRANCH"),
Self::Name(n) => write!(f, "#XL{n}"),
}
}
}
/// Parse a custom modifications JSON string. The parser is guaranteed to be backwards compatible
/// with any JSON made by the serde serialisation of the custom database in previous version of
/// the library.
/// # Errors
/// If the string could not be parsed.
pub fn parse_custom_modifications(
path: &Path,
) -> Result<CustomDatabase, BoxedError<'static, BasicKind>> {
let string = std::fs::read_to_string(path).map_err(|err| {
BoxedError::new(
BasicKind::Error,
"Could not parse custom modifications file",
err.to_string(),
Context::default().source(path.to_string_lossy()).to_owned(),
)
})?;
CustomDatabase::from_json(&string)
}
/// Parse a custom modifications JSON string. The parser is guaranteed to be backwards compatible
/// with any JSON made by the serde serialisation of the custom database in previous version of
/// the library.
/// # Errors
/// If the string could not be parsed.
pub fn parse_custom_modifications_str(
value: &str,
) -> Result<CustomDatabase, BoxedError<'static, BasicKind>> {
CustomDatabase::from_json(value)
}
#[cfg(test)]
#[expect(clippy::missing_panics_doc)]
mod test {
use super::*;
#[test]
fn test_reading_custom_modifications_json_2024() {
let data = include_str!("custom_modifications_2024.json");
let mods = parse_custom_modifications_str(data).unwrap();
assert!(mods.len() > 1);
}
#[test]
fn test_reading_custom_modifications_json_2025() {
let data = include_str!("custom_modifications_20250207.json");
let mods = parse_custom_modifications_str(data).unwrap();
assert!(mods.len() > 1);
}
}