Skip to main content

openreadout_quant/
api.rs

1//! JSON queries for `analyze chromatogram` and `analyze peaks`, shared by the MCP tool
2//! (`openreadout_chromatogram` and `openreadout_peaks`) and the Python bindings: the same
3//! field names and defaults everywhere.
4
5use openreadout_core::model::FileInfo;
6use openreadout_core::parallel::ReadContext;
7use openreadout_core::{Dataset, Error, Result};
8use schemars::JsonSchema;
9use serde::Deserialize;
10
11use crate::analyze::{PeaksOutput, PeaksRequest, run_peaks};
12use crate::bands::RegionBaseline;
13use crate::extract::{
14    Aggregate, ChromRequest, ChromatogramOutput, Polarity, Target, Tolerance, extract,
15};
16use crate::peaks::{AreaTimeUnit, BaselineMode, PeakParams, PickRule};
17use crate::targets::Compound;
18
19/// Points per chromatogram a query returns by default.
20pub const DEFAULT_CHROMATOGRAM_POINTS: usize = 500;
21/// Most points per chromatogram a query returns.
22pub const MAX_CHROMATOGRAM_POINTS: usize = 20_000;
23
24/// Which chromatograms, from which scans (shared by both tools).
25#[derive(Debug, Default, Deserialize, JsonSchema)]
26pub struct SourceArgs {
27    /// Total-ion chromatogram (the default for mass-spectrometry files when nothing else is chosen).
28    #[serde(default)]
29    pub tic: bool,
30    /// Base-peak chromatogram.
31    #[serde(default)]
32    pub bpc: bool,
33    /// Extracted-ion chromatograms at these m/z values (one streaming pass for all).
34    #[serde(default)]
35    pub mz: Vec<f64>,
36    /// XIC tolerance (half-width) in ppm. Default 10.
37    pub ppm: Option<f64>,
38    /// XIC tolerance in m/z units instead of ppm.
39    pub da: Option<f64>,
40    /// SRM/MRM transitions as `"Q1>Q3"` strings, e.g. `"279.2>179.2"`.
41    #[serde(default)]
42    pub transitions: Vec<String>,
43    /// Q1/Q3 tolerance of transitions, m/z units. Default 0.5.
44    pub transition_tol: Option<f64>,
45    /// Stored chromatograms or detector signals (UV/DAD, FID, TCD, stored TIC/SRM): trace indices from openreadout_info → traces[].
46    #[serde(default)]
47    pub traces: Vec<u32>,
48    /// Channel of the traces (e.g. one DAD wavelength). Default: the first signal channel.
49    pub channel: Option<u32>,
50    /// Sweep of the traces (one spectrum of a map or series, one injection). Default 0.
51    pub sweep: Option<u32>,
52    /// Spectra run. Default 0.
53    #[serde(default)]
54    pub run: u32,
55    /// MS level of the scans. Default 1 (2 with `precursor`).
56    pub ms_level: Option<u32>,
57    /// `positive` or `negative`: only scans of this polarity.
58    pub polarity: Option<String>,
59    /// Only scans whose scan filter/description contains this text (case-insensitive).
60    pub scan_filter: Option<String>,
61    /// Only MS/MS scans of this precursor m/z (product-ion XIC).
62    pub precursor: Option<f64>,
63    /// Precursor tolerance, m/z units. Default 0.5.
64    pub precursor_tol: Option<f64>,
65    /// Retention-time range `[start, end]`, minutes.
66    pub rt_range: Option<[f64; 2]>,
67    /// TIC/BPC over this m/z range only, `[low, high]`.
68    pub mz_range: Option<[f64; 2]>,
69    /// Use profile data where scans store both profile and centroids. Default false (the
70    /// instrument's centroids).
71    #[serde(default)]
72    pub profile: bool,
73    /// `sum` (default) or `max` of the points inside an XIC window.
74    pub aggregate: Option<String>,
75}
76
77impl SourceArgs {
78    /// The extraction request.
79    pub fn request(&self) -> Result<ChromRequest> {
80        let mut r = ChromRequest::default();
81        if self.tic {
82            r.targets.push(Target::Tic);
83        }
84        if self.bpc {
85            r.targets.push(Target::Bpc);
86        }
87        r.targets
88            .extend(self.mz.iter().map(|&mz| Target::Xic { mz }));
89        for t in &self.transitions {
90            let bad = || Error::Usage(format!("transition {t:?}: expected \"Q1>Q3\""));
91            let (a, b) = t
92                .split_once('>')
93                .or_else(|| t.split_once('/'))
94                .ok_or_else(bad)?;
95            r.targets.push(Target::Srm {
96                q1: a.trim().parse().map_err(|_| bad())?,
97                q3: b.trim().parse().map_err(|_| bad())?,
98            });
99        }
100        r.targets
101            .extend(self.traces.iter().map(|&trace| Target::Trace {
102                trace,
103                channel: self.channel,
104            }));
105        if self.traces.is_empty() && self.channel.is_some() {
106            r.targets.push(Target::Trace {
107                trace: 0,
108                channel: self.channel,
109            });
110        }
111        if let Some(p) = self.ppm {
112            r.tolerance = Tolerance::Ppm(p);
113        }
114        if let Some(d) = self.da {
115            r.tolerance = Tolerance::Da(d);
116        }
117        if let Some(t) = self.transition_tol {
118            r.transition_tolerance_da = t;
119        }
120        r.run = self.run;
121        r.sweep = self.sweep.unwrap_or(0);
122        r.ms_level = self.ms_level;
123        r.polarity = self
124            .polarity
125            .as_deref()
126            .map(str::parse::<Polarity>)
127            .transpose()?;
128        r.scan_filter.clone_from(&self.scan_filter);
129        r.precursor_mz = self.precursor;
130        if let Some(t) = self.precursor_tol {
131            r.precursor_tolerance_da = t;
132        }
133        r.rt_range_min = self.rt_range;
134        r.mz_range = self.mz_range;
135        r.profile = self.profile;
136        r.aggregate = match self.aggregate.as_deref() {
137            None | Some("sum") => Aggregate::Sum,
138            Some("max") => Aggregate::Max,
139            Some(o) => return Err(Error::Usage(format!("aggregate {o:?}: use sum or max"))),
140        };
141        Ok(r)
142    }
143}
144
145/// An `analyze chromatogram` query.
146#[derive(Debug, Default, Deserialize, JsonSchema)]
147pub struct ChromatogramQuery {
148    /// Which chromatograms.
149    #[serde(flatten)]
150    pub source: SourceArgs,
151    /// Points returned per chromatogram (the most intense point of each of N equal slices).
152    /// Default 500, max 20000; the summary (apex, integral) always covers every point.
153    pub max_points: Option<usize>,
154}
155
156/// An `analyze peaks` query.
157#[derive(Debug, Default, Deserialize, JsonSchema)]
158pub struct PeaksQuery {
159    /// Which chromatograms (default: the first detector trace, else the TIC).
160    #[serde(flatten)]
161    pub source: SourceArgs,
162    /// Savitzky–Golay window in points (below 5: none). Default automatic.
163    pub smooth: Option<u32>,
164    /// Detection threshold, height / noise σ. Default 3.
165    pub min_snr: Option<f64>,
166    /// Detection threshold in signal units.
167    pub min_height: Option<f64>,
168    /// Smallest width at half height, minutes.
169    pub min_width: Option<f64>,
170    /// Baseline under detected peaks: `auto` (default), `drop`, `valley` or `tangent`; or the
171    /// baseline under `x_range` windows and manual integrations: `linear` (default: a straight
172    /// line between the window's ends) or `none` (area of the signal itself).
173    pub baseline: Option<String>,
174    /// Areas in signal × seconds instead of signal × minutes. Default false.
175    #[serde(default)]
176    pub area_seconds: bool,
177    /// Expected retention time (minutes): also report the peak there as `picked`.
178    pub rt: Option<f64>,
179    /// Half-width of the `rt` window (and of compounds without one), minutes. Default 0.5.
180    pub window: Option<f64>,
181    /// `largest` (default) or `nearest` peak in the window.
182    pub pick: Option<String>,
183    /// Manual integrations `[[start, end], ...]` in minutes.
184    #[serde(default)]
185    pub integrate: Vec<[f64; 2]>,
186    /// Axis windows `[[a, b], ...]` to integrate, in the axis's own units (either order): on a
187    /// spectrum (IR/Raman cm⁻¹, UV nm, NMR ppm) each is a region under `spectra[].regions` (area
188    /// with the `baseline`, area without it, maximum, centroid, the bands inside); on a
189    /// chromatogram a manual integration in minutes.
190    #[serde(default)]
191    pub x_range: Vec<[f64; 2]>,
192    /// Targeted compounds: `[{name, mz? | q1+q3? | trace?, rt?, window?, ppm?, polarity?, ms_level?, precursor?}]`; one result row each under `compounds`.
193    #[serde(default)]
194    pub compounds: Vec<Compound>,
195    /// Leave out the full peak tables (keep compounds, picked and manual results). Default false.
196    #[serde(default)]
197    pub summary_only: bool,
198}
199
200/// Run an `analyze chromatogram` query on an open file.
201pub fn chromatogram(
202    ds: &mut dyn Dataset,
203    info: &FileInfo,
204    q: &ChromatogramQuery,
205    ctx: &ReadContext<'_>,
206) -> Result<ChromatogramOutput> {
207    let req = q.source.request()?;
208    let mut out = extract(ds, info, &req, ctx)?;
209    let max = q
210        .max_points
211        .unwrap_or(DEFAULT_CHROMATOGRAM_POINTS)
212        .clamp(1, MAX_CHROMATOGRAM_POINTS);
213    for c in &mut out.chromatograms {
214        c.decimate(max);
215    }
216    Ok(out)
217}
218
219/// Run an `analyze peaks` query on an open file.
220pub fn peaks(
221    ds: &mut dyn Dataset,
222    info: &FileInfo,
223    a: &PeaksQuery,
224    ctx: &ReadContext<'_>,
225) -> Result<PeaksOutput> {
226    let mut r = PeaksRequest {
227        chrom: a.source.request()?,
228        default_window_min: a.window,
229        integrate: a.integrate.clone(),
230        compounds: a.compounds.clone(),
231        x_ranges: a.x_range.clone(),
232        ..PeaksRequest::default()
233    };
234    let mut p = PeakParams {
235        smooth: a.smooth,
236        min_height: a.min_height,
237        min_width_min: a.min_width,
238        rt_range_min: a.source.rt_range,
239        ..PeakParams::default()
240    };
241    if let Some(s) = a.min_snr {
242        p.min_snr = s;
243    }
244    if let Some(b) = &a.baseline {
245        match b.to_ascii_lowercase().as_str() {
246            "linear" | "straight" => r.region_baseline = RegionBaseline::Linear,
247            "none" | "zero" | "off" => r.region_baseline = RegionBaseline::None,
248            _ => p.baseline = b.parse::<BaselineMode>()?,
249        }
250    }
251    if a.area_seconds {
252        p.area_time_unit = AreaTimeUnit::S;
253    }
254    r.params = p;
255    if let Some(k) = &a.pick {
256        r.pick = k.parse::<PickRule>()?;
257    }
258    if let Some(rt) = a.rt {
259        r.expect = Some((
260            rt,
261            a.window.unwrap_or(crate::analyze::DEFAULT_RT_WINDOW_MIN),
262        ));
263    }
264    let (mut out, _) = run_peaks(ds, info, &r, ctx)?;
265    if a.summary_only {
266        for c in &mut out.chromatograms {
267            c.peaks.clear();
268        }
269        for s in &mut out.spectra {
270            s.peaks.clear();
271        }
272    }
273    Ok(out)
274}