imzml 0.1.3

A library for reading the mass spectrometry (imaging) formats mzML and imzML.
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
use std::{
    collections::VecDeque,
    fmt::Display,
    num::ParseIntError,
    str::Utf8Error,
    sync::{MutexGuard, PoisonError},
};

use base64::DecodeError;
use serde::{ser::SerializeStruct, Serialize, Serializer};

use crate::{
    mzml::{attributes::AttributeType, Tag},
    obo::ValueType,
};

/// Possible errors occuring during the parsing of an (i)mzML file, which do not prevent further parsing
#[derive(Debug)]
pub enum ParseError {
    /// Error occured when processing an integer at the current `Tag`
    IntError((Tag, ParseIntError)),
    /// Error occured when parsing UTF8 (typically String values)
    Utf8Error((Tag, Utf8Error)),
    /// General XML error occured when parsing the file (`quick_xml::Error`)
    XMLError((Tag, quick_xml::Error)),
    /// A attribute was included on the `Tag` that was not expected (not in the specification)
    UnexpectedAttribute((Tag, String)),
    /// A attribute was not included on the `Tag` that was expected (listed as required in the specification)
    MissingAttribute((Tag, String)),
    /// The value of an attribute is missing (i.e. <tag attribute="">) where one is expected
    MissingAttributeValue((Tag, String, AttributeType)),
    /// A XML tag was encountered that was not expected (not in the specification)
    UnexpectedTag(String),
    /// Reference in the specified `Tag` cannot be found in the (i)mzML document
    MissingRef {
        /// Location within the file
        breadcrumbs: Breadcrumbs,
        /// Tag which contains the 'ref' attribute
        tag: Tag,
        /// Tag being referenced
        ref_to_tag: Tag,
        /// The missing ID in the 'ref' attribute
        ref_id: String,
    },
    /// Value in CV param missing, but required
    MissingValue((Breadcrumbs, String, ValueType)),
    /// Value in CV param present, but shouldn't have one
    UnexpectedValue((Breadcrumbs, String, String)),
    /// Invalid value type present in CV param (cannot convert value present to the expected value type)
    InvalidValue((Breadcrumbs, String, String)),

    /// Unknown accession included as cvParam (not present in the specified ontology)
    UnknownAccession((Breadcrumbs, String)),
    // //Text(String),
    // //Unknown,

    // From old parser
    //UnimplementedTag(String),
    //UnexpectedParent((Tag, Tag)),
}

impl ParseError {
    /// Returns a description of the error
    pub fn description(&self) -> String {
        match self {
            ParseError::IntError((tag, int_error)) => {
                format!("Couldn't convert integer at tag {}: {}", tag, int_error)
            }
            ParseError::Utf8Error(_) => todo!(),
            ParseError::XMLError(_) => todo!(),
            ParseError::UnexpectedAttribute((tag, string)) => {
                format!("{} tag has an unexpected attribute {}", tag, string)
            }
            ParseError::MissingAttribute((tag, string)) => {
                format!("{} tag is missing required attribute. {}", tag, string)
            }
            ParseError::MissingAttributeValue((tag, attribute, attribute_type)) => {
                format!(
                    "{} tag is missing value  of type {:?} for attribute {}",
                    tag, attribute_type, attribute
                )
            }
            ParseError::UnexpectedTag(string) => {
                format!("Unexpected tag: {}", string)
            }
            ParseError::MissingRef {
                breadcrumbs: _breadcrumbs,
                tag,
                ref_to_tag,
                ref_id,
            } => {
                format!(
                    "Tag {} includes a reference to a {} tag with id {}, but this doesn't exist",
                    tag, ref_to_tag, ref_id
                )
            }
            ParseError::MissingValue((_breadcrumbs, data, value_type)) => {
                format!(
                    " Missing value of type {:?} for cvParam {}",
                    value_type, data
                )
            }
            ParseError::InvalidValue((_breadcrumbs, data, value)) => {
                format!("Found an invalid value ({}) for cvParam {}", value, data)
            }
            ParseError::UnexpectedValue((_breadcrumbs, data, value)) => {
                format!(
                    "Found a value ({}) when one wasn't expected for cvParam {}",
                    value, data
                )
            }
            ParseError::UnknownAccession((_breadcrumbs, accession)) => {
                format!(
                    "Found an accession (cvParam) ({}) that was not present in the ontology",
                    accession
                )
            }
        }
    }
}

impl Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::IntError(_) => {
                write!(f, "{}", self.description())
            }
            ParseError::Utf8Error(_) => {
                write!(f, "{}", self.description())
            },
            ParseError::XMLError(_) => {
                write!(f, "{}", self.description())
            },
            ParseError::UnexpectedAttribute(_) => {
                write!(f, "{}", self.description())
            }
            ParseError::MissingAttribute(_) => {
                write!(f, "{}", self.description())
            }
            ParseError::MissingAttributeValue(_) => {
                write!(f, "{}", self.description())
            }
            ParseError::UnexpectedTag(_) => {
                write!(f, "{}", self.description())
            }
            ParseError::MissingRef {
                breadcrumbs,
                tag: _,
                ref_to_tag: _,
                ref_id: _,
            } => {
                write!(
                    f,
                    "[{}] {}",
                    breadcrumbs, self.description()
                )
            }
            ParseError::MissingValue((breadcrumbs, _data, _value_type)) => {
                write!(
                    f,
                    "[{}] {}",
                    breadcrumbs, self.description()
                )
            }
            ParseError::InvalidValue((breadcrumbs, _data, _value)) => {
                write!(
                    f,
                    "[{}] {}",
                    breadcrumbs, self.description()
                )
            }
            ParseError::UnexpectedValue((breadcrumbs, _data, _value)) => {
                write!(
                    f,
                    "[{}] {}",
                    breadcrumbs, self.description()
                )
            }
            ParseError::UnknownAccession((breadcrumbs, _accession)) => {
                write!(
                    f,
                    "[{}] {}",
                    breadcrumbs, self.description()
                )
            }

            // From old parser
            //ParseError::UnimplementedTag(_) => todo!(),
            //ParseError::UnexpectedParent(_) => todo!(),
        }
    }
}

impl Serialize for ParseError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("parse_error", 2)?;

        match self {
            ParseError::IntError((tag, _error)) => {
                state.serialize_field("type", "IntError")?;
                state.serialize_field("tag", tag)?;
                state.serialize_field("description", &self.description())?;
            }
            ParseError::Utf8Error((tag, _error)) => {
                state.serialize_field("type", "Utf8Error")?;
                state.serialize_field("tag", tag)?;
                state.serialize_field("description", &self.description())?;
            }
            ParseError::XMLError((tag, _error)) => {
                state.serialize_field("type", "XMLError")?;
                state.serialize_field("tag", tag)?;
                state.serialize_field("description", &self.description())?;
            }
            ParseError::UnexpectedAttribute((tag, _error)) => {
                state.serialize_field("type", "UnexpectedAttribute")?;
                state.serialize_field("tag", tag)?;
                state.serialize_field("description", &self.description())?;
            }
            ParseError::MissingAttribute((tag, _error)) => {
                state.serialize_field("type", "MissingAttribute")?;
                state.serialize_field("tag", tag)?;
                state.serialize_field("description", &self.description())?;
            }
            ParseError::MissingAttributeValue((tag, _attribute, _attribute_value)) => {
                state.serialize_field("type", "MissingAttributeValue")?;
                state.serialize_field("tag", tag)?;
                state.serialize_field("description", &self.description())?;
            }
            ParseError::UnexpectedTag(_) => {
                state.serialize_field("type", "UnexpectedTag")?;
                state.serialize_field("description", &self.description())?;
            }
            ParseError::MissingRef {
                breadcrumbs,
                tag,
                ref_to_tag,
                ref_id,
            } => {
                state.serialize_field("type", "MissingRef")?;
                state.serialize_field("tag", tag)?;
                state.serialize_field("description", &self.description())?;
                state.serialize_field("location", &format!("{}", breadcrumbs))?;
                state.serialize_field("ref_to_tag", ref_to_tag)?;
                state.serialize_field("ref_id", ref_id)?;
            }
            ParseError::MissingValue((breadcrumbs, _details, value_type)) => {
                state.serialize_field("type", "MissingValue")?;
                state.serialize_field("description", &self.description())?;
                state.serialize_field("location", &format!("{}", breadcrumbs))?;
                state.serialize_field("expected_value_type", value_type)?;
            }
            ParseError::UnexpectedValue((breadcrumbs, _, _)) => {
                state.serialize_field("type", "UnexpectedValue")?;
                state.serialize_field("description", &self.description())?;
                state.serialize_field("location", &format!("{}", breadcrumbs))?;
            }
            ParseError::InvalidValue((breadcrumbs, _, _)) => {
                state.serialize_field("type", "InvalidValue")?;
                state.serialize_field("description", &self.description())?;
                state.serialize_field("location", &format!("{}", breadcrumbs))?;
            }
            ParseError::UnknownAccession((breadcrumbs, _)) => {
                state.serialize_field("type", "UnknownAccession")?;
                state.serialize_field("description", &self.description())?;
                state.serialize_field("location", &format!("{}", breadcrumbs))?;
            }
        }

        state.end()
    }
}

/// Keep track of tag hierarchy to aid in error reporting.
#[derive(Debug, Clone)]
pub struct Breadcrumbs(pub VecDeque<(Tag, Option<String>)>);

impl std::fmt::Display for Breadcrumbs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (index, (tag, id)) in self.0.iter().enumerate() {
            if index > 0 {
                write!(f, ">")?;
            }

            write!(f, "{}", tag)?;

            if let Some(id) = id {
                write!(f, "[{}]", id)?;
            }
        }

        Ok(())
    }
}

/// Possible errors occuring during the parsing of an (i)mzML file, which prevent further parsing
#[non_exhaustive]
#[derive(Debug)]
pub enum FatalParseError {
    /// I/O error when interacting with the file
    IOError(std::io::Error),
    /// Issue with the validity of the XML causing parsing to cease
    XMLError(quick_xml::Error),
    /// Expected a different tag, so unable to proceed
    UnexpectedTag(String),
    //UnimplementedTag(String),
    /// Tag is not imlpemented correctly (e.g. missing attributes)
    InvalidTag((Tag, String)),
    /// An expected opening tag is missing
    MissingOpeningTag(String),
    /// An expected closing tag is missing
    MissingClosingTag(String),
    /// an unexpected error has occured
    UnexpectedError(String),
    /// Invalid UTF-8 found when trying to convert [u8] to UTF8
    InvalidUtf8(Utf8Error),
    /// An unexpected XML event has been encountered
    UnexpectedEvent(String),
}

impl Serialize for FatalParseError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("fatal_error", 2)?;

        match self {
            FatalParseError::IOError(error) => {
                state.serialize_field("type", "IOError")?;
                state.serialize_field("details", &format!("{}", error))?;
            }
            FatalParseError::XMLError(error) => {
                state.serialize_field("type", "XMLError")?;
                state.serialize_field("details", &format!("{}", error))?;
            }
            FatalParseError::UnexpectedTag(error) => {
                state.serialize_field("type", "UnexpectedTag")?;
                state.serialize_field("details", error)?;
            }
            FatalParseError::MissingOpeningTag(error) => {
                state.serialize_field("type", "MissingOpeningTag")?;
                state.serialize_field("details", error)?;
            }
            FatalParseError::MissingClosingTag(error) => {
                state.serialize_field("type", "MissingOpeningTag")?;
                state.serialize_field("details", error)?;
            }
            FatalParseError::UnexpectedError(error) => {
                state.serialize_field("type", "UnexpectedError")?;
                state.serialize_field("details", error)?;
            }
            FatalParseError::UnexpectedEvent(error) => {
                state.serialize_field("type", "UnexpectedEvent")?;
                state.serialize_field("details", error)?;
            }
            FatalParseError::InvalidUtf8(error) => {
                state.serialize_field("type", "InvalidUtf8")?;
                state.serialize_field("details", &format!("{:?}", error))?;
            }
            FatalParseError::InvalidTag((tag, error)) => {
                state.serialize_field("type", "InvalidTag")?;
                state.serialize_field("tag", &format!("{}", tag))?;
                state.serialize_field("details", error)?;
            }
        }

        state.end()
    }
}

impl From<std::io::Error> for FatalParseError {
    fn from(error: std::io::Error) -> Self {
        FatalParseError::IOError(error)
    }
}

impl From<Utf8Error> for FatalParseError {
    fn from(error: Utf8Error) -> Self {
        FatalParseError::InvalidUtf8(error)
    }
}

impl From<quick_xml::Error> for FatalParseError {
    fn from(error: quick_xml::Error) -> Self {
        FatalParseError::XMLError(error)
    }
}

/// Error occured when accessing and/or decoding data
#[derive(Debug)]
pub enum DataError {
    /// Mutex was poisoned and so cannot continue
    MutexError,
    /// I/O error occured when interacting with the file
    IOError(std::io::Error),
    /// Base64 encoding is invalid
    Base64DecodeError(DecodeError),
    /// Unknown or unsupported data type specified in the metadata, not sure how to proceed
    UnknownDataType,
}

impl<'a, D> From<PoisonError<MutexGuard<'a, D>>> for DataError {
    fn from(_poison_error: PoisonError<MutexGuard<'a, D>>) -> Self {
        Self::MutexError
    }
}

impl From<std::io::Error> for DataError {
    fn from(io_error: std::io::Error) -> Self {
        Self::IOError(io_error)
    }
}

impl From<DecodeError> for DataError {
    fn from(decode_error: DecodeError) -> Self {
        Self::Base64DecodeError(decode_error)
    }
}