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
use crate::error::Breadcrumbs;
use crate::mzml::attributes::{AttributeValue, ID_ATTRIBUTE, LIST_ATTRIBUTES};
use crate::mzml::cvparam::UserParam;
use crate::{FatalParseError, ParseError, Tag};

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

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

use std::borrow::Borrow;

/// Represents a <referenceableParamGroupRef> tag.
#[derive(Debug)]
pub enum ReferenceableParamGroupRef {
    /// Reference by unique identifier (likely missing <referenceableParamGroup> when parsing)
    Id(String),
    /// Reference to `ReferenceableParamGroup`
    Ref(Arc<ReferenceableParamGroup>),
}

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

impl AsRef<ReferenceableParamGroup> for ReferenceableParamGroupRef {
    fn as_ref(&self) -> &ReferenceableParamGroup {
        match self {
            ReferenceableParamGroupRef::Ref(param_group) => param_group.as_ref(),
            ReferenceableParamGroupRef::Id(id) => {
                panic!("Can't dereference an ID based param group: {}", id)
            }
        }
    }
}

impl ReferenceableParamGroupRef {
    /// Parse the starting tag for <referenceableParamGroupRef>
    pub fn parse_start_tag<B: BufRead>(
        parser: &mut MzMLReader<B>,
        start_event: &BytesStart,
    ) -> Result<Self, FatalParseError>
    where
        Self: std::marker::Sized,
    {
        if start_event.name().as_ref() != b"referenceableParamGroupRef" {
            // TODO: Return error
            panic!(
                "Unexpected event {:?} when processing ReferenceableParamGroupRef",
                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.borrow()) {
                        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.referenceable_param_group_ref(value.as_bytes()) {
                Some(reference) => Ok(reference),
                None => {
                    parser.errors.push_back(ParseError::MissingRef {
                        breadcrumbs: Breadcrumbs(parser.breadcrumbs.clone()),
                        tag: *parser.last_tag(),
                        ref_to_tag: Tag::RefParamGroup,
                        ref_id: value.to_string(),
                    });

                    Ok(ReferenceableParamGroupRef::Id(value))
                }
            },
            None => todo!(),
        }

        //let attributes =
        //    parser.process_attributes(Tag::RefParamGroupRef, &REF_ATTRIBUTE, start_event);

        // match attributes.get("ref") {
        //     Some(AttributeValue::String(reference)) => {
        //         match parser.referenceable_param_group_ref(reference) {
        //             Some(reference) => Ok(reference),
        //             None => Ok(ReferenceableParamGroupRef::Id(
        //                 parser.encoding.decode(reference).0.to_string(),
        //             )),
        //         }
        //     }
        //     _ => todo!(),
        // }
    }
}

/// Represents a list of <referenceableParamGroup> tags.
pub struct ReferenceableParamGroupList {
    // TODO: Currently need this to avoid breaking code with the old list: Vec<ReferenceableParamGroup> parameter on MzML struct
    pub(crate) list: Vec<Arc<ReferenceableParamGroup>>,
}

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

impl MzMLTag for ReferenceableParamGroupList {
    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"referenceableParamGroupList" {
            return Err(FatalParseError::UnexpectedTag(format!(
                "Unexpected event {:?} when processing ReferenceableParamGroupList",
                start_event,
            )));
        }

        let attributes =
            parser.process_attributes(Tag::RefParamGroupList, &LIST_ATTRIBUTES, start_event)?;

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

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

        Ok(Some(ReferenceableParamGroupList::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"referenceableParamGroup" => {
                            if let Some(mut param_group) =
                                ReferenceableParamGroup::parse_start_tag(parser, &start_event)?
                            {
                                param_group.parse_xml(parser, buffer)?;

                                self.list.push(Arc::new(param_group));
                            }
                        }
                        _ => 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"referenceableParamGroupList" = end_event.name().as_ref() {
                        parser.breadcrumbs.pop_back();

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

        Ok(())
    }

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

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

/// Represents a <referenceableParamGroup> tag.
#[derive(Debug)]
pub struct ReferenceableParamGroup {
    id: String,

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

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

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

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

    /// Returns the unique identifier for this `ReferenceableParamGroup`
    pub fn id(&self) -> &str {
        &self.id
    }
}

impl MzMLTag for ReferenceableParamGroup {
    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"referenceableParamGroup" {
            return Err(FatalParseError::UnexpectedTag(format!(
                "Unexpected event {:?} when processing ReferenceableParamGroup",
                start_event,
            )));
        }

        let attributes =
            parser.process_attributes(Tag::RefParamGroup, &ID_ATTRIBUTE, start_event)?;

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

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

        Ok(Some(ReferenceableParamGroup::new(id)))
    }

    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) => {
                    // cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
                    // userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead

                    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"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"referenceableParamGroup" = end_event.name().as_ref() {
                        parser.breadcrumbs.pop_back();

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

        Ok(())
    }

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

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

        self.write_params_xml(writer)?;

        writer.end_tag("referenceableParamGroup")
    }
}

//impl<'a> WriteCVParams<'a> for ReferenceableParamGroup<'a> {}
impl HasCVParams for ReferenceableParamGroup {
    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_cv_params(self)
    // }
}

/*impl HasCVParams for ReferenceableParamGroup {


    fn add_param_group_ref(&mut self, param_group_ref: ReferenceableParamGroupRef) {
        self.param_group_refs.push(param_group_ref);
    }
}*/

// impl<'a> ImzMLParser<'a> {
//     pub(super) fn start_referenceable_param_group_list(
//         &mut self,
//         e: &BytesStart,
//     ) -> Result<Tag, FatalParseError> {
//         for att in e.attributes().with_checks(self.with_attribute_checks) {
//             match att {
//                 Ok(attribute) => match attribute.key {
//                     b"count" => match parse_usize(attribute) {
//                         Ok(value) => {
//                             self.current_mzml
//                                 .as_mut()
//                                 .unwrap()
//                                 .referenceable_param_group_list
//                                 .reserve(value);
//                         }
//                         Err(error) => {
//                             self.errors
//                                 .push_back(ParseError::IntError((Tag::RefParamGroupList, error)));
//                         }
//                     },
//                     _ => self.errors.push_back(ParseError::UnexpectedAttribute((
//                         Tag::RefParamGroupList,
//                         std::str::from_utf8(attribute.key).unwrap().to_string(),
//                     ))),
//                 },
//                 Err(error) => {
//                     self.errors
//                         .push_back(ParseError::XMLError((Tag::RefParamGroupList, error)));
//                 }
//             };
//         }

//         Ok(Tag::RefParamGroupList)
//     }

//     pub(super) fn start_referenceable_param_group(
//         &mut self,
//         e: &BytesStart,
//     ) -> Result<Tag, FatalParseError> {
//         for attribute in e.attributes().with_checks(self.with_attribute_checks) {
//             match attribute {
//                 Ok(attribute) => match attribute.key {
//                     b"id" => match std::str::from_utf8(attribute.value.borrow()) {
//                         Ok(value) => {
//                             self.current_referenceable_param_group =
//                                 Some(ReferenceableParamGroup::new(value));
//                         }
//                         Err(error) => {
//                             self.errors
//                                 .push_back(ParseError::Utf8Error((Tag::RefParamGroup, error)));
//                         }
//                     },
//                     _ => self.errors.push_back(ParseError::UnexpectedAttribute((
//                         Tag::RefParamGroup,
//                         std::str::from_utf8(attribute.key).unwrap().to_string(),
//                     ))),
//                 },
//                 Err(error) => {
//                     self.errors
//                         .push_back(ParseError::XMLError((Tag::RefParamGroup, error)));
//                 }
//             };
//         }

//         Ok(Tag::RefParamGroup)
//     }

//     pub(super) fn end_referenceable_param_group(&mut self) -> ParserState {
//         match self.current_referenceable_param_group.take() {
//             Some(ref_param_group) => {
//                 self.current_mzml
//                     .as_mut()
//                     .unwrap()
//                     .referenceable_param_group_list
//                     .push(ref_param_group.into());
//             }
//             None => {
//                 self.errors.push_back(ParseError::UnexpectedTag(
//                     "Found end tag for ReferenceableParamGroup before opening".to_string(),
//                 ));
//             }
//         };

//         ParserState::Processing
//     }

//     pub(super) fn start_referenceable_param_group_ref(
//         &mut self,
//         e: &BytesStart,
//     ) -> Result<Tag, FatalParseError> {
//         let mut value: Option<String> = None;

//         for attribute in e.attributes().with_checks(self.with_attribute_checks) {
//             match attribute {
//                 Ok(attribute) => match attribute.key {
//                     b"ref" => match std::str::from_utf8(attribute.value.borrow()) {
//                         Ok(v) => {
//                             value = Some(v.to_owned());
//                         }
//                         Err(error) => {
//                             self.errors
//                                 .push_back(ParseError::Utf8Error((Tag::RefParamGroupRef, error)));
//                         }
//                     },
//                     _ => self.errors.push_back(ParseError::UnexpectedAttribute((
//                         Tag::RefParamGroupRef,
//                         std::str::from_utf8(attribute.key).unwrap().to_string(),
//                     ))),
//                 },
//                 Err(error) => {
//                     self.errors
//                         .push_back(ParseError::XMLError((Tag::RefParamGroupRef, error)));
//                 }
//             }
//         }

//         match value {
//             Some(value) => {
//                 let param_group_ref = match self
//                     .current_mzml
//                     .as_ref()
//                     .unwrap()
//                     .referenceable_param_group_ref(&value)
//                 {
//                     Some(param_group_ref) => param_group_ref,
//                     None => ReferenceableParamGroupRef::Id(value),
//                 };

//                 if let Some(tag) = self.breadcrumb.back() {
//                     match tag {
//                         Tag::Spectrum => self
//                             .current_spectrum
//                             .as_mut()
//                             .unwrap()
//                             .add_param_group_ref(param_group_ref),
//                         Tag::BinaryDataArray => self
//                             .current_binary_data_array
//                             .as_mut()
//                             .unwrap()
//                             .add_param_group_ref(param_group_ref),
//                         Tag::Scan => self
//                             .current_scan
//                             .as_mut()
//                             .unwrap()
//                             .add_param_group_ref(param_group_ref),
//                         _ => {
//                             self.errors.push_back(ParseError::UnexpectedParent((
//                                 Tag::RefParamGroupRef,
//                                 *tag,
//                             )));
//                         }
//                     }
//                 } else {
//                     panic!(
//                         "Invalid parser state: trying to add referenceable param group to {:?}",
//                         self.breadcrumb
//                     );
//                 }
//             }
//             None => {
//                 self.errors.push_back(ParseError::MissingAttribute((
//                     Tag::RefParamGroupRef,
//                     "ref".to_string(),
//                 )));
//             }
//         }

//         Ok(Tag::RefParamGroupRef)
//     }
// }