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
//! Code to handle the RESID ontology
use std::io::Read;
use context_error::{BoxedError, CreateError};
use mzcv::{CVError, CVFile, CVSource, CVVersion, HashBufReader};
use roxmltree::*;
use crate::{
chemistry::{MolecularFormula, MultiChemical},
ontology::{
Ontology,
ontology_modification::{ModData, OntologyModification},
},
sequence::{
AminoAcid, LinkerSpecificity, PlacementRule, Position, SimpleModification,
SimpleModificationInner,
},
};
/// RESID modifications
///
/// Note that because RESID is stored on a ftp server the automatic downloading does not work.
#[allow(missing_copy_implementations, missing_debug_implementations)]
pub struct Resid {}
impl CVSource for Resid {
type Data = SimpleModificationInner;
type Structure = Vec<SimpleModification>;
fn cv_name() -> &'static str {
"RESID"
}
fn files() -> &'static [CVFile] {
&[CVFile {
name: "RESID",
extension: "xml",
url: None, //FTP is not supported but for when it is: ftp://ftp.proteininformationresource.org/pir_databases/other_databases/resid/RESIDUES.XML
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/resid.dat"),
Configuration::default(),
)
.unwrap()
.0;
Some(cache)
}
#[cfg(feature = "internal-no-data")]
None
}
fn parse(
mut reader: impl Iterator<Item = HashBufReader<Box<dyn Read>, impl sha2::Digest>>,
) -> Result<(CVVersion, Self::Structure), Vec<BoxedError<'static, CVError>>> {
let mut reader = reader.next().unwrap();
let mut buf = String::new();
reader.read_to_string(&mut buf).map_err(|e| {
vec![BoxedError::small(
CVError::FileCouldNotBeOpenend,
"Could not read file",
e.to_string(),
)]
})?;
let document = Document::parse_with_options(
&buf,
ParsingOptions {
allow_dtd: true,
..Default::default()
},
)
.expect("Invalid xml in RESID xml");
let mut modifications: Vec<SimpleModification> = Vec::new();
let database = document
.root()
.first_child()
.expect("No Database node in RESID XML");
'entry: for entry in database.children() {
if entry.has_tag_name("Entry") {
let mut modification = OntologyModification::default();
let mut corrections = Vec::new();
let mut rules = Vec::new();
modification.ontology = Ontology::Resid;
modification.id = entry.attribute("id").unwrap()[2..].parse().unwrap();
for data_block in entry.children() {
match data_block.tag_name().name() {
"Names" => {
for name_node in data_block.children() {
match name_node.tag_name().name() {
"Name" => {
modification.name =
name_node.text().unwrap_or_default().into();
}
"AlternateName" | "SystematicName" => {
modification.synonyms.push((
mzcv::SynonymScope::Exact,
name_node.text().unwrap_or_default().into(),
))
}
"Xref" => {
if let Some((a, b)) =
name_node.text().unwrap_or_default().split_once(':')
{
modification.cross_ids.push((Some(a.into()), b.into()));
} else {
panic!("Invalid Xref content")
}
}
tag if tag.trim().is_empty() => (),
tag => panic!("RESID: Invalid Name tag: {tag} {name_node:?}"),
}
}
}
"FormulaBlock" => {
for formula_node in data_block.children() {
if formula_node.has_tag_name("Formula") {
modification.formula = MolecularFormula::resid(
formula_node.text().unwrap_or_default(),
)
.unwrap()
.to_vec()
.pop()
.unwrap(); // TODO: handle Multi cases, only used for B and Z (potentially just use those?)
}
}
}
"CorrectionBlock" => {
for formula_node in data_block.children() {
if formula_node.has_tag_name("Formula") {
corrections.push((
formula_node.attribute("uids"),
formula_node.attribute("link"),
formula_node.attribute("label"),
MolecularFormula::resid_single(
formula_node.text().unwrap_or_default(),
)
.unwrap(),
));
}
}
} // Fixes on specific aas? or mods
"ReferenceBlock" => {
for ref_node in data_block.children() {
if ref_node.has_tag_name("Xref") {
if let Some((a, b)) =
ref_node.text().unwrap_or_default().split_once(':')
{
modification.cross_ids.push((Some(a.into()), b.into()));
} else {
panic!("Invalid Xref content")
}
}
}
}
"Comment" => {
modification.description = format!(
"{}{}",
modification.description,
data_block.text().unwrap_or_default()
)
.into_boxed_str();
}
"SequenceCode" => {
let mut rule =
(AminoAcid::Alanine, None, None, data_block.attribute("link"));
for rule_node in data_block.children() {
match rule_node.tag_name().name() {
"SequenceSpec" => {
let txt = rule_node.text().unwrap_or_default();
if let Some((a, b)) = txt.split_once(", ") {
if b.contains(',') {
println!(
"RESID: Ignore SequenceSpec '{txt}' for {}",
modification.id
);
continue 'entry; // Ignore any cross-link > 2
}
rule.0 = AminoAcid::try_from(a.trim())
.unwrap_or_else(|()| panic!("Invalid AA: {a}"));
rule.1 = Some(
AminoAcid::try_from(b.trim())
.unwrap_or_else(|()| panic!("Invalid AA: {b}")),
);
} else {
rule.0 = AminoAcid::try_from(txt.trim())
.unwrap_or_else(|()| panic!("Invalid AA: {txt}"));
}
}
"Condition" => match rule_node.text().unwrap_or_default() {
"amino-terminal" => rule.2 = Some(Position::AnyNTerm),
"carboxyl-terminal" => rule.2 = Some(Position::AnyCTerm),
"carboxamidine" => (),
text if text.starts_with("cross-link")
|| text.starts_with("incidental")
|| text.starts_with("secondary") => {} // Ignore
pos => panic!("Invalid condition position: {pos}"),
},
"Xref" => {
if let Some((a, b)) =
rule_node.text().unwrap_or_default().split_once(':')
{
modification.cross_ids.push((Some(a.into()), b.into()));
} else {
panic!("Invalid Xref content")
}
}
_ => (),
}
}
rules.push(rule);
} // Placement rules
_ => (),
}
}
let mut shared_formula = None;
let mut data = None;
for rule in rules {
if rule.0 == AminoAcid::AmbiguousAsparagine
|| rule.0 == AminoAcid::AmbiguousGlutamine
{
println!("RESID: B or Z used as target {}", modification.id);
continue 'entry;
}
let diff_formula = modification.formula.clone()
- rule.0.single_formula().expect("B or Z used as target")
- rule
.1
.map(|a| a.single_formula().expect("B or Z used as target"))
.unwrap_or_default();
if shared_formula.is_some_and(|s| s != diff_formula) {
println!(
"RESID: Detected multiple diff formulas for {}",
modification.id
);
continue 'entry;
}
shared_formula = Some(diff_formula);
if data.is_none() {
if rule.1.is_none() {
data = Some(ModData::Mod {
specificities: Vec::new(),
});
} else {
data = Some(ModData::Linker {
length: None,
specificities: Vec::new(),
});
}
}
if let (Some(ModData::Linker { specificities, .. }), Some(aa)) =
(&mut data, rule.1)
{
if rule.0 == aa {
specificities.push(LinkerSpecificity::Symmetric {
rules: vec![PlacementRule::AminoAcid(
vec![rule.0].into(),
rule.2.unwrap_or(Position::Anywhere),
)],
stubs: Vec::new(),
neutral_losses: Vec::new(),
diagnostic: Vec::new(),
});
} else {
specificities.push(LinkerSpecificity::Asymmetric {
rules: (
vec![PlacementRule::AminoAcid(
vec![rule.0].into(),
rule.2.unwrap_or(Position::Anywhere),
)],
vec![PlacementRule::AminoAcid(
vec![aa].into(),
rule.2.unwrap_or(Position::Anywhere),
)],
),
stubs: Vec::new(),
neutral_losses: Vec::new(),
diagnostic: Vec::new(),
});
}
} else if let (Some(ModData::Mod { specificities }), None) = (&mut data, rule.1)
{
specificities.push((
vec![PlacementRule::AminoAcid(
vec![rule.0].into(),
rule.2.unwrap_or(Position::Anywhere),
)],
Vec::new(),
Vec::new(),
));
} else {
println!(
"RESID: Modification is both cross-linker and normal modification {}",
modification.id
);
continue 'entry;
}
}
modification.data = data.unwrap_or_default();
modifications.push(modification.into());
}
}
Ok((
CVVersion {
last_updated: database.attribute("date").map(|date| {
let mut res = date.split('-');
let day = res.next().and_then(|d| d.parse::<u8>().ok()).unwrap();
let month = res
.next()
.and_then(|m| {
let lower = m.to_ascii_lowercase();
[
"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep",
"oct", "nov", "dec",
]
.iter()
.position(|n| *n == lower)
})
.and_then(|p| u8::try_from(p).ok())
.unwrap();
let year = res.next().and_then(|d| d.parse::<u16>().ok()).unwrap();
(year, month, day, 0, 0)
}),
version: database.attribute("release").map(ToString::to_string),
hash: reader.hash().to_vec(),
},
modifications,
))
}
}