Skip to main content

openreadout_core/
scans.rs

1//! Header-only listing of the spectra (scans) of a mass-spectrometry run: scan number, MS level,
2//! retention time, polarity, precursor m/z and charge, isolation window, activation, filter
3//! string, and the instrument's stored TIC/base peak where the file keeps them, without decoding
4//! any peak arrays.
5//!
6//! Readers stream headers through [`Dataset::visit_scan_headers`]; readers without a
7//! header-only path fall back to decoding each spectrum ([`visit_scans`] does that
8//! transparently, and says so in [`ScanList::source`]). [`ScanFilter`] selects scans (MS level,
9//! polarity, retention-time window, precursor m/z within a tolerance, charge, activation, filter
10//! substring); [`list_scans`] counts every match and returns one page of them.
11
12use std::collections::BTreeMap;
13
14use schemars::JsonSchema;
15use serde::{Deserialize, Serialize};
16
17use crate::reader::{Dataset, SpectrumView};
18use crate::{Error, Result, Spectrum};
19
20/// Everything about one spectrum except its peaks.
21#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
22pub struct ScanHeader {
23    /// Zero-based spectrum index within its run (`spectrum --spectrum`).
24    pub index: u64,
25    /// Scan number as the instrument counts it (`spectrum --scan`).
26    pub scan_number: u64,
27    /// The spectrum's identifier in its file (mzML `id`), when it has one.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub native_id: Option<String>,
30    /// MS level: 1 for a full scan, 2 for a fragment (MS/MS) scan, and so on.
31    pub ms_level: u32,
32    /// Retention time in seconds; null when the file states none for this scan (such a scan
33    /// never matches a retention-time filter).
34    #[serde(default)]
35    pub rt_s: Option<f64>,
36    /// `positive`, `negative` or `unknown`.
37    pub polarity: String,
38    /// True when the stored peaks are centroids.
39    pub centroided: bool,
40    /// m/z of the isolated precursor ion (MS2 and above).
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub precursor_mz: Option<f64>,
43    /// Charge state of the precursor, when the instrument determined it.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub precursor_charge: Option<i32>,
46    /// Intensity of the selected precursor ion, when recorded.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub precursor_intensity: Option<f64>,
49    /// Precursor isolation window `[lower, upper]` in m/z.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub isolation_window_mz: Option<[f64; 2]>,
52    /// Dissociation method (`CID`, `HCD`, `ETD`, ...), upper case.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub activation: Option<String>,
55    /// Collision energy as recorded.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub collision_energy: Option<f64>,
58    /// Ion mobility 1/K0 in V·s/cm², when the scan or precursor has one.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub inverse_reduced_mobility: Option<f64>,
61    /// Instrument scan filter or scan description (e.g. Thermo `FTMS + p ESI d Full ms2 …`).
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub scan_filter: Option<String>,
64    /// Scan (acquisition) window `[lower, upper]` in m/z.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub scan_window_mz: Option<[f64; 2]>,
67    /// Total ion current as the file records it for the scan (an index or header value; not
68    /// recomputed from the peaks). Absent when the file keeps none.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub total_ion_current: Option<f64>,
71    /// Base-peak m/z as the file records it for the scan.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub base_peak_mz: Option<f64>,
74    /// Base-peak intensity as the file records it for the scan.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub base_peak_intensity: Option<f64>,
77    /// Number of stored points (peaks or profile samples), when the header records it.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub point_count: Option<u64>,
80    /// Format-specific scan metadata in the reader's documented vocabulary.
81    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
82    pub extra: BTreeMap<String, serde_json::Value>,
83}
84
85impl From<Spectrum> for ScanHeader {
86    fn from(s: Spectrum) -> Self {
87        let point_count = if s.mz.is_empty() {
88            None
89        } else {
90            Some(s.mz.len() as u64)
91        };
92        ScanHeader {
93            index: s.index,
94            scan_number: s.scan_number,
95            native_id: s.native_id,
96            ms_level: s.ms_level,
97            rt_s: s.rt_s,
98            polarity: s.polarity,
99            centroided: s.centroided,
100            precursor_mz: s.precursor_mz,
101            precursor_charge: s.precursor_charge,
102            precursor_intensity: s.precursor_intensity,
103            isolation_window_mz: s.isolation_window_mz,
104            activation: s.activation,
105            collision_energy: s.collision_energy,
106            inverse_reduced_mobility: s.inverse_reduced_mobility,
107            scan_filter: s.scan_filter,
108            scan_window_mz: s.scan_window_mz,
109            total_ion_current: s.total_ion_current,
110            base_peak_mz: s.base_peak_mz,
111            base_peak_intensity: s.base_peak_intensity,
112            point_count,
113            extra: s.extra,
114        }
115    }
116}
117
118/// Which scans to list. Every condition that is set must hold.
119#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
120pub struct ScanFilter {
121    /// Only this MS level (1 = full scans, 2 = MS/MS).
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub ms_level: Option<u32>,
124    /// Only `positive` or `negative` scans.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub polarity: Option<String>,
127    /// Retention time at least this many seconds.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub rt_min_s: Option<f64>,
130    /// Retention time at most this many seconds.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub rt_max_s: Option<f64>,
133    /// Precursor m/z near this value (within `precursor_tol_mz`, or `precursor_tol_ppm`).
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub precursor_mz: Option<f64>,
136    /// Absolute precursor tolerance in m/z (default 0.01 when neither tolerance is given).
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub precursor_tol_mz: Option<f64>,
139    /// Relative precursor tolerance in ppm.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub precursor_tol_ppm: Option<f64>,
142    /// Only precursors of this charge state.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub charge: Option<i32>,
145    /// Only this activation (`HCD`, `CID`, ...; case-insensitive).
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub activation: Option<String>,
148    /// Only scans whose filter string contains this text (case-insensitive).
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub filter_contains: Option<String>,
151}
152
153/// Default precursor tolerance (m/z) when a precursor is given without one.
154pub const DEFAULT_PRECURSOR_TOL_MZ: f64 = 0.01;
155
156impl ScanFilter {
157    /// Is any condition set?
158    pub fn is_empty(&self) -> bool {
159        *self == ScanFilter::default()
160    }
161
162    /// Check the conditions for consistency (a usage error names the problem).
163    pub fn validate(&self) -> Result<()> {
164        if let Some(p) = &self.polarity
165            && !matches!(p.as_str(), "positive" | "negative" | "unknown")
166        {
167            return Err(Error::Usage(format!(
168                "polarity `{p}`: use positive, negative or unknown"
169            )));
170        }
171        if let (Some(a), Some(b)) = (self.rt_min_s, self.rt_max_s)
172            && a > b
173        {
174            return Err(Error::Usage(format!(
175                "retention-time window {a}–{b} s is empty (minimum above maximum)"
176            )));
177        }
178        if self.precursor_tol_mz.is_some() && self.precursor_tol_ppm.is_some() {
179            return Err(Error::Usage(
180                "give the precursor tolerance in m/z or in ppm, not both".into(),
181            ));
182        }
183        for (name, v) in [
184            ("precursor tolerance", self.precursor_tol_mz),
185            ("precursor ppm tolerance", self.precursor_tol_ppm),
186        ] {
187            if v.is_some_and(|v| !(v.is_finite() && v >= 0.0)) {
188                return Err(Error::Usage(format!(
189                    "{name} must be a non-negative number"
190                )));
191            }
192        }
193        Ok(())
194    }
195
196    /// Does the scan pass every condition?
197    pub fn matches(&self, h: &ScanHeader) -> bool {
198        if self.ms_level.is_some_and(|l| l != h.ms_level) {
199            return false;
200        }
201        if self.polarity.as_ref().is_some_and(|p| *p != h.polarity) {
202            return false;
203        }
204        if (self.rt_min_s.is_some() || self.rt_max_s.is_some())
205            && !h.rt_s.is_some_and(|rt| {
206                self.rt_min_s.is_none_or(|t| rt >= t) && self.rt_max_s.is_none_or(|t| rt <= t)
207            })
208        {
209            return false;
210        }
211        if let Some(target) = self.precursor_mz {
212            let tol = match (self.precursor_tol_ppm, self.precursor_tol_mz) {
213                (Some(ppm), _) => target.abs() * ppm * 1e-6,
214                (None, Some(t)) => t,
215                (None, None) => DEFAULT_PRECURSOR_TOL_MZ,
216            };
217            if !h.precursor_mz.is_some_and(|p| (p - target).abs() <= tol) {
218                return false;
219            }
220        }
221        if self.charge.is_some_and(|z| h.precursor_charge != Some(z)) {
222            return false;
223        }
224        if let Some(a) = &self.activation
225            && !h
226                .activation
227                .as_ref()
228                .is_some_and(|x| x.eq_ignore_ascii_case(a))
229        {
230            return false;
231        }
232        if let Some(t) = &self.filter_contains {
233            let t = t.to_ascii_lowercase();
234            if !h
235                .scan_filter
236                .as_ref()
237                .is_some_and(|f| f.to_ascii_lowercase().contains(&t))
238            {
239                return false;
240            }
241        }
242        true
243    }
244}
245
246/// Output of `scans`: the matching scans of one run, one page of them listed.
247#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
248pub struct ScanList {
249    /// The input file.
250    pub path: String,
251    /// Format id of the input file.
252    pub format: String,
253    /// Run index.
254    pub run: u32,
255    /// Spectra in the run.
256    pub scan_count: u64,
257    /// `headers` when the reader listed scan headers without decoding peaks, `spectra` when
258    /// every spectrum had to be decoded to list it.
259    pub source: String,
260    /// The conditions applied (omitted when every scan is listed).
261    #[serde(default, skip_serializing_if = "ScanFilter::is_empty")]
262    pub filter: ScanFilter,
263    /// Scans matching the conditions (all of them are counted, not only the page listed).
264    pub matched: u64,
265    /// Position of the first listed scan among the matching ones (0-based; `--offset`).
266    pub offset: u64,
267    /// Number of scans listed.
268    pub returned: u64,
269    /// True when more matching scans follow the page (`offset + returned < matched`).
270    pub truncated: bool,
271    /// Counts of the matching scans per MS level (`"1"`, `"2"`, ...).
272    pub ms_level_counts: BTreeMap<String, u64>,
273    /// Retention-time range of the matching scans in seconds.
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub rt_range_s: Option<[f64; 2]>,
276    /// The listed scans, in spectrum-index order.
277    pub scans: Vec<ScanHeader>,
278}
279
280/// How [`visit_scans`] obtained the headers.
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
282pub enum HeaderSource {
283    /// The reader's header-only path (no peaks decoded).
284    Headers,
285    /// Every spectrum decoded (the reader has no header-only path).
286    Spectra,
287}
288
289impl HeaderSource {
290    /// `headers` or `spectra`.
291    pub fn name(self) -> &'static str {
292        match self {
293            HeaderSource::Headers => "headers",
294            HeaderSource::Spectra => "spectra",
295        }
296    }
297}
298
299/// Visit the header of every spectrum of run `run` in index order, through the reader's
300/// header-only path when it has one, else by decoding each spectrum (the run's `scan_count`
301/// from `info` bounds that walk; a file without that run is a usage error). `visit` returns
302/// false to stop early.
303pub fn visit_scans(
304    ds: &mut dyn Dataset,
305    run: u32,
306    visit: &mut dyn FnMut(ScanHeader) -> bool,
307) -> Result<HeaderSource> {
308    if ds.visit_scan_headers(run, 0, visit)? {
309        return Ok(HeaderSource::Headers);
310    }
311    let scan_count = run_scan_count(ds, run)?;
312    for i in 0..scan_count {
313        let mut s = ds.read_spectrum_view(run, i, SpectrumView::Primary)?;
314        let n = s.mz.len() as u64;
315        s.mz = Vec::new();
316        s.intensity = Vec::new();
317        let mut h = ScanHeader::from(s);
318        h.point_count = Some(n);
319        if !visit(h) {
320            break;
321        }
322    }
323    Ok(HeaderSource::Spectra)
324}
325
326/// Number of spectra of run `run` (`info` → `spectra[run].scan_count`), or a usage error
327/// naming what the file holds.
328pub(crate) fn run_scan_count(ds: &mut dyn Dataset, run: u32) -> Result<u64> {
329    let info = ds.info()?;
330    info.spectra
331        .iter()
332        .find(|s| s.index == run)
333        .map(|s| s.scan_count)
334        .ok_or_else(|| {
335            if info.spectra.is_empty() {
336                Error::Usage(format!(
337                    "{} holds no mass spectra (`info` lists what it holds)",
338                    info.path
339                ))
340            } else {
341                Error::Usage(format!(
342                    "run {run} out of range ({} run{})",
343                    info.spectra.len(),
344                    if info.spectra.len() == 1 { "" } else { "s" }
345                ))
346            }
347        })
348}
349
350/// The scans of run `run` matching `filter`: all of them counted (per MS level, RT range), the
351/// `limit` matches from the `offset`-th listed. `ScanPage::scanned` is the run's scan count.
352pub fn list_scans(
353    ds: &mut dyn Dataset,
354    run: u32,
355    filter: &ScanFilter,
356    offset: u64,
357    limit: u64,
358) -> Result<(HeaderSource, ScanPage)> {
359    filter.validate()?;
360    let mut page = ScanPage::default();
361    let src = visit_scans(ds, run, &mut |h| {
362        page.scanned += 1;
363        if !filter.matches(&h) {
364            return true;
365        }
366        page.add(h, offset, limit);
367        true
368    })?;
369    Ok((src, page))
370}
371
372/// [`list_scans`] as the `scans` output: `path` and `format` name the input.
373pub fn scan_list(
374    ds: &mut dyn Dataset,
375    path: &str,
376    format: &str,
377    run: u32,
378    filter: &ScanFilter,
379    offset: u64,
380    limit: u64,
381) -> Result<ScanList> {
382    let (src, page) = list_scans(ds, run, filter, offset, limit)?;
383    let returned = page.scans.len() as u64;
384    Ok(ScanList {
385        path: path.to_string(),
386        format: format.to_string(),
387        run,
388        scan_count: page.scanned,
389        source: src.name().into(),
390        filter: filter.clone(),
391        matched: page.matched,
392        offset,
393        returned,
394        truncated: offset.saturating_add(returned) < page.matched,
395        ms_level_counts: page.ms_level_counts,
396        rt_range_s: page.rt_range_s,
397        scans: page.scans,
398    })
399}
400
401/// Matching scans counted and one page of them kept (see [`list_scans`]).
402#[derive(Debug, Clone, Default)]
403pub struct ScanPage {
404    /// Scans visited (every scan of the run, once the walk is complete).
405    pub scanned: u64,
406    /// Scans matched.
407    pub matched: u64,
408    /// Counts per MS level.
409    pub ms_level_counts: BTreeMap<String, u64>,
410    /// Retention-time range of the matches in seconds.
411    pub rt_range_s: Option<[f64; 2]>,
412    /// The page.
413    pub scans: Vec<ScanHeader>,
414}
415
416impl ScanPage {
417    /// Count a matching scan and keep it when it falls in the page `offset..offset + limit`.
418    pub fn add(&mut self, h: ScanHeader, offset: u64, limit: u64) {
419        *self
420            .ms_level_counts
421            .entry(h.ms_level.to_string())
422            .or_insert(0) += 1;
423        if let Some(rt) = h.rt_s.filter(|t| t.is_finite()) {
424            self.rt_range_s = Some(match self.rt_range_s {
425                Some([a, b]) => [a.min(rt), b.max(rt)],
426                None => [rt, rt],
427            });
428        }
429        if self.matched >= offset && self.matched - offset < limit {
430            self.scans.push(h);
431        }
432        self.matched += 1;
433    }
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439
440    fn h(index: u64, ms_level: u32, rt_s: f64, mz: Option<f64>, z: Option<i32>) -> ScanHeader {
441        ScanHeader {
442            index,
443            scan_number: index + 1,
444            ms_level,
445            rt_s: Some(rt_s),
446            polarity: "positive".into(),
447            precursor_mz: mz,
448            precursor_charge: z,
449            activation: mz.map(|_| "HCD".into()),
450            scan_filter: Some(if ms_level == 1 {
451                "FTMS + p ESI Full ms [100-1000]".into()
452            } else {
453                "FTMS + c ESI d Full ms2 500.25@hcd30.00".into()
454            }),
455            ..ScanHeader::default()
456        }
457    }
458
459    #[test]
460    fn filters_combine() {
461        let scans = [
462            h(0, 1, 10.0, None, None),
463            h(1, 2, 10.5, Some(500.25), Some(2)),
464            h(2, 2, 11.0, Some(500.2551), Some(3)),
465            h(3, 2, 30.0, Some(612.3), Some(3)),
466        ];
467        let f = ScanFilter {
468            ms_level: Some(2),
469            charge: Some(3),
470            ..ScanFilter::default()
471        };
472        assert_eq!(scans.iter().filter(|s| f.matches(s)).count(), 2);
473        let f = ScanFilter {
474            precursor_mz: Some(500.25),
475            ..ScanFilter::default()
476        };
477        assert_eq!(scans.iter().filter(|s| f.matches(s)).count(), 2);
478        let f = ScanFilter {
479            precursor_mz: Some(500.25),
480            precursor_tol_ppm: Some(5.0),
481            ..ScanFilter::default()
482        };
483        assert_eq!(scans.iter().filter(|s| f.matches(s)).count(), 1);
484        let f = ScanFilter {
485            rt_min_s: Some(10.2),
486            rt_max_s: Some(20.0),
487            activation: Some("hcd".into()),
488            filter_contains: Some("MS2".into()),
489            ..ScanFilter::default()
490        };
491        assert_eq!(scans.iter().filter(|s| f.matches(s)).count(), 2);
492        assert!(
493            ScanFilter {
494                rt_min_s: Some(5.0),
495                rt_max_s: Some(1.0),
496                ..ScanFilter::default()
497            }
498            .validate()
499            .is_err()
500        );
501        assert!(
502            ScanFilter {
503                polarity: Some("pos".into()),
504                ..ScanFilter::default()
505            }
506            .validate()
507            .is_err()
508        );
509    }
510
511    #[test]
512    fn pages_count_every_match() {
513        let mut p = ScanPage::default();
514        for i in 0..10 {
515            p.add(h(i, 1 + (i % 2) as u32, i as f64, None, None), 3, 4);
516        }
517        assert_eq!(p.matched, 10);
518        assert_eq!(
519            p.scans.iter().map(|s| s.index).collect::<Vec<_>>(),
520            [3, 4, 5, 6]
521        );
522        assert_eq!(p.ms_level_counts["1"], 5);
523        assert_eq!(p.rt_range_s, Some([0.0, 9.0]));
524    }
525
526    /// A scan whose file states no retention time: listed with a null time, left out of the
527    /// time range, and never matched by a retention-time window.
528    #[test]
529    fn absent_retention_time() {
530        let mut none = h(5, 1, 0.0, None, None);
531        none.rt_s = None;
532        let f = ScanFilter {
533            rt_min_s: Some(-1.0),
534            ..ScanFilter::default()
535        };
536        assert!(!f.matches(&none));
537        assert!(ScanFilter::default().matches(&none));
538        let mut p = ScanPage::default();
539        p.add(h(0, 1, 12.0, None, None), 0, 10);
540        p.add(none.clone(), 0, 10);
541        assert_eq!(p.rt_range_s, Some([12.0, 12.0]));
542        assert_eq!(p.matched, 2);
543        let json = serde_json::to_value(&none).unwrap();
544        assert!(json["rt_s"].is_null(), "{json}");
545    }
546}
547
548/// The spectrum of MS level `ms_level` in run `run` whose retention time is nearest `rt_s`:
549/// `(index, scan number, retention time in s)`, or `None` when no such scan has a retention time.
550pub fn nearest_scan(
551    ds: &mut dyn Dataset,
552    run: u32,
553    rt_s: f64,
554    ms_level: u32,
555) -> Result<Option<(u64, u64, f64)>> {
556    let mut best: Option<(u64, u64, f64)> = None;
557    visit_scans(ds, run, &mut |h| {
558        if h.ms_level == ms_level
559            && let Some(t) = h.rt_s
560            && best.is_none_or(|b| (t - rt_s).abs() < (b.2 - rt_s).abs())
561        {
562            best = Some((h.index, h.scan_number, t));
563        }
564        true
565    })?;
566    Ok(best)
567}
568
569/// Mass difference between the ¹³C and ¹²C isotopes, Da.
570pub const ISOTOPE_SPACING_DA: f64 = 1.003_355;
571/// Mass of a proton, Da.
572pub const PROTON_DA: f64 = 1.007_276;
573
574/// One of the most intense peaks of a mass spectrum, with its charge from the isotope pattern.
575#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
576pub struct MsPeak {
577    /// m/z.
578    pub mz: f64,
579    /// Intensity.
580    pub intensity: f64,
581    /// Charge from the spacing of the isotope peaks above it (1.00336/z), when at least one
582    /// is found.
583    #[serde(skip_serializing_if = "Option::is_none")]
584    pub charge: Option<u32>,
585    /// Isotope peaks found in a row above this one at that spacing.
586    #[serde(skip_serializing_if = "Option::is_none")]
587    pub isotopes: Option<u32>,
588    /// m/z of the lowest peak of the same isotope pattern (the monoisotopic ion when it is
589    /// seen), when it is below this one.
590    #[serde(skip_serializing_if = "Option::is_none")]
591    pub monoisotopic_mz: Option<f64>,
592    /// Neutral monoisotopic mass (z · (m/z ∓ proton)), Da, when the charge and polarity are
593    /// known.
594    #[serde(skip_serializing_if = "Option::is_none")]
595    pub neutral_mass_da: Option<f64>,
596}
597
598/// The centroids of a spectrum: the stored points when centroided, else the local maxima of
599/// the profile.
600fn centroids(sp: &Spectrum) -> Vec<(f64, f64)> {
601    let n = sp.mz.len().min(sp.intensity.len());
602    if sp.centroided {
603        return (0..n)
604            .filter(|&i| sp.intensity[i] > 0.0)
605            .map(|i| (sp.mz[i], f64::from(sp.intensity[i])))
606            .collect();
607    }
608    (0..n)
609        .filter(|&i| {
610            let y = sp.intensity[i];
611            y > 0.0
612                && (i == 0 || sp.intensity[i - 1] < y)
613                && (i + 1 == n || sp.intensity[i + 1] <= y)
614        })
615        .map(|i| (sp.mz[i], f64::from(sp.intensity[i])))
616        .collect()
617}
618
619/// The `n` most intense peaks of `sp`, each with the charge its isotope pattern shows. A peak
620/// inside the isotope pattern of a more intense one already listed is left out.
621pub fn top_peaks(sp: &Spectrum, n: usize) -> Vec<MsPeak> {
622    let c = centroids(sp);
623    if c.is_empty() || n == 0 {
624        return Vec::new();
625    }
626    let mut by_mz = c.clone();
627    by_mz.sort_by(|a, b| a.0.total_cmp(&b.0));
628    let tol = |mz: f64| (mz * 15e-6).max(0.003);
629    let find = |mz: f64, min_i: f64| -> bool {
630        let t = tol(mz);
631        let lo = by_mz.partition_point(|p| p.0 < mz - t);
632        by_mz[lo..]
633            .iter()
634            .take_while(|p| p.0 <= mz + t)
635            .any(|p| p.1 >= min_i)
636    };
637    let mut order = c;
638    order.sort_by(|a, b| b.1.total_cmp(&a.1));
639    let mut out: Vec<MsPeak> = Vec::new();
640    for (mz, intensity) in order {
641        if out.len() >= n {
642            break;
643        }
644        let inside = out.iter().any(|p| {
645            let z = f64::from(p.charge.unwrap_or(1));
646            let base = p.monoisotopic_mz.unwrap_or(p.mz);
647            (0..=8).any(|k| (mz - (base + f64::from(k) * ISOTOPE_SPACING_DA / z)).abs() <= tol(mz))
648        });
649        if inside {
650            continue;
651        }
652        let mut best: Option<(u32, u32)> = None;
653        for z in 1..=8u32 {
654            let mut k = 0;
655            while k < 6
656                && find(
657                    mz + f64::from(k + 1) * ISOTOPE_SPACING_DA / f64::from(z),
658                    intensity * 0.02,
659                )
660            {
661                k += 1;
662            }
663            if k > 0 && best.is_none_or(|b| k > b.1) {
664                best = Some((z, k));
665            }
666        }
667        let charge = best.map(|b| b.0);
668        // the lowest peak of the pattern: step down while the next lower isotope is there
669        let mut mono = mz;
670        if let Some(z) = charge {
671            let step = ISOTOPE_SPACING_DA / f64::from(z);
672            for _ in 0..6 {
673                if find(mono - step, intensity * 0.05) {
674                    mono -= step;
675                } else {
676                    break;
677                }
678            }
679        }
680        let neutral_mass_da = charge.and_then(|z| {
681            let z = f64::from(z);
682            match sp.polarity.as_str() {
683                "positive" => Some(z * (mono - PROTON_DA)),
684                "negative" => Some(z * (mono + PROTON_DA)),
685                _ => None,
686            }
687        });
688        out.push(MsPeak {
689            mz,
690            intensity,
691            charge,
692            isotopes: best.map(|b| b.1),
693            monoisotopic_mz: (mono < mz).then_some(mono),
694            neutral_mass_da,
695        });
696    }
697    out
698}
699
700/// Keep the `cap` most intense points of `sp`, in m/z order.
701pub fn keep_most_intense(sp: &mut Spectrum, cap: usize) {
702    let n = sp.mz.len().min(sp.intensity.len());
703    if n <= cap {
704        return;
705    }
706    let mut idx: Vec<usize> = (0..n).collect();
707    idx.sort_by(|&a, &b| sp.intensity[b].total_cmp(&sp.intensity[a]));
708    idx.truncate(cap);
709    idx.sort_unstable();
710    sp.mz = idx.iter().map(|&i| sp.mz[i]).collect();
711    sp.intensity = idx.iter().map(|&i| sp.intensity[i]).collect();
712}
713
714#[cfg(test)]
715mod peak_tests {
716    use super::*;
717
718    #[test]
719    fn charges_from_isotope_spacing() {
720        let mut sp = Spectrum {
721            centroided: true,
722            polarity: "positive".into(),
723            ..Spectrum::default()
724        };
725        // a 2+ ion at 500.0 with isotopes at +0.5017, +1.0034; a 1+ ion at 700.0 with one isotope
726        let pts = [
727            (500.0, 1000.0),
728            (500.0 + ISOTOPE_SPACING_DA / 2.0, 800.0),
729            (500.0 + ISOTOPE_SPACING_DA, 400.0),
730            (700.0, 600.0),
731            (700.0 + ISOTOPE_SPACING_DA, 300.0),
732            (800.0, 50.0),
733        ];
734        sp.mz = pts.iter().map(|p| p.0).collect();
735        sp.intensity = pts.iter().map(|p| p.1 as f32).collect();
736        let p = top_peaks(&sp, 3);
737        assert_eq!(p[0].charge, Some(2));
738        assert_eq!(p[0].isotopes, Some(2));
739        assert!((p[0].neutral_mass_da.unwrap() - 2.0 * (500.0 - PROTON_DA)).abs() < 1e-9);
740        assert_eq!(p[1].mz, 700.0);
741        assert_eq!(p[1].charge, Some(1));
742        assert_eq!(p[2].mz, 800.0);
743        assert_eq!(p[2].charge, None);
744        keep_most_intense(&mut sp, 2);
745        assert_eq!(sp.mz, vec![500.0, 500.0 + ISOTOPE_SPACING_DA / 2.0]);
746    }
747}