Skip to main content

openreadout_waters/
lib.rs

1//! Clean-room reader for Waters MassLynx `.raw` directories: full-scan spectra of TOF
2//! instruments (SYNAPT, Xevo, Vion) with the m/z calibration applied, MS/MS precursors and
3//! lock-spray reference functions, MRM/SIR intensities of triple quadrupoles, per-scan
4//! statistics and analog channels.
5//!
6//! Derived from public MetaboLights and PRIDE acquisitions compared spectrum by spectrum
7//! against the depositors' own mzML conversions, and from rainbow's public documentation pages
8//! for the 2-, 6- and 8-byte value layouts. No vendor library is used, linked or consulted; see
9//! `docs/provenance/waters-raw.md`.
10//!
11//! Layout and vocabulary: `docs/formats/waters-raw.md`.
12//!
13//! # Example
14//!
15//! ```
16//! use openreadout_core::FormatReader;
17//! use openreadout_waters::WatersRawReader;
18//!
19//! let format = WatersRawReader.descriptor();
20//! assert_eq!(format.id, openreadout_waters::WATERS_ID);
21//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
22//! ```
23//!
24//! Reading an acquisition (pass the `.raw` directory itself):
25//!
26//! ```no_run
27//! use std::path::Path;
28//!
29//! use openreadout_core::FormatReader;
30//! use openreadout_waters::WatersRawReader;
31//!
32//! let mut dataset = WatersRawReader.open(Path::new("run.raw"))?;
33//! let info = dataset.info()?; // headers and scan indexes only
34//! if let Some(run) = info.spectra.first() {
35//!     println!("{} spectra, MS levels {:?}", run.scan_count, run.ms_levels);
36//!     let spectrum = dataset.read_spectrum(0, 0)?;
37//!     println!("MS{} at {:?} s: {} peaks", spectrum.ms_level, spectrum.rt_s, spectrum.mz.len());
38//! }
39//! # Ok::<(), openreadout_core::Error>(())
40//! ```
41//!
42//! # API stability
43//!
44//! The supported API is what this page documents. The parser modules are public only so that
45//! tests and fuzz targets can reach them: they are hidden from this documentation and may change
46//! in any release.
47#![forbid(unsafe_code)]
48#![warn(missing_docs)]
49
50mod assurance;
51#[doc(hidden)]
52pub mod dataset;
53
54#[doc(hidden)]
55pub mod drift;
56#[doc(hidden)]
57pub mod layout;
58
59use std::path::Path;
60
61use openreadout_core::Result;
62use openreadout_core::model::{DetectConfidence, FormatDescriptor};
63use openreadout_core::reader::{Dataset, Detection, FormatReader, has_extension};
64use openreadout_core::source::Input;
65
66#[doc(hidden)]
67pub use dataset::{
68    AnalogChannel, WatersFunction, WatersRawDataset, is_waters_dir, is_waters_dir_in,
69};
70#[doc(hidden)]
71pub use layout::{
72    CHRO_HEADER, Calibration, CalibrationKind, FLAG_LOCK_MASS_PEAK, FUNCTION_BLOCK,
73    FUNCTION_DAUGHTER, FUNCTION_MRM, FUNCTION_PDA, FUNCTION_TOF_MS, FUNCTION_TOF_MSMS,
74    FunctionBlock, IDX_RECORD, IDX_RECORD_WIDE, STAT_SET_MASS, ScanIndex, StatsLayout,
75    decode_intensity12, decode_mass27, decode_packed16, decode_packed32, decode_value6,
76    decode_value8, decode_value12, idx_record_len_for, parse_extern, parse_functions,
77    parse_header_txt, parse_idx, parse_stats_layout, value12_flags,
78};
79
80/// Format id of the Waters MassLynx `.raw` reader.
81pub const WATERS_ID: &str = "waters-raw";
82
83/// Waters MassLynx `.raw` directories.
84#[derive(Debug, Default, Clone, Copy)]
85pub struct WatersRawReader;
86
87impl FormatReader for WatersRawReader {
88    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
89        Some(&assurance::WATERS_RAW)
90    }
91
92    fn descriptor(&self) -> FormatDescriptor {
93        FormatDescriptor {
94            id: WATERS_ID.into(),
95            name: "Waters MassLynx .raw directory".into(),
96            vendor: "Waters".into(),
97            extensions: vec!["raw".into()],
98            family: "chromatography".into(),
99            can_read: true,
100            can_write: false,
101            confidence: assurance::WATERS_RAW.confidence,
102            known_gaps: vec![
103                "Spectra are validated point for point (m/z within 0.06 ppm, intensities equal) against vendor-library conversions of 13 acquisitions (SYNAPT G2/G2-Si/XS, Synapt MS, Xevo TQ-MS/G2-XS, ACQUITY SQD; 12-, 8- and 6-byte layouts, centroid and continuum, DDA, MSe, product-ion scans); the index flag 0x100 means values stored calibrated, otherwise the `Cal Function n` polynomial (T0, T1) is applied".into(),
104                "Lock-mass (lock-spray) correction is off by default (m/z as stored; each reference scan's flagged lock-mass peak is reported as `lock_mass_peak_mz`) and applied on request (`--lock-mass MZ|auto`, `Dataset::set_lock_mass`): checked against MassLynx-corrected copies of two runs to about 2 ppm, its exact smoothing over lock-spray scans is not established; files MassLynx already corrected are read as stored".into(),
105                "Ion-mobility and SONAR functions: run 1 lists the drift bins (_funcNNN.cdt); a scan whose drift index holds non-zero values in its second array (seen in the lock-spray function of a SYNAPT XS SONAR run) is refused, and its drift-summed spectrum in run 0 stays readable".into(),
106                "MRM intensities (4-byte layout) are scaled so each scan sums to the TIC stored in _FUNCnnn.IDX (rainbow reports twice these values) and exposed as tables/traces, not spectra".into(),
107                "Photodiode-array functions are a trace of stored absorbance counts (unscaled); binary .EE/.CMP files and the third word of 12-byte values are listed, not decoded".into(),
108            ],
109        }
110    }
111
112    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
113        self.sniff_input(head, &Input::local(path))
114    }
115
116    /// A `.raw` directory is recognised by its files, listed through the input's namespace.
117    fn sniff_input(&self, _head: &[u8], input: &Input) -> Option<Detection> {
118        let path = input.path();
119        if is_waters_dir_in(input.fs(), path) {
120            return Some(Detection {
121                format_id: WATERS_ID,
122                confidence: if has_extension(path, &["raw"]) {
123                    DetectConfidence::Definite
124                } else {
125                    DetectConfidence::Likely
126                },
127                note: None,
128            });
129        }
130        None
131    }
132
133    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
134        Ok(Box::new(WatersRawDataset::open(path)?))
135    }
136
137    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
138        Ok(Box::new(WatersRawDataset::open_input(input)?))
139    }
140
141    fn reads_any_source(&self) -> bool {
142        true
143    }
144}