Skip to main content

openreadout_agilent_ms/
lib.rs

1//! Clean-room reader for Agilent MassHunter `.d` mass-spectrometry directories (Q-TOF and
2//! triple-quadrupole acquisitions).
3//!
4//! Derived from public MetaboLights data sets compared spectrum by spectrum against the
5//! depositors' own mzML conversions, and from the `MSScan.xsd` schema every data directory
6//! carries. No vendor library is used, linked or consulted; see
7//! `docs/provenance/agilent-masshunter.md`.
8//!
9//! Layout and vocabulary: `docs/formats/agilent-masshunter.md`.
10//!
11//! # Example
12//!
13//! ```
14//! use openreadout_core::FormatReader;
15//! use openreadout_agilent_ms::AgilentMsReader;
16//!
17//! let format = AgilentMsReader.descriptor();
18//! assert_eq!(format.id, openreadout_agilent_ms::FORMAT_ID);
19//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
20//! ```
21//!
22//! Reading a data directory (pass the `.d` directory itself):
23//!
24//! ```no_run
25//! use std::path::Path;
26//!
27//! use openreadout_core::FormatReader;
28//! use openreadout_agilent_ms::AgilentMsReader;
29//!
30//! let mut dataset = AgilentMsReader.open(Path::new("run.d"))?;
31//! let info = dataset.info()?; // the scan index only
32//! let run = &info.spectra[0];
33//! println!("{} spectra, MS levels {:?}", run.scan_count, run.ms_levels);
34//! let spectrum = dataset.read_spectrum(0, 0)?;
35//! println!("MS{} at {:?} s: {} points", spectrum.ms_level, spectrum.rt_s, spectrum.mz.len());
36//! # Ok::<(), openreadout_core::Error>(())
37//! ```
38//!
39//! # API stability
40//!
41//! The supported API is what this page documents. The parser modules are public only so that
42//! tests and fuzz targets can reach them: they are hidden from this documentation and may change
43//! in any release.
44#![forbid(unsafe_code)]
45#![warn(missing_docs)]
46
47mod assurance;
48#[doc(hidden)]
49pub mod dataset;
50#[doc(hidden)]
51pub mod layout;
52
53use std::path::Path;
54
55use openreadout_core::Result;
56use openreadout_core::model::{DetectConfidence, FormatDescriptor};
57use openreadout_core::reader::{Dataset, Detection, FormatReader};
58use openreadout_core::source::{Fs, Input};
59
60#[doc(hidden)]
61pub use dataset::{AgilentDataset, Device, acq_dir, dataset_dir};
62
63/// Format id used on the command line and in JSON.
64pub const FORMAT_ID: &str = "agilent-masshunter";
65
66/// The Agilent MassHunter `.d` reader.
67#[derive(Debug, Default, Clone, Copy)]
68pub struct AgilentMsReader;
69
70/// True when `dir/AcqData/MSScan.bin` exists (names matched case-insensitively).
71fn is_masshunter_dir(fs: &Fs, dir: &Path) -> bool {
72    dataset::acq_dir_in(fs, dir).is_some_and(|a| {
73        fs.is_file(&a.join("MSScan.bin"))
74            || fs.read_dir(&a).is_ok_and(|rd| {
75                rd.flatten()
76                    .any(|e| e.file_name().eq_ignore_ascii_case("MSScan.bin"))
77            })
78    })
79}
80
81impl FormatReader for AgilentMsReader {
82    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
83        Some(&assurance::AGILENT_MASSHUNTER)
84    }
85
86    fn descriptor(&self) -> FormatDescriptor {
87        FormatDescriptor {
88            id: FORMAT_ID.into(),
89            name: "Agilent MassHunter (.d)".into(),
90            vendor: "Agilent Technologies".into(),
91            extensions: vec!["d".into()],
92            family: "mass-spectrometry".into(),
93            can_read: true,
94            can_write: false,
95            confidence: assurance::AGILENT_MASSHUNTER.confidence,
96            known_gaps: vec![
97                "Validated on MSScan layouts 5 (6400-series triple quadrupole 2006-2014: MRM, dynamic MRM, full, product-ion, neutral-loss and SIM scans, quadrupole profiles) and 6 (6200 TOF and 6500-series Q-TOF, acquisition software B.05 to B.10), and on the 6560 ion-mobility layout (drift-bin profiles, all-ions frames); other layouts are read through the file's own MSScan.xsd but are unverified".into(),
98                "Q-TOF profile spectra (MSProfile.bin, LZF) are checked against the scan index only (counts sum to the recorded TIC; the base-peak bin's m/z equals the recorded base-peak m/z): no export holds them; profiles are returned without the zero runs between peaks".into(),
99                "Precursor m/z is each MS/MS scan's own recorded value; ProteoWizard exports report a value averaged over the scans that share a precursor (differences up to 1e-5 relative)".into(),
100                "Ion-mobility data: drift-bin spectra only (the frame-summed spectra are not listed); all-ions high-energy spectra carry no precursor or collision energy (the frame method's energy ramp is shown by dump); compressed drift-bin profiles and CCS values are not supported".into(),
101                "Precursor-ion scans have not been seen; neutral-loss scans report the loss as extra.neutral_loss_mz, not as a precursor".into(),
102                "MSPeriodicActuals.bin, MSActualDefs.xml, the acquisition method's device settings and MSTree2.bin are listed but not decoded; ion-mode codes are reported as numbers".into(),
103                "DAD spectra (DAD1.sd/.sp) are a trace with one channel per wavelength, validated against one ProteoWizard export (520 spectra); DAD and LC-module signals (*.cd/*.cg) are exposed as traces".into(),
104            ],
105        }
106    }
107
108    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
109        self.sniff_input(head, &Input::local(path))
110    }
111
112    /// A `.d` is recognised by `AcqData/MSScan.bin`, looked up through the namespace.
113    fn sniff_input(&self, head: &[u8], input: &Input) -> Option<Detection> {
114        let _ = head;
115        let fs = input.fs();
116        let dir = dataset::dataset_dir_in(fs, input.path())?;
117        if !is_masshunter_dir(fs, &dir) {
118            return None;
119        }
120        let named_d = dir.extension().is_some_and(|e| e.eq_ignore_ascii_case("d"));
121        Some(Detection {
122            format_id: FORMAT_ID,
123            confidence: DetectConfidence::Definite,
124            note: (!named_d)
125                .then(|| "directory holds AcqData/MSScan.bin but is not named *.d".into()),
126        })
127    }
128
129    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
130        Ok(Box::new(AgilentDataset::open(path)?))
131    }
132
133    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
134        Ok(Box::new(AgilentDataset::open_input(input)?))
135    }
136
137    fn reads_any_source(&self) -> bool {
138        true
139    }
140}