Skip to main content

openreadout_sciex/
lib.rs

1//! Clean-room reader for legacy Sciex `.wiff` files with their `.wiff.scan` companions: the
2//! acquisition method (experiments, MRM transitions with their scheduling windows), sample
3//! information, the scan index, MRM intensities and TripleTOF time-of-flight scans with the
4//! per-scan calibration and data-dependent precursors. `.wiff2` files are recognised and
5//! refused: they are encrypted (see `docs/legal/clean-room-policy.md`).
6//!
7//! Derived from public MetaboLights data sets compared against the depositors' own
8//! conversions. The `.wiff` container is read with `openreadout-core`'s compound-file reader.
9//! No vendor library is used, linked or consulted; see `docs/provenance/sciex-wiff.md`.
10//!
11//! Layout and vocabulary: `docs/formats/sciex-wiff.md`.
12//!
13//! # Example
14//!
15//! ```
16//! use openreadout_core::FormatReader;
17//! use openreadout_sciex::SciexWiffReader;
18//!
19//! let format = SciexWiffReader.descriptor();
20//! assert_eq!(format.id, openreadout_sciex::FORMAT_ID);
21//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
22//! ```
23//!
24//! Reading a file (the `.wiff.scan` must sit beside the `.wiff`):
25//!
26//! ```no_run
27//! use std::path::Path;
28//!
29//! use openreadout_core::FormatReader;
30//! use openreadout_sciex::SciexWiffReader;
31//!
32//! let mut dataset = SciexWiffReader.open(Path::new("run.wiff"))?;
33//! let info = dataset.info()?; // method, sample and scan index only
34//! let run = &info.spectra[0];
35//! println!("{} spectra, MS levels {:?}", run.scan_count, run.ms_levels);
36//! let spectrum = dataset.read_spectrum(0, 0)?;
37//! println!("MS{} at {:?} s: {} points", spectrum.ms_level, spectrum.rt_s, spectrum.mz.len());
38//! # Ok::<(), openreadout_core::Error>(())
39//! ```
40//!
41//! # API stability
42//!
43//! The supported API is what this page documents. The parser modules are public only so that
44//! tests and fuzz targets can reach them: they are hidden from this documentation and may change
45//! in any release.
46#![forbid(unsafe_code)]
47#![warn(missing_docs)]
48
49mod assurance;
50#[doc(hidden)]
51pub mod dataset;
52#[doc(hidden)]
53pub mod layout;
54
55use std::path::Path;
56
57use openreadout_core::cfb::CFB_MAGIC;
58use openreadout_core::model::{DetectConfidence, FormatDescriptor};
59use openreadout_core::reader::{Dataset, Detection, FormatReader, has_extension};
60use openreadout_core::source::Input;
61use openreadout_core::{Error, Result};
62
63#[doc(hidden)]
64pub use dataset::{Experiment, Sample, SciexDataset, wiff_path};
65
66/// Format id used on the command line and in JSON.
67pub const FORMAT_ID: &str = "sciex-wiff";
68
69/// The Sciex `.wiff` reader.
70#[derive(Debug, Default, Clone, Copy)]
71pub struct SciexWiffReader;
72
73fn is_wiff2(path: &Path) -> bool {
74    has_extension(path, &["wiff2"])
75}
76
77fn is_scan_companion(path: &Path) -> bool {
78    path.file_name().is_some_and(|n| {
79        n.to_string_lossy()
80            .to_ascii_lowercase()
81            .ends_with(".wiff.scan")
82    })
83}
84
85impl FormatReader for SciexWiffReader {
86    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
87        Some(&assurance::SCIEX_WIFF)
88    }
89
90    fn descriptor(&self) -> FormatDescriptor {
91        FormatDescriptor {
92            id: FORMAT_ID.into(),
93            name: "Sciex WIFF (.wiff + .wiff.scan)".into(),
94            vendor: "SCIEX".into(),
95            extensions: vec!["wiff".into(), "scan".into(), "wiff2".into()],
96            family: "mass-spectrometry".into(),
97            can_read: true,
98            can_write: false,
99            confidence: assurance::SCIEX_WIFF.confidence,
100            known_gaps: vec![
101                ".wiff2 (SCIEX OS) files are encrypted and are refused (exit 6); convert them with the vendor's software".into(),
102                "Validated on MRM files (QTRAP 6500+ scheduled MRM, Analyst 1.7.2: 165 SRM chromatograms bit-exact; QTRAP 6500; a 2007 ten-sample Analyst file with one value per transition per cycle) and LC device traces, and on TripleTOF 6600 and 5600+ data-dependent files (Analyst TF; scan times, MS levels, polarity, precursors, TIC and base-peak m/z against the export); other scan types (Q1/Q3 scans, enhanced product ion, MRM³, SWATH variable windows) are listed but not decoded".into(),
103                "TOF spectra are the stored time-to-digital histograms (counts per bin, calibrated per scan); the vendor library's peak picking, which depositor exports hold, is not reproduced".into(),
104                "ZenoTOF (SCIEX OS) .wiff + .wiff.scan files: scan times, MS levels, polarity and precursor m/z agree with the export; no stream of the file holds the precursor charges or per-scan collision energies the exports list (they appear to be computed by the converter), so both are reported absent".into(),
105                "Without the .wiff.scan, scan headers (times, MS levels, precursors) are listed from the .wiff and peaks are refused (exit 6)".into(),
106                "TripleTOF 5600 files: the index TIC is not the sum of the stored counts (median +0.6 %, from -64 % on the most intense scans to +38 % on the weakest); every scan's largest count equals the index's base-peak intensity at the index's base-peak m/z, so the counts are returned as stored and `total_ion_current` is the index value".into(),
107                "The first half of every 2N-value MRM cycle (zero in the corpus files) is not interpreted; transitions are assigned to cycles by their scheduling windows, and a boundary cycle whose values are all zero is left out of the transitions that start or end there (inferred from one file)".into(),
108                "Multi-period methods: only period 0's experiments are described; multi-sample files expose one run per sample but only sample 1's acquisition time".into(),
109            ],
110        }
111    }
112
113    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
114        if is_wiff2(path) {
115            return Some(Detection {
116                format_id: FORMAT_ID,
117                confidence: DetectConfidence::Definite,
118                note: Some(".wiff2 is encrypted and not readable".into()),
119            });
120        }
121        if is_scan_companion(path) {
122            return Some(Detection {
123                format_id: FORMAT_ID,
124                confidence: DetectConfidence::Likely,
125                note: Some("the .wiff.scan companion: the .wiff beside it is opened".into()),
126            });
127        }
128        if !has_extension(path, &["wiff"]) {
129            return None;
130        }
131        // A file long enough to show the compound-file signature that does not is another kind
132        // of file (exit 3), not a damaged one.
133        if head.len() >= CFB_MAGIC.len() && !head.starts_with(&CFB_MAGIC) {
134            return None;
135        }
136        let cfb = head.starts_with(&CFB_MAGIC);
137        Some(Detection {
138            format_id: FORMAT_ID,
139            confidence: if cfb {
140                DetectConfidence::Definite
141            } else {
142                DetectConfidence::ExtensionOnly
143            },
144            note: (!cfb).then(|| ".wiff extension but no compound-file signature".into()),
145        })
146    }
147
148    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
149        self.open_input(&Input::local(path))
150    }
151
152    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
153        let path = input.path();
154        if is_wiff2(path) {
155            return Err(Error::unsupported(
156                FORMAT_ID,
157                ".wiff2 (SCIEX OS) files",
158                "WIFF2 data are encrypted; this project does not circumvent that. Export mzML from SCIEX OS or convert with the vendor's tools, then open the export.",
159            ));
160        }
161        Ok(Box::new(SciexDataset::open_input(input)?))
162    }
163
164    fn reads_any_source(&self) -> bool {
165        true
166    }
167}