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
use std::collections::{BTreeMap, HashSet};
use context_error::*;
use itertools::Itertools;
use ordered_float::OrderedFloat;
use super::{GlobalModification, Linear};
use crate::{
ParserResult,
sequence::{
AmbiguousLookup, CrossLinkName, HiddenInternalMethods, LabileLocation, Modification,
Peptidoform, PeptidoformIon, PeptidoformIonSet, SequencePosition, SimpleModification,
},
};
impl PeptidoformIonSet {
/// Check if the names and identifiers in this peptidoform ion set follow all ProForma rules:
/// - All labile location identifiers and ambiguous identifiers follow the rules (nonempty,
/// ASCII alphanumeric, not starting with "XL", and is not "BRANCH").
/// - No labile location identifier or ambiguous identifier is reused.
/// - The name does not contain unclosed braces `()`.
pub fn are_identifiers_valid_proforma(&self) -> bool {
if self.name().chars().filter(|c| *c == '(').count()
!= self.name().chars().filter(|c| *c == ')').count()
{
return false;
}
for pep in self.peptidoform_ions() {
if !pep.are_identifiers_valid_proforma() {
return false;
}
}
true
}
}
impl PeptidoformIon {
/// Check if the names and identifiers in this peptidoform ion follow all ProForma rules:
/// - All labile location identifiers and ambiguous identifiers follow the rules (nonempty,
/// ASCII alphanumeric, not starting with "XL", and is not "BRANCH").
/// - No labile location identifier or ambiguous identifier is reused.
/// - The name does not contain unclosed braces `()`.
pub fn are_identifiers_valid_proforma(&self) -> bool {
if self.name().chars().filter(|c| *c == '(').count()
!= self.name().chars().filter(|c| *c == ')').count()
{
return false;
}
for pep in self.peptidoforms() {
if !pep.are_identifiers_valid_proforma() {
return false;
}
}
true
}
}
impl<Complexity> Peptidoform<Complexity> {
/// Check if the names and identifiers in this peptidoform follow all ProForma rules:
/// - All labile location identifiers and ambiguous identifiers follow the rules (nonempty,
/// ASCII alphanumeric, not starting with "XL", and is not "BRANCH").
/// - No labile location identifier or ambiguous identifier is reused.
/// - The name does not contain unclosed braces `()`.
pub fn are_identifiers_valid_proforma(&self) -> bool {
fn valid_identifier(id: &str) -> bool {
!(id.is_empty()
|| id.eq_ignore_ascii_case("BRANCH")
|| id.chars().next().is_some_and(|c| c == 'X' || c == 'x')
&& id.chars().nth(1).is_some_and(|c| c == 'L' || c == 'l'))
&& id.chars().all(|c| c.is_ascii_alphanumeric())
}
let mut identifiers = HashSet::new();
let mut ambiguous_mods = HashSet::new();
for labile_identifier in self.get_labile().iter().filter_map(|(_, p)| {
if let LabileLocation::Known(i, _) = p {
Some(i)
} else {
None
}
}) {
if !identifiers.insert(labile_identifier) || !valid_identifier(labile_identifier) {
return false;
}
}
for (id, ambiguous_identifier) in self
.get_n_term()
.iter()
.chain(self.get_c_term())
.chain(self.sequence().iter().flat_map(|s| s.modifications.iter()))
.filter_map(|m| {
if let Modification::Ambiguous { group, id, .. } = m {
Some((id, group))
} else {
None
}
})
{
if ambiguous_mods.insert(id) && !identifiers.insert(ambiguous_identifier)
|| !valid_identifier(ambiguous_identifier)
{
return false;
}
}
if self.name().chars().filter(|c| *c == '(').count()
!= self.name().chars().filter(|c| *c == ')').count()
{
return false;
}
true
}
}
/// Validate all cross links
/// # Errors
/// If there is a cross link with more than 2 locations. Or if there never is a definition for this
/// cross link. Or if there are peptides that cannot be reached from the first peptide.
pub(super) fn cross_links<'a>(
name: String,
peptidoforms: Vec<Peptidoform<Linear>>,
cross_links_found: BTreeMap<usize, Vec<(usize, SequencePosition)>>,
cross_link_lookup: &[(CrossLinkName, Option<SimpleModification>)],
line: &'a str,
) -> ParserResult<'a, PeptidoformIon, BasicKind> {
let mut errors = Vec::new();
let mut peptidoform = PeptidoformIon::new(name, peptidoforms).ok_or_else(|| {
vec![BoxedError::new(
BasicKind::Error,
"Invalid peptidoform ion",
"Not all global modifications and charges are identical, please report this error",
Context::default().line_index(0).lines(0, line),
)]
})?;
for (id, locations) in cross_links_found {
let definition = &cross_link_lookup[id];
if let Some(linker) = &definition.1 {
match locations.len() {
0 => {
combine_error(
&mut errors,
BoxedError::new(
BasicKind::Error,
"Invalid cross-link",
format!(
"The cross-link named '{}' has no listed locations, this is an internal error please report this",
definition.0
),
Context::default().line_index(0).lines(0, line),
),
);
}
1 => {
let (index, position) = locations[0];
if linker
.is_possible(&peptidoform.peptidoforms[index][position], position)
.any_possible()
{
peptidoform.peptidoforms[index]
.add_simple_modification(position, linker.clone());
} else {
let rules = linker.placement_rules();
combine_error(
&mut errors,
BoxedError::new(
BasicKind::Warning,
"Modification not placed to database rules",
format!(
"Modification {linker} is not allowed on {}{}",
match position {
SequencePosition::NTerm => "the N-terminus".to_string(),
SequencePosition::CTerm => "the C-terminus".to_string(),
SequencePosition::Index(seq_index, _) => format!(
"the side chain of {} at index {seq_index}",
peptidoform.peptidoforms[index][position].aminoacid
),
},
if rules.is_empty() {
String::new()
} else {
format!(
", this modification is only allowed at the following locations: {}",
rules.join(", ")
)
}
),
Context::default().line_index(0).lines(0, line),
),
);
}
}
2 => {
if !peptidoform.add_cross_link(
locations[0],
locations[1],
linker.clone(),
definition.0.clone(),
) {
combine_error(
&mut errors,
BoxedError::new(
BasicKind::Warning,
"Cross-link not placed to database rules",
format!(
"The cross-link named '{}' cannot be placed according to its location specificities",
definition.0
),
Context::default().line_index(0).lines(0, line),
),
);
}
}
_ => {
combine_error(
&mut errors,
BoxedError::new(
BasicKind::Error,
"Invalid cross-link",
format!(
"The cross-link named '{}' has more than 2 attachment locations, only cross-links spanning two locations are allowed",
definition.0
),
Context::default().line_index(0).lines(0, line),
),
);
}
}
} else {
let (c, name, description) = if definition.0 == CrossLinkName::Branch {
("MOD", "00134", " N6-glycyl-L-lysine")
} else {
("X", "DSS", "")
};
combine_error(
&mut errors,
BoxedError::new(
BasicKind::Error,
"Invalid cross-link",
format!(
"The cross-link named '{0}' is never defined, for example for {name}{description} define it like: '[{c}:{name}{0}]'",
definition.0
),
Context::default().line_index(0).lines(0, line),
),
);
}
}
// Check if all peptides can be reached from the first one
let mut found_peptides = Vec::new();
let mut stack = vec![0_usize];
while let Some(index) = stack.pop() {
found_peptides.push(index);
for m in peptidoform.peptidoforms[index]
.get_n_term()
.iter()
.chain(peptidoform.peptidoforms[index].get_c_term())
.chain(
peptidoform.peptidoforms[index]
.sequence()
.iter()
.flat_map(|seq| &seq.modifications),
)
{
if let Modification::CrossLink { peptide, .. } = m
&& !found_peptides.contains(peptide)
&& !stack.contains(peptide)
{
stack.push(*peptide);
}
}
}
if found_peptides.len() != peptidoform.peptidoforms().len() {
combine_error(
&mut errors,
BoxedError::new(
BasicKind::Error,
"Unconnected peptidoform",
"Not all peptides in this peptidoform are connected with cross-links or branches, if separate peptides were intended use the chimeric notation `+` instead of the peptidoform notation `//`.",
Context::default().line_index(0).lines(0, line),
),
);
}
if errors.iter().any(|e| e.get_kind().is_error(())) {
Err(errors)
} else {
Ok((peptidoform, errors))
}
}
impl Peptidoform<Linear> {
/// Apply a global modification if this is a global isotope modification with invalid isotopes
/// it returns false
#[must_use]
pub(super) fn apply_global_modifications(
&mut self,
global_modifications: &[GlobalModification],
) -> bool {
for modification in global_modifications {
match modification {
GlobalModification::Fixed(rule, modification) => {
let positions = self
.iter(..)
.filter(|(position, seq)| rule.is_possible(seq, position.sequence_index))
.map(|(position, _)| position)
.collect_vec();
for position in positions {
self.add_simple_modification(position.sequence_index, modification.clone());
}
}
GlobalModification::Isotope(el, isotope) if el.is_valid(*isotope) => {
let _ = self.add_global((*el, *isotope)); // Already validated
}
GlobalModification::Isotope(..) => return false,
}
}
true
}
/// Place all global unknown positions at all possible locations as ambiguous modifications
/// # Errors
/// When a mod cannot be placed anywhere
pub(super) fn apply_unknown_position_modification(
&mut self,
unknown_position_modifications: &[usize],
ambiguous_lookup: &AmbiguousLookup,
) -> Result<(), Vec<BoxedError<'static, BasicKind>>> {
let mut errors = Vec::new();
for modification in unknown_position_modifications {
// Check if this modification was already placed somewhere if so do not add it again
if self.iter(..).any(|(_, s)| {
s.modifications.iter().any(|m| {
if let Modification::Ambiguous { id, .. } = m {
id == modification
} else {
false
}
})
}) {
continue;
}
let entry = &ambiguous_lookup[*modification];
if let Some(m) = &entry.modification {
if !self.add_unknown_position_modification(m.clone(), .., &entry.as_settings()) {
combine_error(
&mut errors,
BoxedError::new(
BasicKind::Error,
"Modification of unknown position cannot be placed",
"There is no position where this modification can be placed based on the placement rules in the database.",
Context::default().lines(
0,
format!(
"Name: {}, Group: {}",
entry.name,
entry.group.map_or_else(
|| "(no group)".to_string(),
|n| n.to_string()
)
),
),
),
);
}
} else {
combine_error(
&mut errors,
BoxedError::new(
BasicKind::Error,
"Modification of unknown position was not defined",
"Please report this error",
Context::default().lines(
0,
format!(
"Name: {}, Group: {}",
entry.name,
entry
.group
.map_or_else(|| "(no group)".to_string(), |n| n.to_string())
),
),
),
);
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
/// Place all ranged unknown positions at all possible locations as ambiguous modifications
/// # Errors
/// When a mod cannot be placed anywhere
/// # Panics
/// It panics when information for an ambiguous modification is missing (name/mod).
pub(super) fn apply_ranged_unknown_position_modification(
&self,
ranged_unknown_position_modifications: &[(
usize,
usize,
usize,
Option<OrderedFloat<f64>>,
)],
ambiguous_lookup: &AmbiguousLookup,
ambiguous_found_positions: &mut Vec<(
SequencePosition,
bool,
usize,
Option<OrderedFloat<f64>>,
)>,
) -> Result<(), Vec<BoxedError<'static, BasicKind>>> {
let mut errors = Vec::new();
for (start, end, id, score) in ranged_unknown_position_modifications {
let Some(entry) = ambiguous_lookup.get(*id) else {
errors.push(BoxedError::new(
BasicKind::Error,
"Modification of unknown position is not defined",
"This ranged modification of unknown position referenced a nonexistent modification, please report this error",
Context::default().lines(0, format!("ID: {id}, range: {start}..={end}")),
));
continue;
};
let Some(modification) = entry.modification.clone() else {
errors.push(BoxedError::new(
BasicKind::Error,
"Modification of unknown position is not defined",
"The ambiguous modification aplied on this range was never defined",
Context::default().lines(0, format!("ID: {id}, range: {start}..={end}")),
));
continue;
};
let possible_positions = self
.iter(start..=end)
.map(|i| dbg!(i))
.filter(|(position, seq)| {
entry.as_settings().position.map_or_else(
|| modification.is_possible(seq, position.sequence_index).any_possible(),
|rules| {
rules.iter().any(|rule| rule.is_possible(seq, position.sequence_index))
},
) && (entry.as_settings().comkp
|| self[position.sequence_index]
.modifications
.iter()
.all(Modification::is_ambiguous))
})
.map(|(position, _)| position.sequence_index)
.collect_vec();
ambiguous_found_positions
.extend(possible_positions.into_iter().map(|pos| (pos, false, *id, *score)));
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
impl<T> Peptidoform<T> {
/// If a modification rule is broken it returns a warning.
pub fn enforce_modification_rules(&self) -> Vec<BoxedError<'static, BasicKind>> {
let mut warnings = Vec::new();
for (position, seq) in self.iter(..) {
combine_errors(
&mut warnings,
seq.enforce_modification_rules(position.sequence_index, &Context::default()),
);
}
warnings
}
/// If a modification rule is broken it returns a warning.
pub(crate) fn enforce_modification_rules_with_context<'a>(
&self,
context: &Context<'a>,
) -> Vec<BoxedError<'a, BasicKind>> {
let mut warnings = Vec::new();
for (position, seq) in self.iter(..) {
combine_errors(
&mut warnings,
seq.enforce_modification_rules(position.sequence_index, context),
);
}
warnings
}
}