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
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
use std::{
    io::{BufRead, Write},
    sync::Arc,
};

use quick_xml::events::{BytesStart, Event};

use crate::{
    error::Breadcrumbs,
    mzml::{
        attributes::AttributeValue,
        cvparam::{CVParam, HasCVParams, HasParamGroupRefs, UserParam},
        referenceableparamgroup::ReferenceableParamGroupRef,
        software::SoftwareRef,
    },
    FatalParseError, ParseError, Tag,
};

use super::{
    attributes::{ID_ATTRIBUTE, LIST_ATTRIBUTES, PROCESSING_METHOD_ATTRIBUTES},
    writer::Writer,
    MzMLReader, MzMLTag,
};

/// Reference to a `DataProcessing`. This is either a String with the ID or (ideally) an `Arc<DataProcessing>` to the exact instance of the `DataProcessing`.
#[derive(Debug)]
pub enum DataProcessingRef {
    /// ID as a String
    Id(String),
    /// Reference to exact instance of `DataProcessing`.
    Ref(Arc<DataProcessing>),
}

impl DataProcessingRef {
    /// Returns the unique identifier for the `DataProcessingRef` referenced
    pub fn id(&self) -> &str {
        match self {
            DataProcessingRef::Id(id) => id,
            DataProcessingRef::Ref(dp_ref) => dp_ref.id(),
        }
    }
}

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

/// Describes the <dataProcessingList> tag. Container for set of `DataProcessing`.
pub struct DataProcessingList {
    // TODO: Currently need this to avoid breaking code with the old list: Vec<DataProcessingList> parameter on MzML struct
    pub(crate) list: Vec<Arc<DataProcessing>>,
}

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

impl MzMLTag for DataProcessingList {
    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().local_name().as_ref() != b"dataProcessingList" {
            Err(FatalParseError::UnexpectedTag(format!(
                "Unexpected event {:?} when processing DataProcessingList",
                start_event,
            )))
        } else {
            let attributes = parser.process_attributes(
                Tag::DataProcessingList,
                &LIST_ATTRIBUTES,
                start_event,
            )?;

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

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

            Ok(Some(DataProcessingList::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)?;

            match next_event {
                Event::Start(start_event) | Event::Empty(start_event) => {
                    match start_event.name().as_ref() {
                        b"dataProcessing" => {
                            if let Some(mut data_processing) =
                                DataProcessing::parse_start_tag(parser, &start_event)?
                            {
                                data_processing.parse_xml(parser, buffer)?;

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

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

        Ok(())
    }

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

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

/// Describes a <dataProcessing> tag. Collection for set of `ProcessingMethod`.
#[derive(Debug)]
pub struct DataProcessing {
    id: String,

    processing_methods: Vec<ProcessingMethod>,
}

impl Clone for DataProcessing {
    fn clone(&self) -> Self {
        Self {
            id: self.id.clone(),
            processing_methods: self.processing_methods.clone(),
        }
    }
}

impl DataProcessing {
    /// Create a new DataProcessing with the specified unique identifier
    pub fn new(id: &str) -> Self {
        DataProcessing {
            id: id.into(),
            processing_methods: Vec::new(),
        }
    }

    /// Returns the unique identifier assigned to the dataProcessing tag
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Returns access to list of `ProcessingMethod`s
    pub fn processing_methods(&self) -> &[ProcessingMethod] {
        &self.processing_methods
    }
}

impl MzMLTag for DataProcessing {
    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().local_name().as_ref() != b"dataProcessing" {
            Err(FatalParseError::UnexpectedTag(format!(
                "Unexpected event {:?} when processing DataProcessing",
                start_event,
            )))
        } else {
            let attributes =
                parser.process_attributes(Tag::DataProcessing, &ID_ATTRIBUTE, start_event)?;

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

            parser
                .breadcrumbs
                .push_back((Tag::DataProcessing, Some(data_processing.id().to_owned())));

            Ok(Some(data_processing))
        }
    }

    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"processingMethod" => {
                            if let Some(mut processing_method) =
                                ProcessingMethod::parse_start_tag(parser, &start_event)?
                            {
                                processing_method.parse_xml(parser, buffer)?;
                                self.processing_methods.push(processing_method);
                            }
                        }
                        _ => 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"dataProcessing" = end_event.name().as_ref() {
                        parser.breadcrumbs.pop_back();

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

        Ok(())
    }

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

    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> Result<(), quick_xml::Error> {
        writer.start_tag_with_attr("dataProcessing", "id", &self.id)?;

        // write each processingMethod
        for processing_method in &self.processing_methods {
            processing_method.write_xml(writer)?;
        }

        writer.end_tag("dataProcessing")
    }
}

/// Describes a <processingMethod> tag.
#[derive(Debug)]
pub struct ProcessingMethod {
    order: u16,
    software_ref: SoftwareRef,

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

impl Clone for ProcessingMethod {
    fn clone(&self) -> Self {
        Self {
            order: self.order,
            software_ref: self.software_ref.clone(),
            param_group_refs: self.param_group_refs.clone(),
            cv_params: self.cv_params.clone(),
            user_params: self.user_params.clone(),
        }
    }
}

impl ProcessingMethod {
    /// Creates a new ProcessingMethod from the order (in which the processing method was applied)
    /// and a reference to the software used to perform the processing.
    pub fn new(order: u16, software_ref: SoftwareRef) -> Self {
        ProcessingMethod {
            order,
            software_ref,
            param_group_refs: Vec::new(),
            cv_params: Vec::new(),
            user_params: Vec::new(),
        }
    }

    /// Return the order (index in the sequence in which this method was applied)
    pub fn order(&self) -> u16 {
        self.order
    }
}

impl MzMLTag for ProcessingMethod {
    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().local_name().as_ref() != b"processingMethod" {
            Err(FatalParseError::UnexpectedTag(format!(
                "Unexpected event {:?} when processing ProcessingMethod",
                start_event,
            )))
        } else {
            let attributes = parser.process_attributes(
                Tag::ProcessingMethod,
                &PROCESSING_METHOD_ATTRIBUTES,
                start_event,
            )?;

            let processing_method = match (attributes.get("order"), attributes.get("softwareRef")) {
                (
                    Some(AttributeValue::Integer(order)),
                    Some(AttributeValue::String(software_ref)),
                ) => {
                    let software_ref_id = parser
                        .parse_string(Tag::ProcessingMethod, software_ref)
                        .unwrap_or("");

                    let software_ref = match parser.software_ref(software_ref_id.as_bytes()) {
                        Some(software_ref) => software_ref,
                        None => {
                            parser.errors.push_back(ParseError::MissingRef {
                                breadcrumbs: Breadcrumbs(parser.breadcrumbs.clone()),
                                tag: Tag::ProcessingMethod,
                                ref_to_tag: Tag::Software,
                                ref_id: software_ref_id.to_string(),
                            });

                            SoftwareRef::Id(software_ref_id.to_string())
                        }
                    };

                    ProcessingMethod::new(*order as u16, software_ref)
                }
                (Some(AttributeValue::Integer(order)), None) => {
                    ProcessingMethod::new(*order as u16, SoftwareRef::Id("".to_string()))
                }
                (None, Some(AttributeValue::String(software_ref))) => {
                    let software_ref = parser
                        .parse_string(Tag::ProcessingMethod, software_ref)
                        .unwrap_or("");
                    let software_ref = parser.software_ref(software_ref.as_bytes()).unwrap();

                    ProcessingMethod::new(0, software_ref)
                }
                _ => ProcessingMethod::new(0, SoftwareRef::Id("".to_string())),
            };

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

            Ok(Some(processing_method))
        }
    }

    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();

            match parser.next(buffer)? {
                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"processingMethod" = end_event.name().as_ref() {
                        parser.breadcrumbs.pop_back();

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

        Ok(())
    }

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

    fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> Result<(), quick_xml::Error> {
        let mut elem = BytesStart::new("processingMethod");
        elem.push_attribute(("order", self.order().to_string().as_str()));
        elem.push_attribute(("softwareRef", self.software_ref.id()));

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

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

        writer.end_tag("processingMethod")
    }
}

//impl<'a> WriteCVParams<'a> for ProcessingMethod<'a> {}

impl HasCVParams for ProcessingMethod {
    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 ProcessingMethod {
    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_data_processing_list(
//         &mut self,
//         e: &BytesStart,
//     ) -> Result<Tag, FatalParseError> {
//         let attributes = self.process_attributes(Tag::DataProcessingList, &LIST_ATTRIBUTES, e);

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

//         Ok(Tag::DataProcessingList)
//     }

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

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

//         self.current_data_processing = Some(data_processing);
//         Ok(Tag::DataProcessing)
//     }

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

//         ParserState::Processing
//     }

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

//         let processing_method = match (attributes.get("order"), attributes.get("softwareRef")) {
//             (Some(AttributeValue::Integer(order)), Some(AttributeValue::String(software_ref))) => {
//                 let software_ref_id = self.parse_string(Tag::ProcessingMethod, software_ref);
//                 let software_ref = match self
//                     .current_mzml
//                     .as_ref()
//                     .unwrap()
//                     .software_ref(software_ref_id)
//                 {
//                     Some(software_ref) => software_ref,
//                     None => {
//                         self.errors.push_back(ParseError::MissingRef {
//                             tag: Tag::ProcessingMethod,
//                             ref_to_tag: Tag::Software,
//                             ref_id: software_ref_id.to_string(),
//                         });

//                         SoftwareRef::Id(software_ref_id.to_string())
//                     }
//                 };

//                 ProcessingMethod::new(*order as u16, software_ref)
//             }
//             (Some(AttributeValue::Integer(order)), None) => {
//                 ProcessingMethod::new(*order as u16, SoftwareRef::Id("".to_string()))
//             }
//             (None, Some(AttributeValue::String(software_ref))) => {
//                 let software_ref = self.parse_string(Tag::ProcessingMethod, software_ref);
//                 let software_ref = self
//                     .current_mzml
//                     .as_ref()
//                     .unwrap()
//                     .software_ref(software_ref)
//                     .unwrap();

//                 ProcessingMethod::new(0, software_ref)
//             }
//             _ => ProcessingMethod::new(0, SoftwareRef::Id("".to_string())),
//         };

//         self.current_processing_method = Some(processing_method);

//         Ok(Tag::ProcessingMethod)
//     }

//     pub(crate) fn end_processing_method(&mut self) -> ParserState {
//         match self.current_data_processing {
//             Some(ref mut current_data_processing) => match self.current_processing_method.take() {
//                 Some(processing_method) => {
//                     current_data_processing
//                         .processing_methods
//                         .push(processing_method);
//                 }
//                 None => self.errors.push_back(ParseError::UnexpectedTag(
//                     "Found </processingMethod> tag before <processingMethod> tag".to_string(),
//                 )),
//             },
//             None => self.errors.push_back(ParseError::UnexpectedTag(
//                 "Trying to add processingMethod tag without first creating dataProcessing"
//                     .to_string(),
//             )),
//         }

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