Skip to main content

emit_sample_mzml/
emit_sample_mzml.rs

1//! Emit a small synthetic mzML document (plain and indexed) from the
2//! canonical writer, for schema-conformance checking in CI.
3//!
4//! Usage:
5//!   emit_sample_mzml [PLAIN_OUT] [INDEXED_OUT]
6//!
7//! Defaults to `sample_plain.mzML` and `sample_indexed.mzML` in the
8//! current directory. The output is validated against the vendored
9//! PSI-MS mzML XSD by the `validate-mzml` CI job.
10
11use std::fs::File;
12use std::io::BufWriter;
13
14use openmassspec_core::{
15    write_indexed_mzml, write_mzml, Activation, Analyzer, ChromatogramRecord, CvTerm,
16    MobilityArrayKind, MsPower, Polarity, PrecursorInfo, RunMetadata, ScanMode, SpectrumRecord,
17    SpectrumSource,
18};
19
20struct SampleSource {
21    meta: RunMetadata,
22    spectra: Vec<SpectrumRecord>,
23    chroms: Vec<ChromatogramRecord>,
24    cursor: usize,
25}
26
27impl SampleSource {
28    fn new() -> Self {
29        let meta = RunMetadata {
30            source_file_name: "sample.raw".into(),
31            source_file_format: CvTerm::new("MS:1000563", "Thermo RAW format"),
32            native_id_format: CvTerm::new("MS:1000768", "Thermo nativeID format"),
33            instrument: CvTerm::new("MS:1001911", "Q Exactive"),
34            software_name: "openmassspec-core-sample".into(),
35            software_version: env!("CARGO_PKG_VERSION").into(),
36            // Exercises the `startTimeStamp` attribute path so it is
37            // schema-checked without a vendor file.
38            start_timestamp: Some("2026-06-01T14:30:00Z".into()),
39            mobility_array_kind: Some(MobilityArrayKind::InverseReducedVsPerCm2),
40        };
41        let ms1 = SpectrumRecord {
42            index: 0,
43            scan_number: 1,
44            native_id: "controllerType=0 controllerNumber=1 scan=1".into(),
45            ms_level: MsPower::Ms1.ms_level(),
46            polarity: Some(Polarity::Positive),
47            scan_mode: Some(ScanMode::Centroid),
48            analyzer: Some(Analyzer::FTMS),
49            filter: Some("FTMS + p ESI Full ms".into()),
50            retention_time_sec: 0.123 * 60.0,
51            total_ion_current: None,
52            base_peak_mz: None,
53            base_peak_intensity: None,
54            low_mz: None,
55            high_mz: None,
56            ion_injection_time_ms: Some(20.0),
57            inv_mobility: None,
58            faims_cv: None,
59            precursor: None,
60            mz: vec![100.0, 200.0, 300.0],
61            intensity: vec![1.0, 5.0, 2.0],
62            inv_mobility_per_peak: None,
63        };
64        let ms2 = SpectrumRecord {
65            index: 1,
66            scan_number: 2,
67            native_id: "controllerType=0 controllerNumber=1 scan=2".into(),
68            ms_level: MsPower::Ms2.ms_level(),
69            polarity: Some(Polarity::Positive),
70            scan_mode: Some(ScanMode::Centroid),
71            analyzer: Some(Analyzer::FTMS),
72            filter: Some("FTMS + p ESI d Full ms2 200.00@hcd28.00".into()),
73            retention_time_sec: 0.5 * 60.0,
74            total_ion_current: Some(123.45),
75            base_peak_mz: Some(150.5),
76            base_peak_intensity: Some(99.0),
77            low_mz: Some(100.0),
78            high_mz: Some(180.0),
79            ion_injection_time_ms: Some(50.0),
80            inv_mobility: None,
81            faims_cv: Some(-45.0),
82            precursor: Some(PrecursorInfo {
83                target_mz: Some(200.0),
84                selected_mz: Some(200.001),
85                isolation_width: Some(2.0),
86                charge: Some(2),
87                intensity: None,
88                collision_energy: Some(28.0),
89                ce_is_nce: true,
90                precursor_native_id: Some("controllerType=0 controllerNumber=1 scan=1".into()),
91                activation: Some(Activation::CID),
92                analyzer: Some(Analyzer::FTMS),
93            }),
94            mz: vec![150.5, 160.0],
95            intensity: vec![99.0, 50.0],
96            inv_mobility_per_peak: None,
97        };
98        // A frame-collapsed ion-mobility MS1 (the Bruker timsTOF shape):
99        // scalar 1/K0 plus a per-peak inverse-reduced-mobility array, which
100        // the writer emits as a third binary data array. Exercises the
101        // ion-mobility CV path so it is schema-checked without a vendor file.
102        let ms1_mobility = SpectrumRecord {
103            index: 2,
104            scan_number: 3,
105            native_id: "frame=1 scan=0".into(),
106            ms_level: MsPower::Ms1.ms_level(),
107            polarity: Some(Polarity::Positive),
108            scan_mode: Some(ScanMode::Centroid),
109            analyzer: Some(Analyzer::TOFMS),
110            filter: None,
111            retention_time_sec: 0.75 * 60.0,
112            total_ion_current: None,
113            base_peak_mz: None,
114            base_peak_intensity: None,
115            low_mz: None,
116            high_mz: None,
117            ion_injection_time_ms: None,
118            inv_mobility: Some(0.95),
119            faims_cv: None,
120            precursor: None,
121            mz: vec![120.0, 240.0, 360.0],
122            intensity: vec![3.0, 7.0, 4.0],
123            inv_mobility_per_peak: Some(vec![0.92, 0.95, 0.98]),
124        };
125        // A TIC and a SRM/MRM transition chromatogram. Exercises the
126        // `chromatogramList` path (plain + indexed) so it is schema-checked
127        // without a vendor file.
128        let tic = ChromatogramRecord {
129            index: 0,
130            id: "TIC".into(),
131            chromatogram_type: Some(CvTerm::new("MS:1000235", "total ion current chromatogram")),
132            precursor_mz: None,
133            product_mz: None,
134            time_sec: vec![0.0, 30.0, 45.0],
135            intensity: vec![120.0, 340.0, 210.0],
136        };
137        let srm = ChromatogramRecord {
138            index: 1,
139            id: "SRM SIC Q1=524.3 Q3=136.1".into(),
140            chromatogram_type: Some(CvTerm::new(
141                "MS:1001473",
142                "selected reaction monitoring chromatogram",
143            )),
144            precursor_mz: Some(524.3),
145            product_mz: Some(136.1),
146            time_sec: vec![0.0, 30.0],
147            intensity: vec![50.0, 80.0],
148        };
149        Self {
150            meta,
151            spectra: vec![ms1, ms2, ms1_mobility],
152            chroms: vec![tic, srm],
153            cursor: 0,
154        }
155    }
156}
157
158impl SpectrumSource for SampleSource {
159    fn run_metadata(&self) -> RunMetadata {
160        self.meta.clone()
161    }
162
163    fn iter_spectra<'a>(&'a mut self) -> Box<dyn Iterator<Item = SpectrumRecord> + 'a> {
164        self.cursor = 0;
165        Box::new(std::iter::from_fn(move || {
166            let rec = self.spectra.get(self.cursor).cloned();
167            if rec.is_some() {
168                self.cursor += 1;
169            }
170            rec
171        }))
172    }
173
174    fn iter_chromatograms<'a>(&'a mut self) -> Box<dyn Iterator<Item = ChromatogramRecord> + 'a> {
175        Box::new(self.chroms.clone().into_iter())
176    }
177
178    fn spectrum_count_hint(&self) -> Option<usize> {
179        Some(self.spectra.len())
180    }
181}
182
183fn main() -> std::io::Result<()> {
184    let mut args = std::env::args().skip(1);
185    let plain_path = args.next().unwrap_or_else(|| "sample_plain.mzML".into());
186    let indexed_path = args.next().unwrap_or_else(|| "sample_indexed.mzML".into());
187
188    let mut src = SampleSource::new();
189    let mut plain = BufWriter::new(File::create(&plain_path)?);
190    write_mzml(&mut src, &mut plain)
191        .map_err(|e| std::io::Error::other(format!("write_mzml: {e}")))?;
192
193    let mut indexed = BufWriter::new(File::create(&indexed_path)?);
194    write_indexed_mzml(&mut src, &mut indexed)
195        .map_err(|e| std::io::Error::other(format!("write_indexed_mzml: {e}")))?;
196
197    eprintln!("wrote {plain_path} and {indexed_path}");
198    Ok(())
199}