openreadout-core 0.4.0

Core traits, normalized metadata model, provenance tags, JSON output and exit codes for OpenReadout
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! Header-only listing of the spectra (scans) of a mass-spectrometry run: scan number, MS level,
//! retention time, polarity, precursor m/z and charge, isolation window, activation, filter
//! string, and the instrument's stored TIC/base peak where the file keeps them, without decoding
//! any peak arrays.
//!
//! Readers stream headers through [`Dataset::visit_scan_headers`]; readers without a
//! header-only path fall back to decoding each spectrum ([`visit_scans`] does that
//! transparently, and says so in [`ScanList::source`]). [`ScanFilter`] selects scans (MS level,
//! polarity, retention-time window, precursor m/z within a tolerance, charge, activation, filter
//! substring); [`list_scans`] counts every match and returns one page of them.

use std::collections::BTreeMap;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::reader::{Dataset, SpectrumView};
use crate::{Error, Result, Spectrum};

/// Everything about one spectrum except its peaks.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ScanHeader {
    /// Zero-based spectrum index within its run (`spectrum --spectrum`).
    pub index: u64,
    /// Scan number as the instrument counts it (`spectrum --scan`).
    pub scan_number: u64,
    /// The spectrum's identifier in its file (mzML `id`), when it has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_id: Option<String>,
    /// MS level: 1 for a full scan, 2 for a fragment (MS/MS) scan, and so on.
    pub ms_level: u32,
    /// Retention time in seconds; null when the file states none for this scan (such a scan
    /// never matches a retention-time filter).
    #[serde(default)]
    pub rt_s: Option<f64>,
    /// `positive`, `negative` or `unknown`.
    pub polarity: String,
    /// True when the stored peaks are centroids.
    pub centroided: bool,
    /// m/z of the isolated precursor ion (MS2 and above).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precursor_mz: Option<f64>,
    /// Charge state of the precursor, when the instrument determined it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precursor_charge: Option<i32>,
    /// Intensity of the selected precursor ion, when recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precursor_intensity: Option<f64>,
    /// Precursor isolation window `[lower, upper]` in m/z.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub isolation_window_mz: Option<[f64; 2]>,
    /// Dissociation method (`CID`, `HCD`, `ETD`, ...), upper case.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub activation: Option<String>,
    /// Collision energy as recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub collision_energy: Option<f64>,
    /// Ion mobility 1/K0 in V·s/cm², when the scan or precursor has one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inverse_reduced_mobility: Option<f64>,
    /// Instrument scan filter or scan description (e.g. Thermo `FTMS + p ESI d Full ms2 …`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scan_filter: Option<String>,
    /// Scan (acquisition) window `[lower, upper]` in m/z.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scan_window_mz: Option<[f64; 2]>,
    /// Total ion current as the file records it for the scan (an index or header value; not
    /// recomputed from the peaks). Absent when the file keeps none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub total_ion_current: Option<f64>,
    /// Base-peak m/z as the file records it for the scan.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_peak_mz: Option<f64>,
    /// Base-peak intensity as the file records it for the scan.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_peak_intensity: Option<f64>,
    /// Number of stored points (peaks or profile samples), when the header records it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub point_count: Option<u64>,
    /// Format-specific scan metadata in the reader's documented vocabulary.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, serde_json::Value>,
}

impl From<Spectrum> for ScanHeader {
    fn from(s: Spectrum) -> Self {
        let point_count = if s.mz.is_empty() {
            None
        } else {
            Some(s.mz.len() as u64)
        };
        ScanHeader {
            index: s.index,
            scan_number: s.scan_number,
            native_id: s.native_id,
            ms_level: s.ms_level,
            rt_s: s.rt_s,
            polarity: s.polarity,
            centroided: s.centroided,
            precursor_mz: s.precursor_mz,
            precursor_charge: s.precursor_charge,
            precursor_intensity: s.precursor_intensity,
            isolation_window_mz: s.isolation_window_mz,
            activation: s.activation,
            collision_energy: s.collision_energy,
            inverse_reduced_mobility: s.inverse_reduced_mobility,
            scan_filter: s.scan_filter,
            scan_window_mz: s.scan_window_mz,
            total_ion_current: s.total_ion_current,
            base_peak_mz: s.base_peak_mz,
            base_peak_intensity: s.base_peak_intensity,
            point_count,
            extra: s.extra,
        }
    }
}

/// Which scans to list. Every condition that is set must hold.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ScanFilter {
    /// Only this MS level (1 = full scans, 2 = MS/MS).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ms_level: Option<u32>,
    /// Only `positive` or `negative` scans.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub polarity: Option<String>,
    /// Retention time at least this many seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rt_min_s: Option<f64>,
    /// Retention time at most this many seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rt_max_s: Option<f64>,
    /// Precursor m/z near this value (within `precursor_tol_mz`, or `precursor_tol_ppm`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precursor_mz: Option<f64>,
    /// Absolute precursor tolerance in m/z (default 0.01 when neither tolerance is given).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precursor_tol_mz: Option<f64>,
    /// Relative precursor tolerance in ppm.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub precursor_tol_ppm: Option<f64>,
    /// Only precursors of this charge state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub charge: Option<i32>,
    /// Only this activation (`HCD`, `CID`, ...; case-insensitive).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub activation: Option<String>,
    /// Only scans whose filter string contains this text (case-insensitive).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub filter_contains: Option<String>,
}

/// Default precursor tolerance (m/z) when a precursor is given without one.
pub const DEFAULT_PRECURSOR_TOL_MZ: f64 = 0.01;

impl ScanFilter {
    /// Is any condition set?
    pub fn is_empty(&self) -> bool {
        *self == ScanFilter::default()
    }

    /// Check the conditions for consistency (a usage error names the problem).
    pub fn validate(&self) -> Result<()> {
        if let Some(p) = &self.polarity
            && !matches!(p.as_str(), "positive" | "negative" | "unknown")
        {
            return Err(Error::Usage(format!(
                "polarity `{p}`: use positive, negative or unknown"
            )));
        }
        if let (Some(a), Some(b)) = (self.rt_min_s, self.rt_max_s)
            && a > b
        {
            return Err(Error::Usage(format!(
                "retention-time window {a}–{b} s is empty (minimum above maximum)"
            )));
        }
        if self.precursor_tol_mz.is_some() && self.precursor_tol_ppm.is_some() {
            return Err(Error::Usage(
                "give the precursor tolerance in m/z or in ppm, not both".into(),
            ));
        }
        for (name, v) in [
            ("precursor tolerance", self.precursor_tol_mz),
            ("precursor ppm tolerance", self.precursor_tol_ppm),
        ] {
            if v.is_some_and(|v| !(v.is_finite() && v >= 0.0)) {
                return Err(Error::Usage(format!(
                    "{name} must be a non-negative number"
                )));
            }
        }
        Ok(())
    }

    /// Does the scan pass every condition?
    pub fn matches(&self, h: &ScanHeader) -> bool {
        if self.ms_level.is_some_and(|l| l != h.ms_level) {
            return false;
        }
        if self.polarity.as_ref().is_some_and(|p| *p != h.polarity) {
            return false;
        }
        if (self.rt_min_s.is_some() || self.rt_max_s.is_some())
            && !h.rt_s.is_some_and(|rt| {
                self.rt_min_s.is_none_or(|t| rt >= t) && self.rt_max_s.is_none_or(|t| rt <= t)
            })
        {
            return false;
        }
        if let Some(target) = self.precursor_mz {
            let tol = match (self.precursor_tol_ppm, self.precursor_tol_mz) {
                (Some(ppm), _) => target.abs() * ppm * 1e-6,
                (None, Some(t)) => t,
                (None, None) => DEFAULT_PRECURSOR_TOL_MZ,
            };
            if !h.precursor_mz.is_some_and(|p| (p - target).abs() <= tol) {
                return false;
            }
        }
        if self.charge.is_some_and(|z| h.precursor_charge != Some(z)) {
            return false;
        }
        if let Some(a) = &self.activation
            && !h
                .activation
                .as_ref()
                .is_some_and(|x| x.eq_ignore_ascii_case(a))
        {
            return false;
        }
        if let Some(t) = &self.filter_contains {
            let t = t.to_ascii_lowercase();
            if !h
                .scan_filter
                .as_ref()
                .is_some_and(|f| f.to_ascii_lowercase().contains(&t))
            {
                return false;
            }
        }
        true
    }
}

/// Output of `scans`: the matching scans of one run, one page of them listed.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ScanList {
    /// The input file.
    pub path: String,
    /// Format id of the input file.
    pub format: String,
    /// Run index.
    pub run: u32,
    /// Spectra in the run.
    pub scan_count: u64,
    /// `headers` when the reader listed scan headers without decoding peaks, `spectra` when
    /// every spectrum had to be decoded to list it.
    pub source: String,
    /// The conditions applied (omitted when every scan is listed).
    #[serde(default, skip_serializing_if = "ScanFilter::is_empty")]
    pub filter: ScanFilter,
    /// Scans matching the conditions (all of them are counted, not only the page listed).
    pub matched: u64,
    /// Position of the first listed scan among the matching ones (0-based; `--offset`).
    pub offset: u64,
    /// Number of scans listed.
    pub returned: u64,
    /// True when more matching scans follow the page (`offset + returned < matched`).
    pub truncated: bool,
    /// Counts of the matching scans per MS level (`"1"`, `"2"`, ...).
    pub ms_level_counts: BTreeMap<String, u64>,
    /// Retention-time range of the matching scans in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rt_range_s: Option<[f64; 2]>,
    /// The listed scans, in spectrum-index order.
    pub scans: Vec<ScanHeader>,
}

/// How [`visit_scans`] obtained the headers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeaderSource {
    /// The reader's header-only path (no peaks decoded).
    Headers,
    /// Every spectrum decoded (the reader has no header-only path).
    Spectra,
}

impl HeaderSource {
    /// `headers` or `spectra`.
    pub fn name(self) -> &'static str {
        match self {
            HeaderSource::Headers => "headers",
            HeaderSource::Spectra => "spectra",
        }
    }
}

/// Visit the header of every spectrum of run `run` in index order, through the reader's
/// header-only path when it has one, else by decoding each spectrum (the run's `scan_count`
/// from `info` bounds that walk; a file without that run is a usage error). `visit` returns
/// false to stop early.
pub fn visit_scans(
    ds: &mut dyn Dataset,
    run: u32,
    visit: &mut dyn FnMut(ScanHeader) -> bool,
) -> Result<HeaderSource> {
    if ds.visit_scan_headers(run, 0, visit)? {
        return Ok(HeaderSource::Headers);
    }
    let scan_count = run_scan_count(ds, run)?;
    for i in 0..scan_count {
        let mut s = ds.read_spectrum_view(run, i, SpectrumView::Primary)?;
        let n = s.mz.len() as u64;
        s.mz = Vec::new();
        s.intensity = Vec::new();
        let mut h = ScanHeader::from(s);
        h.point_count = Some(n);
        if !visit(h) {
            break;
        }
    }
    Ok(HeaderSource::Spectra)
}

/// Number of spectra of run `run` (`info` → `spectra[run].scan_count`), or a usage error
/// naming what the file holds.
pub(crate) fn run_scan_count(ds: &mut dyn Dataset, run: u32) -> Result<u64> {
    let info = ds.info()?;
    info.spectra
        .iter()
        .find(|s| s.index == run)
        .map(|s| s.scan_count)
        .ok_or_else(|| {
            if info.spectra.is_empty() {
                Error::Usage(format!(
                    "{} holds no mass spectra (`info` lists what it holds)",
                    info.path
                ))
            } else {
                Error::Usage(format!(
                    "run {run} out of range ({} run{})",
                    info.spectra.len(),
                    if info.spectra.len() == 1 { "" } else { "s" }
                ))
            }
        })
}

/// The scans of run `run` matching `filter`: all of them counted (per MS level, RT range), the
/// `limit` matches from the `offset`-th listed. `ScanPage::scanned` is the run's scan count.
pub fn list_scans(
    ds: &mut dyn Dataset,
    run: u32,
    filter: &ScanFilter,
    offset: u64,
    limit: u64,
) -> Result<(HeaderSource, ScanPage)> {
    filter.validate()?;
    let mut page = ScanPage::default();
    let src = visit_scans(ds, run, &mut |h| {
        page.scanned += 1;
        if !filter.matches(&h) {
            return true;
        }
        page.add(h, offset, limit);
        true
    })?;
    Ok((src, page))
}

/// [`list_scans`] as the `scans` output: `path` and `format` name the input.
pub fn scan_list(
    ds: &mut dyn Dataset,
    path: &str,
    format: &str,
    run: u32,
    filter: &ScanFilter,
    offset: u64,
    limit: u64,
) -> Result<ScanList> {
    let (src, page) = list_scans(ds, run, filter, offset, limit)?;
    let returned = page.scans.len() as u64;
    Ok(ScanList {
        path: path.to_string(),
        format: format.to_string(),
        run,
        scan_count: page.scanned,
        source: src.name().into(),
        filter: filter.clone(),
        matched: page.matched,
        offset,
        returned,
        truncated: offset.saturating_add(returned) < page.matched,
        ms_level_counts: page.ms_level_counts,
        rt_range_s: page.rt_range_s,
        scans: page.scans,
    })
}

/// Matching scans counted and one page of them kept (see [`list_scans`]).
#[derive(Debug, Clone, Default)]
pub struct ScanPage {
    /// Scans visited (every scan of the run, once the walk is complete).
    pub scanned: u64,
    /// Scans matched.
    pub matched: u64,
    /// Counts per MS level.
    pub ms_level_counts: BTreeMap<String, u64>,
    /// Retention-time range of the matches in seconds.
    pub rt_range_s: Option<[f64; 2]>,
    /// The page.
    pub scans: Vec<ScanHeader>,
}

impl ScanPage {
    /// Count a matching scan and keep it when it falls in the page `offset..offset + limit`.
    pub fn add(&mut self, h: ScanHeader, offset: u64, limit: u64) {
        *self
            .ms_level_counts
            .entry(h.ms_level.to_string())
            .or_insert(0) += 1;
        if let Some(rt) = h.rt_s.filter(|t| t.is_finite()) {
            self.rt_range_s = Some(match self.rt_range_s {
                Some([a, b]) => [a.min(rt), b.max(rt)],
                None => [rt, rt],
            });
        }
        if self.matched >= offset && self.matched - offset < limit {
            self.scans.push(h);
        }
        self.matched += 1;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn h(index: u64, ms_level: u32, rt_s: f64, mz: Option<f64>, z: Option<i32>) -> ScanHeader {
        ScanHeader {
            index,
            scan_number: index + 1,
            ms_level,
            rt_s: Some(rt_s),
            polarity: "positive".into(),
            precursor_mz: mz,
            precursor_charge: z,
            activation: mz.map(|_| "HCD".into()),
            scan_filter: Some(if ms_level == 1 {
                "FTMS + p ESI Full ms [100-1000]".into()
            } else {
                "FTMS + c ESI d Full ms2 500.25@hcd30.00".into()
            }),
            ..ScanHeader::default()
        }
    }

    #[test]
    fn filters_combine() {
        let scans = [
            h(0, 1, 10.0, None, None),
            h(1, 2, 10.5, Some(500.25), Some(2)),
            h(2, 2, 11.0, Some(500.2551), Some(3)),
            h(3, 2, 30.0, Some(612.3), Some(3)),
        ];
        let f = ScanFilter {
            ms_level: Some(2),
            charge: Some(3),
            ..ScanFilter::default()
        };
        assert_eq!(scans.iter().filter(|s| f.matches(s)).count(), 2);
        let f = ScanFilter {
            precursor_mz: Some(500.25),
            ..ScanFilter::default()
        };
        assert_eq!(scans.iter().filter(|s| f.matches(s)).count(), 2);
        let f = ScanFilter {
            precursor_mz: Some(500.25),
            precursor_tol_ppm: Some(5.0),
            ..ScanFilter::default()
        };
        assert_eq!(scans.iter().filter(|s| f.matches(s)).count(), 1);
        let f = ScanFilter {
            rt_min_s: Some(10.2),
            rt_max_s: Some(20.0),
            activation: Some("hcd".into()),
            filter_contains: Some("MS2".into()),
            ..ScanFilter::default()
        };
        assert_eq!(scans.iter().filter(|s| f.matches(s)).count(), 2);
        assert!(
            ScanFilter {
                rt_min_s: Some(5.0),
                rt_max_s: Some(1.0),
                ..ScanFilter::default()
            }
            .validate()
            .is_err()
        );
        assert!(
            ScanFilter {
                polarity: Some("pos".into()),
                ..ScanFilter::default()
            }
            .validate()
            .is_err()
        );
    }

    #[test]
    fn pages_count_every_match() {
        let mut p = ScanPage::default();
        for i in 0..10 {
            p.add(h(i, 1 + (i % 2) as u32, i as f64, None, None), 3, 4);
        }
        assert_eq!(p.matched, 10);
        assert_eq!(
            p.scans.iter().map(|s| s.index).collect::<Vec<_>>(),
            [3, 4, 5, 6]
        );
        assert_eq!(p.ms_level_counts["1"], 5);
        assert_eq!(p.rt_range_s, Some([0.0, 9.0]));
    }

    /// A scan whose file states no retention time: listed with a null time, left out of the
    /// time range, and never matched by a retention-time window.
    #[test]
    fn absent_retention_time() {
        let mut none = h(5, 1, 0.0, None, None);
        none.rt_s = None;
        let f = ScanFilter {
            rt_min_s: Some(-1.0),
            ..ScanFilter::default()
        };
        assert!(!f.matches(&none));
        assert!(ScanFilter::default().matches(&none));
        let mut p = ScanPage::default();
        p.add(h(0, 1, 12.0, None, None), 0, 10);
        p.add(none.clone(), 0, 10);
        assert_eq!(p.rt_range_s, Some([12.0, 12.0]));
        assert_eq!(p.matched, 2);
        let json = serde_json::to_value(&none).unwrap();
        assert!(json["rt_s"].is_null(), "{json}");
    }
}

/// The spectrum of MS level `ms_level` in run `run` whose retention time is nearest `rt_s`:
/// `(index, scan number, retention time in s)`, or `None` when no such scan has a retention time.
pub fn nearest_scan(
    ds: &mut dyn Dataset,
    run: u32,
    rt_s: f64,
    ms_level: u32,
) -> Result<Option<(u64, u64, f64)>> {
    let mut best: Option<(u64, u64, f64)> = None;
    visit_scans(ds, run, &mut |h| {
        if h.ms_level == ms_level
            && let Some(t) = h.rt_s
            && best.is_none_or(|b| (t - rt_s).abs() < (b.2 - rt_s).abs())
        {
            best = Some((h.index, h.scan_number, t));
        }
        true
    })?;
    Ok(best)
}

/// Mass difference between the ¹³C and ¹²C isotopes, Da.
pub const ISOTOPE_SPACING_DA: f64 = 1.003_355;
/// Mass of a proton, Da.
pub const PROTON_DA: f64 = 1.007_276;

/// One of the most intense peaks of a mass spectrum, with its charge from the isotope pattern.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct MsPeak {
    /// m/z.
    pub mz: f64,
    /// Intensity.
    pub intensity: f64,
    /// Charge from the spacing of the isotope peaks above it (1.00336/z), when at least one
    /// is found.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub charge: Option<u32>,
    /// Isotope peaks found in a row above this one at that spacing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub isotopes: Option<u32>,
    /// m/z of the lowest peak of the same isotope pattern (the monoisotopic ion when it is
    /// seen), when it is below this one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub monoisotopic_mz: Option<f64>,
    /// Neutral monoisotopic mass (z · (m/z ∓ proton)), Da, when the charge and polarity are
    /// known.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub neutral_mass_da: Option<f64>,
}

/// The centroids of a spectrum: the stored points when centroided, else the local maxima of
/// the profile.
fn centroids(sp: &Spectrum) -> Vec<(f64, f64)> {
    let n = sp.mz.len().min(sp.intensity.len());
    if sp.centroided {
        return (0..n)
            .filter(|&i| sp.intensity[i] > 0.0)
            .map(|i| (sp.mz[i], f64::from(sp.intensity[i])))
            .collect();
    }
    (0..n)
        .filter(|&i| {
            let y = sp.intensity[i];
            y > 0.0
                && (i == 0 || sp.intensity[i - 1] < y)
                && (i + 1 == n || sp.intensity[i + 1] <= y)
        })
        .map(|i| (sp.mz[i], f64::from(sp.intensity[i])))
        .collect()
}

/// The `n` most intense peaks of `sp`, each with the charge its isotope pattern shows. A peak
/// inside the isotope pattern of a more intense one already listed is left out.
pub fn top_peaks(sp: &Spectrum, n: usize) -> Vec<MsPeak> {
    let c = centroids(sp);
    if c.is_empty() || n == 0 {
        return Vec::new();
    }
    let mut by_mz = c.clone();
    by_mz.sort_by(|a, b| a.0.total_cmp(&b.0));
    let tol = |mz: f64| (mz * 15e-6).max(0.003);
    let find = |mz: f64, min_i: f64| -> bool {
        let t = tol(mz);
        let lo = by_mz.partition_point(|p| p.0 < mz - t);
        by_mz[lo..]
            .iter()
            .take_while(|p| p.0 <= mz + t)
            .any(|p| p.1 >= min_i)
    };
    let mut order = c;
    order.sort_by(|a, b| b.1.total_cmp(&a.1));
    let mut out: Vec<MsPeak> = Vec::new();
    for (mz, intensity) in order {
        if out.len() >= n {
            break;
        }
        let inside = out.iter().any(|p| {
            let z = f64::from(p.charge.unwrap_or(1));
            let base = p.monoisotopic_mz.unwrap_or(p.mz);
            (0..=8).any(|k| (mz - (base + f64::from(k) * ISOTOPE_SPACING_DA / z)).abs() <= tol(mz))
        });
        if inside {
            continue;
        }
        let mut best: Option<(u32, u32)> = None;
        for z in 1..=8u32 {
            let mut k = 0;
            while k < 6
                && find(
                    mz + f64::from(k + 1) * ISOTOPE_SPACING_DA / f64::from(z),
                    intensity * 0.02,
                )
            {
                k += 1;
            }
            if k > 0 && best.is_none_or(|b| k > b.1) {
                best = Some((z, k));
            }
        }
        let charge = best.map(|b| b.0);
        // the lowest peak of the pattern: step down while the next lower isotope is there
        let mut mono = mz;
        if let Some(z) = charge {
            let step = ISOTOPE_SPACING_DA / f64::from(z);
            for _ in 0..6 {
                if find(mono - step, intensity * 0.05) {
                    mono -= step;
                } else {
                    break;
                }
            }
        }
        let neutral_mass_da = charge.and_then(|z| {
            let z = f64::from(z);
            match sp.polarity.as_str() {
                "positive" => Some(z * (mono - PROTON_DA)),
                "negative" => Some(z * (mono + PROTON_DA)),
                _ => None,
            }
        });
        out.push(MsPeak {
            mz,
            intensity,
            charge,
            isotopes: best.map(|b| b.1),
            monoisotopic_mz: (mono < mz).then_some(mono),
            neutral_mass_da,
        });
    }
    out
}

/// Keep the `cap` most intense points of `sp`, in m/z order.
pub fn keep_most_intense(sp: &mut Spectrum, cap: usize) {
    let n = sp.mz.len().min(sp.intensity.len());
    if n <= cap {
        return;
    }
    let mut idx: Vec<usize> = (0..n).collect();
    idx.sort_by(|&a, &b| sp.intensity[b].total_cmp(&sp.intensity[a]));
    idx.truncate(cap);
    idx.sort_unstable();
    sp.mz = idx.iter().map(|&i| sp.mz[i]).collect();
    sp.intensity = idx.iter().map(|&i| sp.intensity[i]).collect();
}

#[cfg(test)]
mod peak_tests {
    use super::*;

    #[test]
    fn charges_from_isotope_spacing() {
        let mut sp = Spectrum {
            centroided: true,
            polarity: "positive".into(),
            ..Spectrum::default()
        };
        // a 2+ ion at 500.0 with isotopes at +0.5017, +1.0034; a 1+ ion at 700.0 with one isotope
        let pts = [
            (500.0, 1000.0),
            (500.0 + ISOTOPE_SPACING_DA / 2.0, 800.0),
            (500.0 + ISOTOPE_SPACING_DA, 400.0),
            (700.0, 600.0),
            (700.0 + ISOTOPE_SPACING_DA, 300.0),
            (800.0, 50.0),
        ];
        sp.mz = pts.iter().map(|p| p.0).collect();
        sp.intensity = pts.iter().map(|p| p.1 as f32).collect();
        let p = top_peaks(&sp, 3);
        assert_eq!(p[0].charge, Some(2));
        assert_eq!(p[0].isotopes, Some(2));
        assert!((p[0].neutral_mass_da.unwrap() - 2.0 * (500.0 - PROTON_DA)).abs() < 1e-9);
        assert_eq!(p[1].mz, 700.0);
        assert_eq!(p[1].charge, Some(1));
        assert_eq!(p[2].mz, 800.0);
        assert_eq!(p[2].charge, None);
        keep_most_intense(&mut sp, 2);
        assert_eq!(sp.mz, vec![500.0, 500.0 + ISOTOPE_SPACING_DA / 2.0]);
    }
}