Skip to main content

openreadout_quant/
targets.rs

1//! Compound lists for targeted quantitation: one row per compound with how to extract its
2//! chromatogram (an m/z, an SRM transition, a detector trace or the default chromatogram) and
3//! where to expect it (retention time ± window). Read from CSV/TSV (header row) or JSON (an
4//! array of objects, or `{"compounds": [...]}`).
5
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9use openreadout_core::{Error, Result};
10
11use crate::extract::Polarity;
12
13/// One compound of a targeted method.
14#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
15pub struct Compound {
16    /// Name, reported in the results.
17    pub name: String,
18    /// XIC m/z (with `precursor_mz`: a product ion in MS/MS scans).
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub mz: Option<f64>,
21    /// SRM/MRM precursor (Q1) m/z.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub q1: Option<f64>,
24    /// SRM/MRM product (Q3) m/z.
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub q3: Option<f64>,
27    /// Expected retention time, minutes (absent: the largest peak of the chromatogram).
28    #[serde(default, alias = "rt", skip_serializing_if = "Option::is_none")]
29    pub rt_min: Option<f64>,
30    /// Half-width of the retention-time window, minutes.
31    #[serde(default, alias = "window", skip_serializing_if = "Option::is_none")]
32    pub rt_window_min: Option<f64>,
33    /// XIC tolerance, ppm.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub ppm: Option<f64>,
36    /// XIC tolerance, Da (instead of ppm).
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub da: Option<f64>,
39    /// Scan polarity.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub polarity: Option<Polarity>,
42    /// MS level of the scans.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub ms_level: Option<u32>,
45    /// Precursor m/z of the MS/MS scans (product-ion XIC).
46    #[serde(default, alias = "precursor", skip_serializing_if = "Option::is_none")]
47    pub precursor_mz: Option<f64>,
48    /// Detector trace index (for UV, FID, … quantitation).
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub trace: Option<u32>,
51    /// Channel of that trace.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub channel: Option<u32>,
54}
55
56/// One result row: a compound in one file.
57#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
58pub struct CompoundResult {
59    /// The input file.
60    pub path: String,
61    /// Compound name.
62    pub compound: String,
63    /// Label of the chromatogram it was measured on.
64    pub chromatogram: String,
65    /// Expected retention time, minutes.
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub expected_rt_min: Option<f64>,
68    /// Window half-width, minutes.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub rt_window_min: Option<f64>,
71    /// True when a peak was found in the window.
72    pub found: bool,
73    /// Apex retention time, minutes.
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub rt_min: Option<f64>,
76    /// Apex − expected retention time, minutes.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub rt_shift_min: Option<f64>,
79    /// Peak area (signal × `area_time_unit` of the method).
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub area: Option<f64>,
82    /// Peak height above the baseline.
83    #[serde(skip_serializing_if = "Option::is_none")]
84    pub height: Option<f64>,
85    /// Height / noise σ.
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub snr: Option<f64>,
88    /// Width at half height, minutes.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub width_half_min: Option<f64>,
91    /// USP tailing factor.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub tailing_factor: Option<f64>,
94    /// Integration start, minutes.
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub start_min: Option<f64>,
97    /// Integration end, minutes.
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub end_min: Option<f64>,
100    /// Baseline code of the peak (`BB`, `BV`, …).
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub baseline_code: Option<String>,
103    /// Area % of the peak within its chromatogram.
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub area_percent: Option<f64>,
106    /// Unit of `area`, e.g. `counts·min`, `mAU·s`.
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub area_unit: Option<String>,
109    /// Why nothing was found, or anything else worth knowing.
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub note: Option<String>,
112}
113
114const COLUMNS: &[(&str, &[&str])] = &[
115    (
116        "name",
117        &["name", "compound", "analyte", "id", "compound_name"],
118    ),
119    ("mz", &["mz", "m/z", "target_mz", "xic_mz"]),
120    ("q1", &["q1", "q1_mz"]),
121    ("q3", &["q3", "q3_mz", "product_mz"]),
122    (
123        "rt_min",
124        &[
125            "rt",
126            "rt_min",
127            "retention_time",
128            "expected_rt",
129            "expected_rt_min",
130        ],
131    ),
132    (
133        "rt_window_min",
134        &[
135            "window",
136            "rt_window",
137            "rt_window_min",
138            "rt_tolerance",
139            "window_min",
140        ],
141    ),
142    ("ppm", &["ppm", "tolerance_ppm", "mz_tolerance_ppm"]),
143    ("da", &["da", "tolerance_da", "mz_tolerance_da"]),
144    ("polarity", &["polarity"]),
145    ("ms_level", &["ms_level", "mslevel"]),
146    ("precursor_mz", &["precursor", "precursor_mz"]),
147    ("trace", &["trace"]),
148    ("channel", &["channel"]),
149];
150
151fn canonical(header: &str) -> Option<&'static str> {
152    let h = header.trim().to_ascii_lowercase().replace([' ', '-'], "_");
153    COLUMNS
154        .iter()
155        .find(|(_, names)| names.contains(&h.as_str()))
156        .map(|(c, _)| *c)
157}
158
159fn accepted() -> String {
160    COLUMNS
161        .iter()
162        .map(|(c, _)| *c)
163        .collect::<Vec<_>>()
164        .join(", ")
165}
166
167/// Split one CSV/TSV line (double quotes group fields; `""` is a quote).
168fn split_line(line: &str, delim: char) -> Vec<String> {
169    let mut out = Vec::new();
170    let mut cur = String::new();
171    let mut quoted = false;
172    let mut chars = line.chars().peekable();
173    while let Some(c) = chars.next() {
174        match c {
175            '"' if quoted && chars.peek() == Some(&'"') => {
176                cur.push('"');
177                chars.next();
178            }
179            '"' => quoted = !quoted,
180            c if c == delim && !quoted => out.push(std::mem::take(&mut cur).trim().to_string()),
181            c => cur.push(c),
182        }
183    }
184    out.push(cur.trim().to_string());
185    out
186}
187
188fn set_field(c: &mut Compound, col: &str, v: &str, line: usize) -> Result<()> {
189    if v.is_empty() {
190        return Ok(());
191    }
192    let f = || -> Result<f64> {
193        v.parse::<f64>()
194            .ok()
195            .filter(|x| x.is_finite())
196            .ok_or_else(|| {
197                Error::Usage(format!(
198                    "compound list line {line}: `{col}` is not a number: `{v}`"
199                ))
200            })
201    };
202    let u = || -> Result<u32> {
203        v.parse::<u32>().map_err(|_| {
204            Error::Usage(format!(
205                "compound list line {line}: `{col}` is not a whole number: `{v}`"
206            ))
207        })
208    };
209    match col {
210        "name" => c.name = v.to_string(),
211        "mz" => c.mz = Some(f()?),
212        "q1" => c.q1 = Some(f()?),
213        "q3" => c.q3 = Some(f()?),
214        "rt_min" => c.rt_min = Some(f()?),
215        "rt_window_min" => c.rt_window_min = Some(f()?),
216        "ppm" => c.ppm = Some(f()?),
217        "da" => c.da = Some(f()?),
218        "polarity" => c.polarity = Some(v.parse()?),
219        "ms_level" => c.ms_level = Some(u()?),
220        "precursor_mz" => c.precursor_mz = Some(f()?),
221        "trace" => c.trace = Some(u()?),
222        "channel" => c.channel = Some(u()?),
223        _ => {}
224    }
225    Ok(())
226}
227
228/// Parse a compound list: JSON when the text starts with `[` or `{`, otherwise CSV (or TSV when
229/// the header contains a tab). Lines starting with `#` and blank lines are skipped.
230pub fn parse_compounds(text: &str) -> Result<Vec<Compound>> {
231    let trimmed = text.trim_start_matches('\u{feff}').trim_start();
232    let list = if trimmed.starts_with('[') || trimmed.starts_with('{') {
233        parse_json(trimmed)?
234    } else {
235        parse_delimited(trimmed)?
236    };
237    if list.is_empty() {
238        return Err(Error::Usage("the compound list is empty".into()));
239    }
240    for (i, c) in list.iter().enumerate() {
241        check(c, i + 1)?;
242    }
243    Ok(list)
244}
245
246fn parse_json(text: &str) -> Result<Vec<Compound>> {
247    let v: serde_json::Value = serde_json::from_str(text)
248        .map_err(|e| Error::Usage(format!("compound list is not valid JSON: {e}")))?;
249    let arr = match &v {
250        serde_json::Value::Array(a) => a.clone(),
251        serde_json::Value::Object(o) => o
252            .get("compounds")
253            .and_then(|c| c.as_array())
254            .cloned()
255            .ok_or_else(|| {
256                Error::Usage("a JSON compound list is an array or {\"compounds\": [...]}".into())
257            })?,
258        _ => {
259            return Err(Error::Usage(
260                "a JSON compound list is an array of objects".into(),
261            ));
262        }
263    };
264    let mut out = Vec::new();
265    for (i, item) in arr.iter().enumerate() {
266        let obj = item
267            .as_object()
268            .ok_or_else(|| Error::Usage(format!("compound {}: not an object", i + 1)))?;
269        let mut c = Compound::default();
270        for (k, val) in obj {
271            let col = canonical(k).ok_or_else(|| {
272                Error::Usage(format!(
273                    "compound {}: unknown field `{k}` (accepted: {})",
274                    i + 1,
275                    accepted()
276                ))
277            })?;
278            let s = match val {
279                serde_json::Value::String(s) => s.clone(),
280                serde_json::Value::Null => String::new(),
281                other => other.to_string(),
282            };
283            set_field(&mut c, col, &s, i + 1)?;
284        }
285        out.push(c);
286    }
287    Ok(out)
288}
289
290fn parse_delimited(text: &str) -> Result<Vec<Compound>> {
291    let mut lines = text
292        .lines()
293        .enumerate()
294        .filter(|(_, l)| !l.trim().is_empty() && !l.trim_start().starts_with('#'));
295    let Some((_, header)) = lines.next() else {
296        return Ok(Vec::new());
297    };
298    let delim = if header.contains('\t') {
299        '\t'
300    } else if header.contains(';') && !header.contains(',') {
301        ';'
302    } else {
303        ','
304    };
305    let cols: Vec<&'static str> = split_line(header, delim)
306        .iter()
307        .map(|h| {
308            canonical(h).ok_or_else(|| {
309                Error::Usage(format!(
310                    "compound list: unknown column `{h}` (accepted: {})",
311                    accepted()
312                ))
313            })
314        })
315        .collect::<Result<_>>()?;
316    let mut out = Vec::new();
317    for (n, line) in lines {
318        let mut c = Compound::default();
319        for (col, v) in cols.iter().zip(split_line(line, delim)) {
320            set_field(&mut c, col, &v, n + 1)?;
321        }
322        out.push(c);
323    }
324    Ok(out)
325}
326
327fn check(c: &Compound, i: usize) -> Result<()> {
328    if c.name.trim().is_empty() {
329        return Err(Error::Usage(format!("compound {i}: `name` is required")));
330    }
331    if c.q1.is_some() != c.q3.is_some() {
332        return Err(Error::Usage(format!(
333            "compound {i} ({}): give both q1 and q3 for a transition",
334            c.name
335        )));
336    }
337    if c.mz.is_some() && c.q1.is_some() {
338        return Err(Error::Usage(format!(
339            "compound {i} ({}): give either mz or q1/q3, not both",
340            c.name
341        )));
342    }
343    if c.ppm.is_some() && c.da.is_some() {
344        return Err(Error::Usage(format!(
345            "compound {i} ({}): give either ppm or da, not both",
346            c.name
347        )));
348    }
349    for (v, what) in [
350        (c.mz, "mz"),
351        (c.q1, "q1"),
352        (c.q3, "q3"),
353        (c.ppm, "ppm"),
354        (c.da, "da"),
355        (c.precursor_mz, "precursor"),
356    ] {
357        if v.is_some_and(|x| x <= 0.0) {
358            return Err(Error::Usage(format!(
359                "compound {i} ({}): {what} must be > 0",
360                c.name
361            )));
362        }
363    }
364    if c.rt_window_min.is_some_and(|w| w <= 0.0) {
365        return Err(Error::Usage(format!(
366            "compound {i} ({}): the window must be > 0 minutes",
367            c.name
368        )));
369    }
370    Ok(())
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn csv_tsv_and_json() {
379        let csv = "# method\nName,m/z,RT,window,ppm\n\"caffeine, std\",195.0877,5.3,0.2,5\nIS,198.1,5.3,,\n";
380        let c = parse_compounds(csv).unwrap();
381        assert_eq!(c.len(), 2);
382        assert_eq!(c[0].name, "caffeine, std");
383        assert_eq!(c[0].mz, Some(195.0877));
384        assert_eq!(c[0].rt_window_min, Some(0.2));
385        assert_eq!(c[1].rt_window_min, None);
386        let tsv = "name\tq1\tq3\trt\nPGE2\t351.2\t271.2\t12.1\n";
387        let c = parse_compounds(tsv).unwrap();
388        assert_eq!((c[0].q1, c[0].q3), (Some(351.2), Some(271.2)));
389        let json = r#"[{"name": "A", "mz": 100.5, "polarity": "negative", "rt": 3}]"#;
390        let c = parse_compounds(json).unwrap();
391        assert_eq!(c[0].polarity, Some(Polarity::Negative));
392        assert_eq!(c[0].rt_min, Some(3.0));
393        let c = parse_compounds(r#"{"compounds": [{"name": "B", "trace": 1}]}"#).unwrap();
394        assert_eq!(c[0].trace, Some(1));
395    }
396
397    #[test]
398    fn errors_name_the_problem() {
399        let e = parse_compounds("name,mzz\nA,1\n").unwrap_err();
400        assert!(e.to_string().contains("mzz"), "{e}");
401        assert_eq!(e.exit_code(), 2);
402        assert!(parse_compounds("name,mz\nA,abc\n").is_err());
403        assert!(parse_compounds("name,q1\nA,100\n").is_err());
404        assert!(parse_compounds("mz\n100\n").is_err());
405        assert!(parse_compounds("").is_err());
406        assert!(parse_compounds("[1]").is_err());
407    }
408}