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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
use std::collections::HashMap;
use std::fmt::Display;
use std::io::SeekFrom;
use std::{io, mem};
use chrono::{DateTime, FixedOffset};
use log::warn;
use quick_xml::events::{BytesEnd, BytesStart, BytesText};
use quick_xml::Error as XMLError;
use thiserror::Error;
use super::reader::Bytes;
use crate::io::traits::SeekRead;
use crate::io::OffsetIndex;
use crate::meta::{
Component, ComponentType, DataProcessing, FileDescription, InstrumentConfiguration, MassSpectrometerFileFormatTerm, NativeSpectrumIdentifierFormatTerm, ProcessingMethod, Sample, ScanSettings, Software, SourceFile
};
use crate::params::{curie_to_num, ControlledVocabulary, Param, ParamCow, Unit};
use crate::prelude::*;
use crate::spectrum::{bindata::ArrayRetrievalError, ArrayType};
pub(crate) fn decode_latin1_escape(value: &[u8]) -> String {
quick_xml::escape::escape(encoding_rs::mem::decode_latin1(value).as_ref()).into()
}
/**
The different states the [`MzMLReaderType`](crate::io::mzml::MzMLReaderType) can enter while parsing
different phases of the document. This information is really only
needed by the module consumer to determine where in the document an
error occurred.
*/
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum MzMLParserState {
Start = 0,
Resume,
// Top-level metadata
CVList,
FileDescription,
FileContents,
SourceFileList,
SourceFile,
ScanSettingsList,
ScanSettings,
SourceFileRefList,
TargetList,
Target,
ReferenceParamGroupList,
ReferenceParamGroup,
Sample,
SampleList,
SoftwareList,
Software,
InstrumentConfigurationList,
InstrumentConfiguration,
ComponentList,
Source,
Analyzer,
Detector,
DataProcessingList,
DataProcessing,
ProcessingMethod,
Run,
// Spectrum and Chromatogram List Elements
Spectrum,
SpectrumList,
BinaryDataArrayList,
BinaryDataArray,
Binary,
ScanList,
Scan,
ScanWindowList,
ScanWindow,
PrecursorList,
Precursor,
IsolationWindow,
SelectedIonList,
SelectedIon,
Activation,
SpectrumDone,
SpectrumListDone,
ChromatogramList,
Chromatogram,
ChromatogramDone,
ChromatogramListDone,
ParserError,
EOF,
}
impl Display for MzMLParserState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{:?}", self))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EntryType {
#[default]
Spectrum,
Chromatogram,
}
/**
All the ways that mzML parsing can go wrong
*/
#[derive(Debug, Error)]
pub enum MzMLParserError {
#[error("An error occurred outside of normal conditions {0}")]
UnknownError(MzMLParserState),
#[error("An incomplete spectrum was parsed")]
IncompleteSpectrum,
#[error("An incomplete element {0} was encountered in {1}")]
IncompleteElementError(String, MzMLParserState),
#[error("An XML error {1} was encountered in {0}")]
XMLError(MzMLParserState, #[source] XMLError),
#[error("An XML error {1} was encountered in {0}: {2}")]
XMLErrorContext(MzMLParserState, #[source] XMLError, String),
#[error("An IO error {1} was encountered in {0}")]
IOError(MzMLParserState, #[source] io::Error),
#[error("The {0} section is over")]
SectionOver(&'static str),
#[error("Failed to decode {1}: {2} for {0}")]
ArrayDecodingError(MzMLParserState, ArrayType, ArrayRetrievalError),
#[error("Reached the end of the file")]
EOF
}
impl From<MzMLParserError> for io::Error {
fn from(value: MzMLParserError) -> Self {
match value {
MzMLParserError::IOError(_, ref e) => io::Error::new(e.kind(), value),
_ => io::Error::new(io::ErrorKind::InvalidData, value),
}
}
}
pub(crate) type ParserResult = Result<MzMLParserState, MzMLParserError>;
/**
Common XML error handling behaviors
*/
pub trait XMLParseBase {
fn handle_xml_error(&self, error: quick_xml::Error, state: MzMLParserState) -> MzMLParserError {
MzMLParserError::XMLError(state, error)
}
}
/**
Common `CVParam` parsing behaviors
*/
pub trait CVParamParse: XMLParseBase {
fn handle_param_borrowed<'inner, 'outer: 'inner + 'event, 'event: 'inner>(
event: &'event BytesStart<'event>,
reader_position: usize,
state: MzMLParserState,
) -> Result<ParamCow<'inner>, MzMLParserError> {
let mut name = None;
let mut value = None;
let mut accession = None;
let mut controlled_vocabulary = None;
let mut unit = Unit::Unknown;
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => match attr.key.as_ref() {
b"name" => {
name = Some(attr.unescape_value().or_else(|_| {
log::debug!("Non-UTF-8 detected in parameter name at {reader_position} in state {state}");
Ok(decode_latin1_escape(&attr.value).into())
}).unwrap_or_else(|e: quick_xml::Error| {
panic!("Error decoding CV param name at {}: {}", reader_position, e)
}));
}
b"value" => {
value = Some(attr.unescape_value().or_else(|_| {
log::debug!("Non-UTF-8 detected in parameter value at {reader_position} in state {state}");
Ok(decode_latin1_escape(&attr.value).into())
}).unwrap_or_else(|e: quick_xml::Error| {
panic!(
"Error decoding CV param value at {}: {}",
reader_position, e
)
}));
}
b"cvRef" => {
let cv_id = attr.unescape_value().unwrap_or_else(|e| {
panic!(
"Error decoding CV param reference at {}: {}",
reader_position, e
)
});
controlled_vocabulary = cv_id
.parse::<ControlledVocabulary>()
.unwrap_or_else(|_| {
panic!("Failed to parse controlled vocabulary ID {}", cv_id)
})
.as_option();
}
b"accession" => {
let v = attr.unescape_value().unwrap_or_else(|e| {
panic!(
"Error decoding CV param accession at {}: {}",
reader_position, e
)
});
let (_, acc) = curie_to_num(&v);
accession = acc;
}
b"unitName" => {
let v = attr.unescape_value().or_else(|_| {
log::debug!("Non-UTF-8 detected in parameter unit name at {reader_position} in state {state}");
Ok(decode_latin1_escape(&attr.value).into())
}).unwrap_or_else(|e: quick_xml::Error| {
panic!(
"Error decoding CV param unit name at {}: {}",
reader_position, e
)
});
unit = Unit::from_name(&v);
}
b"unitAccession" => {
let v = attr.unescape_value().unwrap_or_else(|e| {
panic!(
"Error decoding CV param unit name at {}: {}",
reader_position, e
)
});
unit = Unit::from_accession(&v);
}
b"unitCvRef" => {}
_ => {}
},
Err(msg) => return Err(MzMLParserError::XMLError(state, msg.into())),
}
}
let param = ParamCow::new(
name.unwrap(),
value.unwrap_or_default().into(),
accession,
controlled_vocabulary,
unit,
);
Ok(param)
}
fn handle_param(
event: &BytesStart,
reader_position: usize,
state: MzMLParserState,
) -> Result<Param, MzMLParserError> {
let mut param = Param::new();
let mut unit_name = None;
let mut unit_accession = None;
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => match attr.key.as_ref() {
b"name" => {
param.name = attr
.unescape_value()
.or_else(|_| {
log::debug!("Non-UTF-8 detected in parameter name at {reader_position} in state {state}");
Ok(decode_latin1_escape(&attr.value).into())
})
.unwrap_or_else(|e: quick_xml::Error| {
panic!("Error decoding CV param name at {}: {}", reader_position, e)
})
.to_string();
}
b"value" => {
param.value = attr
.unescape_value()
.or_else(|_| {
log::debug!("Non-UTF-8 detected in parameter value at {reader_position} in state {state}");
Ok(decode_latin1_escape(&attr.value).into())
})
.unwrap_or_else(|e: quick_xml::Error| {
panic!(
"Error decoding CV param value at {}: {}",
reader_position, e
)
})
.into();
}
b"cvRef" => {
let cv_id = attr.unescape_value().unwrap_or_else(|e| {
panic!(
"Error decoding CV param reference at {}: {}",
reader_position, e
)
});
param.controlled_vocabulary = cv_id
.parse::<ControlledVocabulary>()
.unwrap_or_else(|_| {
panic!("Failed to parse controlled vocabulary ID {}", cv_id)
})
.as_option();
}
b"accession" => {
let v = attr.unescape_value().unwrap_or_else(|e| {
panic!(
"Error decoding CV param accession at {}: {}",
reader_position, e
)
});
let (_, acc) = curie_to_num(&v);
param.accession = acc;
}
b"unitName" => {
let v = attr.unescape_value().or_else(|_| {
log::debug!("Non-UTF-8 detected in parameter unit name at {reader_position} in state {state}");
Ok(decode_latin1_escape(&attr.value).into())
}).unwrap_or_else(|e: quick_xml::Error| {
panic!(
"Error decoding CV param unit name at {}: {}",
reader_position, e
)
});
unit_name = Some(Unit::from_name(&v));
}
b"unitAccession" => {
let v = attr.unescape_value().unwrap_or_else(|e| {
panic!(
"Error decoding CV param unit name at {}: {}",
reader_position, e
)
});
unit_accession = Some(Unit::from_accession(&v));
}
b"unitCvRef" => {}
_ => {}
},
Err(msg) => return Err(MzMLParserError::XMLError(state, msg.into())),
}
}
if let Some(unit_acc) = unit_accession {
match unit_acc {
Unit::Unknown => {}
_ => {
param.unit = unit_acc;
}
}
}
if let Some(unit_name) = unit_name {
match unit_name {
Unit::Unknown => {}
_ => {
param.unit = unit_name;
}
}
}
Ok(param)
}
}
/// SAX-style start/end/text/empty event handlers
pub trait MzMLSAX {
fn start_element(&mut self, event: &BytesStart, state: MzMLParserState) -> ParserResult;
fn empty_element(
&mut self,
event: &BytesStart,
state: MzMLParserState,
reader_position: usize,
) -> ParserResult;
fn end_element(&mut self, event: &BytesEnd, state: MzMLParserState) -> ParserResult;
fn text(&mut self, event: &BytesText, state: MzMLParserState) -> ParserResult;
}
/// Errors that can occur while extracting the trailing index of an `indexedmzML` document
#[derive(Debug, Error)]
pub enum MzMLIndexingError {
#[error("Offset index not found")]
OffsetNotFound,
#[error("XML error {0} occurred while reading out mzML index")]
XMLError(
#[from]
#[source]
XMLError,
),
#[error("IO error {0} occurred while reading out mzML index")]
IOError(
#[from]
#[source]
io::Error,
),
}
impl From<MzMLIndexingError> for io::Error {
fn from(value: MzMLIndexingError) -> Self {
match value {
MzMLIndexingError::OffsetNotFound => io::Error::new(io::ErrorKind::InvalidData, value),
MzMLIndexingError::XMLError(e) => match &e {
XMLError::Io(e) => io::Error::new(e.kind(), e.clone()),
_ => io::Error::new(io::ErrorKind::InvalidData, e),
},
MzMLIndexingError::IOError(e) => e,
}
}
}
#[derive(Debug, Default, Clone)]
pub struct IndexedMzMLIndexExtractor {
pub spectrum_index: OffsetIndex,
pub chromatogram_index: OffsetIndex,
pub state: IndexParserState,
last_id: String,
}
#[derive(Debug, Clone, Copy, Default)]
pub enum IndexParserState {
#[default]
Start,
SeekingOffset,
SpectrumIndexList,
ChromatogramIndexList,
Done,
}
impl Display for IndexParserState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{:?}", self))
}
}
impl XMLParseBase for IndexedMzMLIndexExtractor {}
impl IndexedMzMLIndexExtractor {
pub fn new() -> IndexedMzMLIndexExtractor {
IndexedMzMLIndexExtractor {
spectrum_index: OffsetIndex::new("spectrum".into()),
chromatogram_index: OffsetIndex::new("chromatogram".into()),
last_id: String::new(),
..Default::default()
}
}
pub fn find_offset_from_reader<R: SeekRead>(
&mut self,
reader: &mut R,
) -> Result<Option<u64>, MzMLIndexingError> {
self.state = IndexParserState::SeekingOffset;
reader.seek(SeekFrom::End(-200))?;
let mut buf = Bytes::new();
reader.read_to_end(&mut buf)?;
let pattern = regex::Regex::new("<indexListOffset>(\\d+)</indexListOffset>").unwrap();
if let Some(captures) = pattern.captures(&String::from_utf8_lossy(&buf)) {
if let Some(offset) = captures.get(1) {
if let Ok(offset) = offset.as_str().parse::<u64>() {
return Ok(Some(offset));
}
}
}
Ok(None)
}
pub fn start_element(
&mut self,
event: &BytesStart,
state: IndexParserState,
) -> Result<IndexParserState, MzMLIndexingError> {
let elt_name = event.name();
match elt_name.as_ref() {
b"offset" => {
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"idRef" {
self.last_id = attr
.unescape_value()
.map(|v| v.to_string())
.or_else(|_| -> Result<String, quick_xml::Error> {
log::trace!("Detected non-UTF8 character in idRef");
Ok(decode_latin1_escape(&attr.value))
})
.unwrap_or_else(|e| {
panic!("Error decoding idRef on offset {e} from bytes {:?}", attr.value)
});
}
}
Err(err) => {
return Err(MzMLIndexingError::XMLError(err.into()));
}
}
}
}
b"index" => {
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"name" {
let index_name = attr
.unescape_value()
.expect("Error decoding idRef")
.to_string();
match index_name.as_ref() {
"spectrum" => {
self.state = IndexParserState::SpectrumIndexList;
return Ok(IndexParserState::SpectrumIndexList);
}
"chromatogram" => {
self.state = IndexParserState::ChromatogramIndexList;
return Ok(IndexParserState::ChromatogramIndexList);
}
_ => {}
}
}
}
Err(err) => {
return Err(MzMLIndexingError::XMLError(err.into()));
}
}
}
}
b"indexList" => {}
_ => {}
}
Ok(state)
}
pub fn end_element(
&mut self,
event: &BytesEnd,
state: IndexParserState,
) -> Result<IndexParserState, MzMLIndexingError> {
let elt_name = event.name();
match elt_name.as_ref() {
b"offset" => {}
b"index" => {}
b"indexList" => return Ok(IndexParserState::Done),
_ => {}
}
Ok(state)
}
pub fn text(
&mut self,
event: &BytesText,
state: IndexParserState,
) -> Result<IndexParserState, XMLError> {
match state {
IndexParserState::SpectrumIndexList => {
let bin = event
.unescape()
.expect("Failed to unescape spectrum offset");
if let Ok(offset) = bin.parse::<u64>() {
if !self.last_id.is_empty() {
let key = mem::take(&mut self.last_id);
self.spectrum_index.insert(key, offset);
} else {
warn!("Out of order text in index")
}
}
}
IndexParserState::ChromatogramIndexList => {
let bin = event
.unescape()
.expect("Failed to unescape chromatogram offset");
if let Ok(offset) = bin.parse::<u64>() {
if !self.last_id.is_empty() {
let key = mem::take(&mut self.last_id);
self.chromatogram_index.insert(key, offset);
} else {
warn!("Out of order text in index")
}
}
}
_ => {}
}
Ok(state)
}
}
/**A SAX-style parser for building up the metadata section prior to the `<run>` element
of an mzML file.*/
#[derive(Debug, Default)]
pub struct FileMetadataBuilder<'a> {
pub file_description: FileDescription,
pub instrument_configurations: Vec<InstrumentConfiguration>,
pub softwares: Vec<Software>,
pub samples: Vec<Sample>,
pub scan_settings: Vec<ScanSettings>,
pub data_processings: Vec<DataProcessing>,
pub reference_param_groups: HashMap<String, Vec<Param>>,
pub last_group: String,
pub(crate) instrument_id_map: Option<&'a mut IncrementingIdMap>,
// Run attributes
pub run_id: Option<String>,
pub default_instrument_config: Option<u32>,
pub default_source_file: Option<String>,
pub start_timestamp: Option<DateTime<FixedOffset>>,
// SpectrumList attributes
pub num_spectra: Option<u64>,
pub default_data_processing: Option<String>,
}
impl XMLParseBase for FileMetadataBuilder<'_> {}
impl CVParamParse for FileMetadataBuilder<'_> {}
impl FileMetadataBuilder<'_> {
pub fn start_element(&mut self, event: &BytesStart, state: MzMLParserState) -> ParserResult {
let elt_name = event.name();
match elt_name.as_ref() {
b"fileDescription" => return Ok(MzMLParserState::FileDescription),
b"fileContent" => return Ok(MzMLParserState::FileContents),
b"sourceFileList" => return Ok(MzMLParserState::SourceFileList),
b"sourceFile" => {
let mut source_file = SourceFile::default();
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"id" {
source_file.id = attr
.unescape_value()
.expect("Error decoding id")
.to_string();
} else if attr.key.as_ref() == b"name" {
source_file.name = attr
.unescape_value()
.expect("Error decoding name")
.to_string();
} else if attr.key.as_ref() == b"location" {
source_file.location = attr
.unescape_value()
.expect("Error decoding location")
.to_string();
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.file_description.source_files.push(source_file);
return Ok(MzMLParserState::SourceFile);
}
b"softwareList" => return Ok(MzMLParserState::SoftwareList),
b"software" => {
let mut software = Software::default();
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"id" {
software.id = attr
.unescape_value()
.expect("Error decoding id")
.to_string();
} else if attr.key.as_ref() == b"version" {
software.version = attr
.unescape_value()
.expect("Error decoding version")
.to_string();
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.softwares.push(software);
return Ok(MzMLParserState::Software);
}
b"referenceableParamGroupList" => {
return Ok(MzMLParserState::ReferenceParamGroupList);
}
b"referenceableParamGroup" => {
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"id" {
let key = attr
.unescape_value()
.expect("Error decoding id")
.to_string();
self.reference_param_groups.entry(key.clone()).or_default();
self.last_group = key;
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
return Ok(MzMLParserState::ReferenceParamGroup);
}
b"instrumentConfigurationList" => {
return Ok(MzMLParserState::InstrumentConfigurationList)
}
b"instrumentConfiguration" => {
let mut ic = InstrumentConfiguration::default();
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"id" {
ic.id = self
.instrument_id_map
.as_mut()
.expect("An instrument ID map was not provided")
.get(
attr.unescape_value().expect("Error decoding id").as_ref(),
);
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.instrument_configurations.push(ic);
return Ok(MzMLParserState::InstrumentConfiguration);
}
b"componentList" => return Ok(MzMLParserState::ComponentList),
b"source" => {
let mut source = Component {
component_type: ComponentType::IonSource,
..Default::default()
};
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"order" {
source.order = attr
.unescape_value()
.expect("Error decoding order")
.parse()
.expect("Failed to parse integer from `order`");
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.instrument_configurations
.last_mut()
.unwrap()
.components
.push(source);
return Ok(MzMLParserState::Source);
}
b"analyzer" => {
let mut analyzer = Component {
component_type: ComponentType::Analyzer,
..Default::default()
};
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"order" {
analyzer.order = attr
.unescape_value()
.expect("Error decoding order")
.parse()
.expect("Failed to parse integer from `order`");
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.instrument_configurations
.last_mut()
.unwrap()
.components
.push(analyzer);
return Ok(MzMLParserState::Analyzer);
}
b"detector" => {
let mut detector = Component {
component_type: ComponentType::Detector,
..Default::default()
};
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"order" {
detector.order = attr
.unescape_value()
.expect("Error decoding order")
.parse()
.expect("Failed to parse integer from `order`");
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.instrument_configurations
.last_mut()
.unwrap()
.components
.push(detector);
return Ok(MzMLParserState::Detector);
}
b"sampleList" => return Ok(MzMLParserState::SampleList),
b"sample" => {
let mut sample = Sample::default();
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"id" {
sample.id = attr
.unescape_value()
.expect("Error decoding id")
.to_string();
} else if attr.key.as_ref() == b"name" {
sample.name = Some(
attr.unescape_value()
.expect("Error decoding name")
.to_string(),
);
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.samples.push(sample);
return Ok(MzMLParserState::Sample);
}
b"dataProcessingList" => return Ok(MzMLParserState::DataProcessingList),
b"dataProcessing" => {
let mut dp = DataProcessing::default();
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"id" {
dp.id = attr
.unescape_value()
.expect("Error decoding id")
.to_string();
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.data_processings.push(dp);
return Ok(MzMLParserState::DataProcessing);
}
b"processingMethod" => {
let mut method = ProcessingMethod::default();
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"order" {
method.order = attr
.unescape_value()
.expect("Error decoding order")
.parse()
.expect("Failed to parse order");
} else if attr.key.as_ref() == b"softwareRef" {
method.software_reference = attr
.unescape_value()
.expect("Error decoding softwareRef")
.to_string();
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.data_processings
.last_mut()
.unwrap()
.methods
.push(method);
return Ok(MzMLParserState::ProcessingMethod);
}
b"run" => {
for attr in event.attributes().flatten() {
match attr.key.as_ref() {
b"id" => {
self.run_id = Some(
attr.unescape_value()
.expect("Error decoding run ID")
.to_string(),
);
}
b"defaultInstrumentConfigurationRef" => {
let value = attr
.unescape_value()
.expect("Error decoding default instrument configuration ID");
self.default_instrument_config =
self.instrument_id_map.as_mut().map(|m| m.get(&value));
}
b"defaultSourceFileRef" => {
self.default_source_file = Some(
attr.unescape_value()
.expect("Error decoding default source file reference")
.to_string(),
);
}
b"startTimeStamp" => {
let val = attr
.unescape_value()
.expect("Error decoding start timestamp");
let val = DateTime::parse_from_rfc3339(&val).inspect_err(
|&e| {
log::error!("Expected a dateTime value conforming to ISO 8601 standard: {e}");
}
).ok();
self.start_timestamp = val;
}
_ => {}
}
}
return Ok(MzMLParserState::Run);
}
b"spectrumList" => {
for attr in event.attributes().flatten() {
match attr.key.as_ref() {
b"count" => {
self.num_spectra = attr.unescape_value()
.expect("Error decoding spectrum list size")
.parse()
.map_err(|e| {
log::error!("Error parsing spectrum list size: {e}");
e
}).ok();
}
b"defaultDataProcessingRef" => {
let value = attr
.unescape_value()
.expect("Error decoding default instrument configuration ID");
self.default_data_processing = Some(value.to_string())
}
_ => {}
}
}
return Ok(MzMLParserState::SpectrumList);
}
b"scanSettingsList" => {
return Ok(MzMLParserState::ScanSettingsList)
}
b"scanSettings" => {
let mut settings = ScanSettings::default();
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"id" {
settings.id = attr
.unescape_value()
.expect("Error decoding id")
.to_string();
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
self.scan_settings.push(settings);
return Ok(MzMLParserState::ScanSettings)
}
b"sourceFileRefList" => {
return Ok(MzMLParserState::SourceFileRefList)
}
b"targetList" => {
return Ok(MzMLParserState::TargetList)
}
b"target" => {
self.scan_settings.last_mut().unwrap().targets.push(Default::default());
return Ok(MzMLParserState::Target)
}
_ => {}
}
Ok(state)
}
pub fn fill_param_into(&mut self, param: Param, state: MzMLParserState) {
match state {
MzMLParserState::SourceFile => {
let sf = self.file_description.source_files.last_mut().unwrap();
if let Some(curie) = param.curie() {
if NativeSpectrumIdentifierFormatTerm::from_curie(&curie).is_some() {
sf.id_format = Some(param);
} else if MassSpectrometerFileFormatTerm::from_curie(&curie).is_some() {
sf.file_format = Some(param);
} else {
sf.add_param(param)
}
} else {
sf.add_param(param)
}
}
MzMLParserState::Sample => {
let sample = self.samples.last_mut().unwrap();
sample.add_param(param)
}
MzMLParserState::FileContents => {
self.file_description.add_param(param);
}
MzMLParserState::InstrumentConfiguration => {
self.instrument_configurations
.last_mut()
.unwrap()
.add_param(param);
}
MzMLParserState::Software => self.softwares.last_mut().unwrap().add_param(param),
MzMLParserState::ProcessingMethod => self
.data_processings
.last_mut()
.unwrap()
.methods
.last_mut()
.unwrap()
.add_param(param),
MzMLParserState::Detector | MzMLParserState::Analyzer | MzMLParserState::Source => self
.instrument_configurations
.last_mut()
.unwrap()
.components
.last_mut()
.unwrap()
.add_param(param),
MzMLParserState::ReferenceParamGroup => {
self.reference_param_groups
.get_mut(&self.last_group)
.unwrap()
.push(param);
}
MzMLParserState::ScanSettings => {
self.scan_settings.last_mut().unwrap().add_param(param);
}
MzMLParserState::Target => {
self.scan_settings.last_mut().unwrap().targets.last_mut().unwrap().add_param(param);
}
_ => {}
}
}
pub fn empty_element(
&mut self,
event: &BytesStart,
state: MzMLParserState,
reader_position: usize,
) -> ParserResult {
let elt_name = event.name();
match elt_name.as_ref() {
b"cvParam" | b"userParam" => match Self::handle_param(event, reader_position, state) {
Ok(param) => {
self.fill_param_into(param, state);
return Ok(state);
}
Err(err) => return Err(err),
},
b"softwareRef" => {
if state == MzMLParserState::InstrumentConfiguration {
let ic = self.instrument_configurations.last_mut().unwrap();
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"ref" {
ic.software_reference = attr
.unescape_value()
.expect("Error decoding software reference")
.to_string();
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
}
}
b"referenceableParamGroupRef" => {
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"ref" {
let group_id = attr
.unescape_value()
.expect("Error decoding reference group")
.to_string();
let param_group = match self.reference_param_groups.get(&group_id) {
Some(params) => params.clone(),
None => {
panic!("Encountered a referenceableParamGroupRef without a group definition")
}
};
for param in param_group {
self.fill_param_into(param, state)
}
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
}
b"sourceFileRef" => {
if state == MzMLParserState::SourceFileRefList {
let settings = self.scan_settings.last_mut().unwrap();
for attr_parsed in event.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"ref" {
settings.source_file_refs.push(attr
.unescape_value()
.expect("Error decoding software reference")
.to_string());
}
}
Err(msg) => {
return Err(self.handle_xml_error(msg.into(), state));
}
}
}
}
}
&_ => {}
}
Ok(state)
}
pub fn end_element(&mut self, event: &BytesEnd, state: MzMLParserState) -> ParserResult {
let elt_name = event.name();
match elt_name.as_ref() {
b"fileDescription" => return Ok(MzMLParserState::FileDescription),
b"fileContent" => return Ok(MzMLParserState::FileDescription),
b"sourceFile" => return Ok(MzMLParserState::SourceFileList),
b"softwareList" => return Ok(MzMLParserState::SoftwareList),
b"software" => return Ok(MzMLParserState::SoftwareList),
b"sample" => return Ok(MzMLParserState::SampleList),
b"sampleList" => return Ok(MzMLParserState::SampleList),
b"referenceableParamGroupList" => {
return Ok(MzMLParserState::ReferenceParamGroupList);
}
b"instrumentConfigurationList" => {
return Ok(MzMLParserState::InstrumentConfigurationList)
}
b"instrumentConfiguration" => return Ok(MzMLParserState::InstrumentConfigurationList),
b"componentList" => return Ok(MzMLParserState::InstrumentConfiguration),
b"source" => return Ok(MzMLParserState::ComponentList),
b"analyzer" => return Ok(MzMLParserState::ComponentList),
b"detector" => return Ok(MzMLParserState::ComponentList),
b"dataProcessingList" => return Ok(MzMLParserState::DataProcessingList),
b"dataProcessing" => return Ok(MzMLParserState::DataProcessingList),
b"processingMethod" => return Ok(MzMLParserState::DataProcessing),
b"scanSettings" => return Ok(MzMLParserState::ScanSettingsList),
b"scanSettingsList" => return Ok(MzMLParserState::ScanSettingsList),
b"targetList" => return Ok(MzMLParserState::ScanSettings),
b"sourceFileRefList" => return Ok(MzMLParserState::ScanSettings),
b"target" => return Ok(MzMLParserState::TargetList),
b"run" => {
// TODO
}
_ => {}
}
Ok(state)
}
pub fn text(&mut self, _event: &BytesText, state: MzMLParserState) -> ParserResult {
Ok(state)
}
}
/// A mapping from [`String`] to [`u32`] that automatically increments when
/// a new key is provided. A relatively safe means of maintaining an internally
/// consistent mapping from a textual source ID to an in-memory numeric ID.
#[derive(Debug, Default, Clone)]
pub struct IncrementingIdMap {
id_map: HashMap<String, u32>,
next_id: u32,
}
impl IncrementingIdMap {
/// Get the numeric ID for a textual ID, automatically issuing a new
/// numeric ID when a new textual ID is provided.
pub fn get(&mut self, key: &str) -> u32 {
if let Some(value) = self.id_map.get(key) {
*value
} else {
let value = self.next_id;
self.id_map.insert(key.to_string(), self.next_id);
self.next_id += 1;
value
}
}
}
/// Builds an offset index to each `<spectrum>` XML element by doing a fast pre-scan
/// of an mzML or imzML file. This is a shared utility function used by both
/// [`MzMLReaderType`](crate::io::mzml::MzMLReaderType) and
/// [`ImzMLReaderType`](crate::io::imzml::ImzMLReaderType).
///
/// # Arguments
/// * `handle` - A seekable buffered reader positioned at any point in the file
/// * `spectrum_index` - The offset index to populate with spectrum ID -> byte offset mappings
/// * `buffer` - A reusable buffer for XML parsing
///
/// # Returns
/// The byte offset where indexing stopped (usually at the end of `<spectrumList>`)
pub fn build_spectrum_index<R: SeekRead>(
handle: &mut io::BufReader<R>,
spectrum_index: &mut OffsetIndex,
buffer: &mut Bytes,
) -> u64 {
use quick_xml::{events::Event, Reader};
use log::trace;
let start = handle
.stream_position()
.expect("Failed to save restore location");
trace!("Starting to build offset index by traversing the file, storing last position as {start}");
handle.seek(SeekFrom::Start(0))
.expect("Failed to reset stream to beginning");
let mut reader = Reader::from_reader(&mut *handle);
reader.trim_text(true);
loop {
match reader.read_event_into(buffer) {
Ok(Event::Start(ref e)) => {
let element_name = e.name();
if element_name.as_ref() == b"spectrum" {
// Hit a spectrum, extract ID and save current offset
for attr_parsed in e.attributes() {
match attr_parsed {
Ok(attr) => {
if attr.key.as_ref() == b"id" {
let scan_id = attr
.unescape_value()
.expect("Error decoding spectrum id in streaming index")
.to_string();
// This count is off by 2 because somehow the < and > bytes are removed?
spectrum_index.insert(
scan_id,
(reader.buffer_position() - e.len() - 2) as u64,
);
break;
};
}
Err(_msg) => {}
}
}
}
}
Ok(Event::End(ref e)) => {
let element_name = e.name();
if element_name.as_ref() == b"spectrumList" {
break;
}
}
Ok(Event::Eof) => {
break;
}
_ => {}
};
buffer.clear();
}
let offset = reader.buffer_position() as u64;
trace!("Ended indexing scan at offset {offset}. Restoring starting position {start}");
handle
.seek(SeekFrom::Start(start))
.expect("Failed to restore location");
spectrum_index.init = true;
if spectrum_index.is_empty() {
warn!("An index was built but no entries were found")
}
offset
}