Skip to main content

openreadout_bruker_tims/
lib.rs

1//! Clean-room readers for Bruker `.d` directories: timsTOF acquisitions (TDF/TSF, format id
2//! `bruker-tdf`) and BAF acquisitions of the other TOF and FT-ICR instruments (module `baf`,
3//! [`BrukerBafReader`], format id `bruker-baf`; `docs/formats/bruker-baf.md`).
4//!
5//! A TDF dataset (`analysis.tdf` + `analysis.tdf_bin`) stores frames of trapped-ion-mobility
6//! scans; a TSF dataset (`analysis.tsf` + `analysis.tsf_bin`) one line spectrum per frame. The
7//! `.tdf`/`.tsf` files are SQLite databases, read here by a small pure-Rust reader (write-ahead
8//! logs included); frame blobs are zstd-compressed. Spectra are exposed per MS1 frame (summed
9//! over scans), per DDA-PASEF precursor and per DIA-PASEF window. Layout and vocabulary:
10//! `docs/formats/bruker-tdf.md`. Provenance: `docs/provenance/bruker-tdf.md`.
11//!
12//! # Example
13//!
14//! Every reader implements [`openreadout_core::FormatReader`]: `descriptor`
15//! says what it reads, `sniff` recognises a file from its first bytes, and `open` returns a
16//! [`openreadout_core::Dataset`] with a header-only `info()` summary and lazy data
17//! access.
18//!
19//! ```
20//! use openreadout_core::FormatReader;
21//! use openreadout_bruker_tims::BrukerTimsReader;
22//!
23//! let format = BrukerTimsReader.descriptor();
24//! assert_eq!(format.id, openreadout_bruker_tims::FORMAT_ID);
25//! println!("{} ({}): .{}", format.name, format.family, format.extensions.join(", ."));
26//! ```
27//!
28//! Reading a file:
29//!
30//! ```no_run
31//! use std::path::Path;
32//!
33//! use openreadout_core::FormatReader;
34//! use openreadout_bruker_tims::BrukerTimsReader;
35//!
36//! let mut dataset = BrukerTimsReader.open(Path::new("run.d"))?;
37//! let info = dataset.info()?; // headers only
38//! let run = &info.spectra[0];
39//! println!("{} spectra, MS levels {:?}", run.scan_count, run.ms_levels);
40//! // Spectrum 0 of run 0: parallel m/z and intensity arrays.
41//! let spectrum = dataset.read_spectrum(0, 0)?;
42//! println!("MS{} at {:?} s: {} points", spectrum.ms_level, spectrum.rt_s, spectrum.mz.len());
43//! # Ok::<(), openreadout_core::Error>(())
44//! ```
45//!
46//! Applications that accept any instrument file usually register every reader in an
47//! [`openreadout_core::Registry`] and let it detect the format; that is what the
48//! `openreadout` command-line tool does.
49//!
50//! # API stability
51//!
52//! The supported API is what this page documents. The parser modules are public only so that
53//! tests and fuzz targets can reach them: they are hidden from this documentation and may change
54//! in any release.
55#![forbid(unsafe_code)]
56#![warn(missing_docs)]
57
58mod assurance;
59#[doc(hidden)]
60pub mod baf;
61#[doc(hidden)]
62pub mod calibration;
63#[doc(hidden)]
64pub mod dataset;
65#[doc(hidden)]
66pub mod frame;
67#[doc(hidden)]
68pub mod sqlite;
69
70use std::path::Path;
71
72use openreadout_core::Result;
73use openreadout_core::model::{DetectConfidence, FormatDescriptor};
74use openreadout_core::reader::{Dataset, Detection, FormatReader};
75use openreadout_core::source::Input;
76
77#[doc(hidden)]
78pub use calibration::{MobilityModel, MzCalibrationRow, MzModel, TimsCalibrationRow};
79#[doc(hidden)]
80pub use dataset::{
81    Conversions, FrameRecord, MaldiSpot, PrecursorRecord, Selection, TimsDataset, TimsKind,
82    dataset_dir, kind_of,
83};
84#[doc(hidden)]
85pub use frame::{
86    FrameError, TimsFrame, decode_tdf_frame, decode_tdf_frame_lzf, decode_tsf_profile,
87    decode_tsf_spectrum, group_and_sum, read_blob,
88};
89#[doc(hidden)]
90pub use sqlite::{SqlTable, SqlValue, SqliteDb, SqliteError};
91
92pub use baf::BrukerBafReader;
93
94/// Format id on the command line and in JSON.
95pub const FORMAT_ID: &str = "bruker-tdf";
96
97/// The timsTOF reader.
98#[derive(Debug, Default, Clone, Copy)]
99pub struct BrukerTimsReader;
100
101impl FormatReader for BrukerTimsReader {
102    fn assurance(&self) -> Option<&'static openreadout_core::assurance::AssuranceProfile> {
103        Some(&assurance::BRUKER_TDF)
104    }
105
106    fn descriptor(&self) -> FormatDescriptor {
107        FormatDescriptor {
108            id: FORMAT_ID.into(),
109            name: "Bruker timsTOF (TDF/TSF .d)".into(),
110            vendor: "Bruker".into(),
111            extensions: vec!["d".into(), "tdf".into(), "tsf".into()],
112            family: "mass-spectrometry".into(),
113            can_read: true,
114            can_write: false,
115            confidence: assurance::BRUKER_TDF.confidence,
116            known_gaps: vec![
117                "m/z and 1/K0 apply the file's MzCalibration (types 1, 2) and TimsCalibration (type 2) models, validated to <= 0.065 ppm and 5e-13 V*s/cm2 against vendor-library conversions of five files; other model types fall back to the acquisition-range approximation (tens of ppm off) and say so in notes and check".into(),
118                "prm-PASEF frames (MsMsType 10) are summed whole, not split per target window (no public prm-PASEF file to validate against)".into(),
119                "Spectra are raw sums of TOF bins over scans (no smoothing or centroiding); per-scan mobility arrays are not returned by `spectrum` (library: TimsDataset::read_frame)".into(),
120                "TimsCompressionType 1 frames hold more scans than Frames.NumScans; all are read (NumPeaks and SummedIntensities count them; the reference conversion lists only the first NumScans)".into(),
121            ],
122        }
123    }
124
125    fn sniff(&self, head: &[u8], path: &Path) -> Option<Detection> {
126        self.sniff_input(head, &Input::local(path))
127    }
128
129    /// A `.d` is recognised by its analysis file, looked up through the namespace.
130    fn sniff_input(&self, head: &[u8], input: &Input) -> Option<Detection> {
131        let fs = input.fs();
132        let dir = dataset::dataset_dir_in(fs, input.path())?;
133        let kind = dataset::kind_of_in(fs, &dir)?;
134        let named_d = dir.extension().is_some_and(|e| e.eq_ignore_ascii_case("d"));
135        // A directory arrives with an empty head; a file inside the .d with its own head.
136        let _ = head;
137        Some(Detection {
138            format_id: FORMAT_ID,
139            confidence: DetectConfidence::Definite,
140            note: (!named_d).then(|| {
141                format!(
142                    "directory holds analysis.{} but is not named *.d",
143                    if kind == TimsKind::Tdf { "tdf" } else { "tsf" }
144                )
145            }),
146        })
147    }
148
149    fn open(&self, path: &Path) -> Result<Box<dyn Dataset>> {
150        Ok(Box::new(TimsDataset::open(path)?))
151    }
152
153    fn open_input(&self, input: &Input) -> Result<Box<dyn Dataset>> {
154        Ok(Box::new(TimsDataset::open_input(input)?))
155    }
156
157    fn reads_any_source(&self) -> bool {
158        true
159    }
160}