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
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
//extern crate wasm_bindgen;

use std::sync::Arc;

use super::cvparam::{CVParam, HasCVParams, HasParamGroupRefs};
use super::writer::Writer;
use super::{MzMLReader, MzMLTag};

use quick_xml::events::{BytesStart, Event};
use std::io::{BufRead, Write};

use crate::mzml::attributes::{AttributeValue, LIST_ATTRIBUTES, SOFTWARE_ATTRIBUTES};
use crate::mzml::cvparam::UserParam;
use crate::{FatalParseError, ParseError, Tag};

use super::referenceableparamgroup::ReferenceableParamGroupRef;

pub struct SoftwareList {
    // TODO: Currently need this to avoid breaking code with the old bda_list: Vec<SoftwareList> parameter on MzML struct
    pub(crate) list: Vec<Arc<Software>>,
}

impl SoftwareList {
    fn new(count: usize) -> Self {
        SoftwareList {
            list: Vec::with_capacity(count),
        }
    }
}

impl MzMLTag for SoftwareList {
    fn parse_start_tag<B: BufRead>(
        parser: &mut MzMLReader<B>,
        start_event: &BytesStart,
    ) -> Result<Option<Self>, FatalParseError>
    where
        Self: std::marker::Sized,
    {
        if start_event.name().as_ref() != b"softwareList" {
            return Err(FatalParseError::UnexpectedTag(format!(
                "Unexpected event {:?} when processing SoftwareList",
                start_event,
            )));
        }

        let attributes = parser.process_attributes(Self::tag(), &LIST_ATTRIBUTES, start_event)?;

        let count = match attributes.get("count") {
            Some(&AttributeValue::Integer(count)) => count as usize,
            _ => 0,
        };

        parser.breadcrumbs.push_back((Tag::SoftwareList, None));

        Ok(Some(SoftwareList::new(count)))
    }

    fn parse_xml<B: BufRead>(
        &mut self,
        parser: &mut MzMLReader<B>,
        buffer: &mut Vec<u8>,
    ) -> Result<(), FatalParseError> {
        // Check what comes next
        loop {
            // Clear the buffer ready for the next tag
            buffer.clear();

            let next_event = parser.next(buffer)?;
            let is_empty = matches!(next_event, Event::Empty(_));

            match next_event {
                Event::Start(start_event) | Event::Empty(start_event) => {
                    match start_event.name().as_ref() {
                        b"software" => {
                            if let Some(mut software) =
                                Software::parse_start_tag(parser, &start_event)?
                            {
                                // If there are no cvParam entries in the software, then don't need to parse xml
                                if !is_empty {
                                    software.parse_xml(parser, buffer)?;
                                }

                                self.list.push(Arc::new(software));
                            }
                        }
                        _ => parser.errors.push_back(ParseError::UnexpectedTag(format!(
                            "{:?} unexpected when processing {:?}",
                            std::str::from_utf8(start_event.name().as_ref()),
                            Self::tag()
                        ))),
                    }
                }
                Event::End(end_event) => {
                    if let b"softwareList" = end_event.name().as_ref() {
                        parser.breadcrumbs.pop_back();

                        break;
                    }
                }
                Event::Eof => {
                    return Err(FatalParseError::MissingClosingTag(
                        "softwareList".to_string(),
                    ));
                }
                _ => {}
            }
        }

        Ok(())
    }

    fn tag() -> Tag {
        Tag::SoftwareList
    }

    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> Result<(), quick_xml::Error> {
        writer.write_arc_list("softwareList", &self.list)
    }
}

#[derive(Debug)]
pub enum SoftwareRef {
    Id(String),
    Ref(Arc<Software>),
}

impl Clone for SoftwareRef {
    fn clone(&self) -> Self {
        match self {
            Self::Id(arg0) => Self::Id(arg0.clone()),
            Self::Ref(arg0) => Self::Ref(arg0.clone()),
        }
    }
}

impl MzMLTag for SoftwareRef {
    fn tag() -> Tag {
        Tag::SoftwareRef
    }

    fn parse_start_tag<B: BufRead>(
        parser: &mut MzMLReader<B>,
        start_event: &BytesStart,
    ) -> Result<Option<Self>, FatalParseError>
    where
        Self: std::marker::Sized,
    {
        if start_event.name().as_ref() != b"softwareRef" {
            // TODO: Return error
            panic!(
                "Unexpected event {:?} when processing SoftwareRef",
                start_event
            );
        }

        let mut value: Option<String> = None;

        for attribute in start_event
            .attributes()
            .with_checks(parser.with_attribute_checks)
        {
            match attribute {
                Ok(attribute) => match attribute.key.as_ref() {
                    b"ref" => match std::str::from_utf8(&attribute.value) {
                        Ok(v) => {
                            value = Some(v.to_owned());
                        }
                        Err(error) => {
                            parser
                                .errors
                                .push_back(ParseError::Utf8Error((Tag::RefParamGroupRef, error)));
                        }
                    },
                    _ => parser.errors.push_back(ParseError::UnexpectedAttribute((
                        Tag::RefParamGroupRef,
                        std::str::from_utf8(attribute.key.as_ref())?.to_string(),
                    ))),
                },
                Err(error) => {
                    parser
                        .errors
                        .push_back(ParseError::XMLError((Tag::RefParamGroupRef, error.into())));
                }
            }
        }

        match value {
            Some(value) => match parser.software_ref(value.as_bytes()) {
                Some(reference) => Ok(Some(reference)),
                None => Ok(Some(SoftwareRef::Id(value))),
            },
            None => todo!(),
        }
    }

    fn parse_xml<B: BufRead>(
        &mut self,
        _parser: &mut MzMLReader<B>,
        _buffer: &mut Vec<u8>,
    ) -> Result<(), FatalParseError> {
        Ok(())
    }

    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> Result<(), quick_xml::Error> {
        writer.empty_tag_with_attr("softwareRef", "ref", self.id())
    }
}

impl SoftwareRef {
    pub fn id(&self) -> &str {
        match self {
            SoftwareRef::Id(id) => id,
            SoftwareRef::Ref(software) => software.id(),
        }
    }
}

// impl SoftwareRef {
//     pub fn parse_start_tag<B: BufRead>(
//         parser: &mut MzMLReader<B>,
//         start_event: &BytesStart,
//     ) -> Result<Self, FatalParseError>
//     where
//         Self: std::marker::Sized,
//     {

//     }
// }

#[derive(Debug)]
pub struct Software {
    id: Arc<str>,
    version: String,

    param_group_refs: Vec<ReferenceableParamGroupRef>,
    cv_params: Vec<CVParam>,
    user_params: Vec<UserParam>,
}

impl Clone for Software {
    fn clone(&self) -> Self {
        Self {
            id: self.id.clone(),
            version: self.version.clone(),
            param_group_refs: self.param_group_refs.clone(),
            cv_params: self.cv_params.clone(),
            user_params: self.user_params.clone(),
        }
    }
}

impl Software {
    pub fn new(id: &str, version: &str) -> Self {
        Software {
            id: id.into(),
            version: version.into(),

            param_group_refs: Vec::new(),
            cv_params: Vec::new(),
            user_params: Vec::new(),
        }
    }

    pub fn id(&self) -> &str {
        &self.id
    }
}

impl MzMLTag for Software {
    fn parse_start_tag<B: BufRead>(
        parser: &mut MzMLReader<B>,
        start_event: &BytesStart,
    ) -> Result<Option<Self>, FatalParseError>
    where
        Self: std::marker::Sized,
    {
        if start_event.name().as_ref() != b"software" {
            return Err(FatalParseError::UnexpectedTag(format!(
                "Unexpected event {:?} when processing Software",
                start_event,
            )));
        }

        let attributes =
            parser.process_attributes(Tag::Sample, &SOFTWARE_ATTRIBUTES, start_event)?;

        let software = match (attributes.get("id"), attributes.get("version")) {
            (Some(AttributeValue::String(id)), Some(AttributeValue::String(version))) => {
                Software::new(
                    parser.parse_string(Tag::Software, id).unwrap_or(""),
                    parser.parse_string(Tag::Software, version).unwrap_or(""),
                )
            }
            (Some(AttributeValue::String(id)), None) => {
                Software::new(parser.parse_string(Tag::Software, id).unwrap_or(""), "")
            }
            (None, Some(AttributeValue::String(version))) => Software::new(
                "",
                parser.parse_string(Tag::Software, version).unwrap_or(""),
            ),
            _ => Software::new("", ""),
        };

        parser
            .breadcrumbs
            .push_back((Tag::Software, Some(software.id().to_owned())));

        Ok(Some(software))
    }

    fn parse_xml<B: BufRead>(
        &mut self,
        parser: &mut MzMLReader<B>,
        buffer: &mut Vec<u8>,
    ) -> Result<(), FatalParseError> {
        // Check what comes next
        loop {
            // Clear the buffer ready for the next tag
            buffer.clear();

            let next_event = parser.next(buffer)?;

            match next_event {
                Event::Start(start_event) | Event::Empty(start_event) => match start_event
                    .name()
                    .as_ref()
                {
                    b"cvParam" => {
                        if let Some(cv_param) = CVParam::parse_start_tag(parser, &start_event)? {
                            self.cv_params.push(cv_param);
                        }
                    }
                    b"referenceableParamGroupRef" => {
                        let param_group_ref =
                            ReferenceableParamGroupRef::parse_start_tag(parser, &start_event)?;
                        self.param_group_refs.push(param_group_ref);
                    }
                    b"userParam" => {
                        if let Some(user_param) = UserParam::parse_start_tag(parser, &start_event)?
                        {
                            self.user_params.push(user_param);
                        }
                    }
                    _ => parser.errors.push_back(ParseError::UnexpectedTag(format!(
                        "{:?} unexpected when processing {:?}",
                        std::str::from_utf8(start_event.name().as_ref()),
                        Self::tag()
                    ))),
                },
                Event::End(end_event) => {
                    if let b"software" = end_event.name().as_ref() {
                        parser.breadcrumbs.pop_back();

                        break;
                    }
                }
                Event::Eof => {
                    return Err(FatalParseError::MissingClosingTag("software".to_string()));
                }
                _ => {}
            }
        }

        Ok(())
    }

    fn tag() -> Tag {
        Tag::Software
    }

    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> Result<(), quick_xml::Error> {
        let mut elem = BytesStart::new("software");
        elem.push_attribute(("id", self.id.as_ref()));
        elem.push_attribute(("version", self.version.as_ref()));

        writer.write_event(Event::Start(elem))?;

        self.write_ref_param_groups_xml(writer)?;
        self.write_params_xml(writer)?;

        writer.end_tag("software")
    }
}

//impl<'a> WriteCVParams<'a> for Software<'a> {}
impl HasCVParams for Software {
    fn add_cv_param(&mut self, param: CVParam) {
        self.cv_params.push(param);
    }

    fn cv_params(&self) -> &Vec<CVParam> {
        &self.cv_params
    }

    fn cv_params_mut(&mut self) -> &mut Vec<CVParam> {
        self.cv_params.as_mut()
    }

    fn add_user_param(&mut self, param: UserParam) {
        self.user_params.push(param);
    }

    fn user_params(&self) -> &Vec<UserParam> {
        &self.user_params
    }

    // fn cv_param_iter(&self) -> CVParamIterator {
    //     CVParamIterator::from_has_param_group(self)
    // }
}

impl HasParamGroupRefs for Software {
    fn add_param_group_ref(&mut self, param_group_ref: ReferenceableParamGroupRef) {
        self.param_group_refs.push(param_group_ref);
    }

    fn param_group_refs(&self) -> &Vec<ReferenceableParamGroupRef> {
        &self.param_group_refs
    }
}

// impl<'a> ImzMLParser<'a> {
//     pub(super) fn start_software_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
//         let attributes = self.process_attributes(Tag::SoftwareList, &LIST_ATTRIBUTES, e);

//         if let Some(&AttributeValue::Integer(count)) = attributes.get("count") {
//             self.current_mzml
//                 .as_mut()
//                 .unwrap()
//                 .software_list
//                 .reserve(count as usize);
//         }

//         Ok(Tag::SoftwareList)
//     }

//     pub(super) fn start_software(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
//         let attributes = self.process_attributes(Tag::Sample, &SOFTWARE_ATTRIBUTES, e);

//         let software = match (attributes.get("id"), attributes.get("version")) {
//             (Some(AttributeValue::String(id)), Some(AttributeValue::String(version))) => {
//                 Software::new(
//                     self.parse_string(Tag::Software, id),
//                     self.parse_string(Tag::Software, version),
//                 )
//             }
//             (Some(AttributeValue::String(id)), None) => {
//                 Software::new(self.parse_string(Tag::Software, id), "")
//             }
//             (None, Some(AttributeValue::String(version))) => {
//                 Software::new("", self.parse_string(Tag::Software, version))
//             }
//             _ => Software::new("", ""),
//         };

//         self.current_software = Some(software);

//         Ok(Tag::Software)
//     }

//     pub(crate) fn end_software(&mut self) -> ParserState {
//         match self.current_software.take() {
//             Some(software) => {
//                 self.current_mzml
//                     .as_mut()
//                     .unwrap()
//                     .software_list
//                     .push(software.into());
//             }
//             None => self.errors.push_back(ParseError::UnexpectedTag(
//                 "Found </software> tag before <software> tag".to_string(),
//             )),
//         }

//         ParserState::Processing
//     }
// }