mzdata-spectrum 0.67.2

A library to read mass spectrometry data formats and a data model for mass spectra
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt::Display;

use log::warn;
use num_traits::Float;

// use super::spectrum_types::{CentroidPeakAdapting, DeconvolutedPeakAdapting, SpectrumLike};
// use crate::io::traits::SpectrumSource;
use crate::params::{
    AccessionIntCode, CURIE, ControlledVocabulary, Param, ParamDescribed, ParamLike, ParamValue,
    Unit,
};
use mzdata_meta::DissociationMethodTerm;
use mzdata_param::{
    ParamList, curie, find_param_method, impl_param_described, impl_param_described_deferred,
};

/**

Describe the initialization stage of an isolation window
*/
#[derive(Debug, Clone, Copy, Default)]
#[repr(i8)]
pub enum IsolationWindowState {
    /// The isolation window hasn't been populated at all yet
    #[default]
    Unknown = 0,
    /// The isolation window is defined in terms of offsets relative
    /// to an isolation target
    Offset,
    /// The isolation window is defined in terms of absolute bounds. This
    /// configuration uses deprecated controlled vocabulary terms.
    Explicit,
    /// The isolation window is completely specified, either in terms of the
    /// isolation target with optional relative boundaries or explicit boundaries
    Complete,
    /// No isolation is explicitly specified, meaning all ions were fragmented,
    /// intentionally selecting everything.
    NoIsolation,
}

impl Display for IsolationWindowState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[derive(Debug)]
/// A helper type that wraps an existing mutable reference to [`IsolationWindow`]
/// that runs through a state machine updating fields depending upon the accumulated
/// state of the isolation window.
///
/// If relative offsets are used, they will materialize +/- relative to [`Self::target`].
/// If the deprecated absolute limits are used, they are taken as-is. The relative and
/// absolute APIs should not be mixed as the state machine does not track absolute/relative
/// bounds independently.
///
/// ```
/// use mzdata_spectrum::{IsolationWindow, IsolationWindowBuilder};
///
/// let mut state = IsolationWindow::default();
/// IsolationWindowBuilder(&mut state)
///     .lower_offset(2.0)
///     .upper_offset(3.0)
///     .target(500.0);
/// assert_eq!(state.lower_bound, 498.0);
/// assert_eq!(state.upper_bound, 503.0);
/// assert_eq!(state.target, 500.0);
/// ```
pub struct IsolationWindowBuilder<'a>(pub &'a mut IsolationWindow);

impl<'a> IsolationWindowBuilder<'a> {

    /// Get the current state of the isolation window
    pub const fn flags(&self) -> IsolationWindowState {
        self.0.flags
    }

    /// Set the target value
    pub const fn target(self, value: f32) -> Self {
        self.0.target = value;
        self.0.flags = match self.0.flags {
            IsolationWindowState::Unknown => IsolationWindowState::Complete,
            IsolationWindowState::Explicit => IsolationWindowState::Complete,
            IsolationWindowState::Offset => {
                self.0.lower_bound = self.0.target - self.0.lower_bound;
                self.0.upper_bound += self.0.target;
                IsolationWindowState::Complete
            }
            IsolationWindowState::Complete => IsolationWindowState::Complete,
            IsolationWindowState::NoIsolation => IsolationWindowState::NoIsolation,
        };
        self
    }

    /// Set the lower offset relative to the [`Self::target`]
    ///
    /// # Panics
    /// If one of the bounds is already explicit and the target is not specified
    pub const fn lower_offset(self, lower_bound: f32) -> Self {
        match self.0.flags {
            IsolationWindowState::Unknown => {
                self.0.flags = IsolationWindowState::Offset;
                self.0.lower_bound = lower_bound;
            }
            // The other offset came first; keep waiting for the target to resolve both.
            IsolationWindowState::Offset => {
                self.0.lower_bound = lower_bound;
            }
            IsolationWindowState::Complete => {
                self.0.lower_bound = self.0.target - lower_bound;
            }
            IsolationWindowState::Explicit => {
                if self.0.target == 0.0 {
                    panic!("Mixed relative and absolute isolation window bounds could not be resolvd. Explicit and relative bounds specified before target");
                } else {
                    self.0.lower_bound = self.0.target - lower_bound;
                }
            }
            _ => {}
        }
        self
    }

    /// Set the upper offset relative to the [`Self::target`]
    ///
    /// # Panics
    /// If one of the bounds is already explicit and the target is not specified
    pub const fn upper_offset(self, upper_bound: f32) -> Self {
        match self.0.flags {
            IsolationWindowState::Unknown => {
                self.0.flags = IsolationWindowState::Offset;
                self.0.upper_bound = upper_bound;
            }
            IsolationWindowState::Offset => {
                self.0.upper_bound = upper_bound;
            }
            IsolationWindowState::Complete => {
                self.0.upper_bound = self.0.target + upper_bound;
            }
            IsolationWindowState::Explicit => {
                if self.0.target == 0.0 {
                    panic!("Mixed relative and absolute isolation window bounds could not be resolvd. Explicit and relative bounds specified before target");
                } else {
                    self.0.upper_bound = self.0.target + upper_bound;
                }
            }
            _ => {}
        }
        self
    }

    /// Set the explicit lower limit
    pub const fn lower_limit(self, lower_bound: f32) -> Self {
        match self.0.flags {
            IsolationWindowState::Unknown | IsolationWindowState::Explicit | IsolationWindowState::Complete | IsolationWindowState::Offset => {
                self.0.flags = IsolationWindowState::Explicit;
                self.0.lower_bound = lower_bound;
                if self.0.upper_bound != 0.0 && self.0.target != 0.0 {
                    self.0.flags = IsolationWindowState::Complete
                }
            },
            IsolationWindowState::NoIsolation => {},
        }
        self
    }

    /// Set the explicit upper limit
    pub const fn upper_limit(self, upper_bound: f32) -> Self {
        if matches!(
            self.0.flags,
            IsolationWindowState::Unknown
                | IsolationWindowState::Explicit
                | IsolationWindowState::Offset
                | IsolationWindowState::Complete
        ) {
            self.0.flags = IsolationWindowState::Explicit;
            self.0.upper_bound = upper_bound;
            if self.0.lower_bound != 0.0 && self.0.target != 0.0 {
                self.0.flags = IsolationWindowState::Complete
            }
        }
        self
    }

    /// Set no isolation, MSe/all ions fragmentation
    pub const fn no_isolation(self) -> Self {
        self.0.flags = IsolationWindowState::NoIsolation;
        self
    }

    /// Check if the window is finished being configured
    pub const fn is_complete(&self) -> bool {
        matches!(
            self.0.flags,
            IsolationWindowState::Complete | IsolationWindowState::NoIsolation
        )
    }

    /// Set the isolation window unit
    pub const fn unit(self, unit: Unit) -> Self {
        *self.0.unit_mut() = unit;
        self
    }
}

#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// The interval around the precursor ion that was isolated in the precursor scan.
/// Although an isolation window may be specified either with explicit bounds or
/// offsets from the target, this data structure always uses explicit bounds once
/// it is in a [`IsolationWindowState::Complete`]. If [`Self::flags`] is
/// [`IsolationWindowState::NoIsolation`], then the assumption is that the bounds
/// are undefined and that there is no target.
pub struct IsolationWindow {
    /// The recorded isolation window target m/z, which may actually be outside the window
    pub target: f32,
    /// The lower m/z boundary of the isolation window.
    pub lower_bound: f32,
    /// The upper m/z boundary of the isolation window.
    pub upper_bound: f32,
    /// Describes the decision making process used to establish the bounds of the
    /// window from the source file.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub flags: IsolationWindowState,
    unit: Unit
}

impl IsolationWindow {
    pub const fn new(
        target: f32,
        lower_bound: f32,
        upper_bound: f32,
        flags: IsolationWindowState,
    ) -> Self {
        Self {
            target,
            lower_bound,
            upper_bound,
            flags,
            unit: Unit::Unknown
        }
    }

    /// Get the unit of the isolation window
    pub const fn unit(&self) -> Unit {
        self.unit
    }

    /// Get mutable access to unit of the isolation window
    pub const fn unit_mut(&mut self) -> &mut Unit {
        &mut self.unit
    }

    /// Create an isolation window that is in the "no isolation" state.
    pub const fn full() -> Self {
        Self::new(0.0, 0.0, 0.0, IsolationWindowState::NoIsolation)
    }

    /// Check if there is a registered intent to isolate nothing
    pub const fn has_isolation(&self) -> bool {
        !matches!(self.flags, IsolationWindowState::NoIsolation)
    }

    /// Create a new isolation window around `target` with width `radius`
    /// units above and below the `target`
    pub const fn around(target: f32, radius: f32) -> Self {
        let lower_bound = target - radius;
        let upper_bound = target + radius;
        Self::new(
            target,
            lower_bound,
            upper_bound,
            IsolationWindowState::Complete,
        )
    }

    /// Test if `point` is within the isolation window
    pub fn contains<F: Float>(&self, point: F) -> bool {
        let point = point.to_f32().unwrap();
        self.lower_bound <= point && point <= self.upper_bound
    }

    /// Check if the isolation window has any width, or is just a single point at the
    /// target. This often means that the bounds are unknown or unspecified. This is
    /// distinct from [`Self::has_isolation`]
    pub const fn is_empty(&self) -> bool {
        self.lower_bound == 0.0 && self.upper_bound == 0.0 && self.has_isolation()
    }
}

impl PartialEq for IsolationWindow {
    fn eq(&self, other: &Self) -> bool {
        self.target == other.target
            && self.lower_bound == other.lower_bound
            && self.upper_bound == other.upper_bound
    }
}

/// The m/z range which was scanned
#[derive(Default, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ScanWindow {
    /// The minimum m/z scanned
    pub lower_bound: f32,
    /// The maximum m/z scanned
    pub upper_bound: f32,
}

impl ScanWindow {
    pub const fn new(lower_bound: f32, upper_bound: f32) -> Self {
        Self {
            lower_bound,
            upper_bound,
        }
    }

    /// Test if `point` is between [`Self::lower_bound`] and [`Self::upper_bound`]
    pub fn contains<F: Float>(&self, point: F) -> bool {
        let point = point.to_f32().unwrap();
        self.lower_bound <= point && point <= self.upper_bound
    }

    /// Test if [`Self::lower_bound`] and [`Self::upper_bound`] are both equal to 0.
    pub fn is_empty(&self) -> bool {
        self.lower_bound == 0.0 && self.upper_bound == 0.0
    }
}

type ScanWindowList = Vec<ScanWindow>;

#[derive(Default, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// Describes a single scan event. Unless additional post-processing is done,
/// there is usually only one event per spectrum.
pub struct ScanEvent {
    /// When did the scan start acquisition relative to the run start, in minutes
    pub start_time: f64,
    /// The time spent filling the ion trapping device, in milliseconds
    pub injection_time: f32,
    /// The windows of the primary axis covered by this event
    pub scan_windows: ScanWindowList,
    /// The identifier of the [`InstrumentConfiguration`](crate::meta::InstrumentConfiguration) associated
    /// with the event
    pub instrument_configuration_id: u32,
    /// Lazily initialized [`ParamList`]
    pub params: Option<Box<ParamList>>,
    /// The identifier for another spectrum in the current run or another file.
    pub spectrum_reference: Option<Box<str>>,
}

pub(crate) const ION_MOBILITY_SCAN_TERMS: [CURIE; 4] = [
    // ion mobility drift time
    curie!(MS:1002476),
    // inverse reduced ion mobility drift time
    curie!(MS:1002815),
    // FAIMS compensation voltage
    curie!(MS:1001581),
    // SELEXION compensation voltage
    curie!(MS:1003371),
];

/// Describes an entity that may have a point-level ion mobility coordinate.
///
/// The default implementation searches for the following ion mobility kinds in attached
/// [`Param`]s:
/// - MS:1002476 ion mobility drift time (milliseconds)
/// - MS:1002815 inverse reduced ion mobility (Vs/cm^2)
/// - MS:1001581 FAIMS compensation voltage (volts)
/// - MS:1003371 SELEXION compensation voltage (volts)
pub trait IonMobilityMeasure: ParamDescribed {

    /// Get the ion mobility coordinate, if one is available.
    fn ion_mobility(&'_ self) -> Option<f64> {
        for u in ION_MOBILITY_SCAN_TERMS {
            if let Some(v) = self.get_param_by_curie(&u).map(|p| p.value()) {
                return v.to_f64().map(Some).unwrap_or_else(|e| {
                    warn!("Failed to parse ion mobility {u} value {v}: {e}");
                    None
                });
            }
        }
        None
    }

    /// Test if an ion mobility value is present
    fn has_ion_mobility(&self) -> bool {
        self.ion_mobility().is_some()
    }

    /// Get the raw [`Param`] representation of the ion mobility measure
    /// with the unit
    fn ion_mobility_type(&self) -> Option<&Param> {
        for u in ION_MOBILITY_SCAN_TERMS {
            if let Some(v) = self.get_param_by_curie(&u) {
                return Some(v);
            }
        }
        None
    }
}

pub(crate) const PRESET_SCAN_CONFIGURATION: CURIE = curie!(MS:1000616);
pub(crate) const MASS_RESOLUTION: CURIE = curie!(MS:1000011);
pub(crate) const FILTER_STRING: CURIE = curie!(MS:1000512);
pub(crate) const SCAN_TITLE: CURIE = curie!(MS:1000499);

impl ScanEvent {
    pub fn new(
        start_time: f64,
        injection_time: f32,
        scan_windows: ScanWindowList,
        instrument_configuration_id: u32,
        params: Option<Box<ParamList>>,
    ) -> Self {
        Self {
            start_time,
            injection_time,
            scan_windows,
            instrument_configuration_id,
            params,
            spectrum_reference: None,
        }
    }

    find_param_method!(
        filter_string,
        &FILTER_STRING,
        |p| { p.as_str() },
        Option<Cow<'_, str>>
    );
    find_param_method!(resolution, &MASS_RESOLUTION);
    find_param_method!(scan_configuration, &PRESET_SCAN_CONFIGURATION);
}

impl IonMobilityMeasure for ScanEvent {}

type ScanEventList = Vec<ScanEvent>;

/// Represents means by which a spectrum is generated using
/// one or more instrument analyzers
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ScanCombination {
    // MS:1000795
    #[default]
    NoCombination,
    // MS:1000571
    Sum,
    // MS:1000573
    Median,
}

impl Display for ScanCombination {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl ScanCombination {
    pub fn from_accession(
        controlled_vocabulary: ControlledVocabulary,
        accession: AccessionIntCode,
    ) -> Option<ScanCombination> {
        match controlled_vocabulary {
            ControlledVocabulary::MS => match accession {
                1000795 => Some(Self::NoCombination),
                1000571 => Some(Self::Sum),
                1000573 => Some(Self::Median),
                _ => None,
            },
            _ => None,
        }
    }

    pub const fn name(&self) -> &str {
        match self {
            ScanCombination::NoCombination => "no combination",
            ScanCombination::Sum => "sum of spectra",
            ScanCombination::Median => "median of spectra",
        }
    }

    pub const fn accession(&self) -> AccessionIntCode {
        match self {
            ScanCombination::NoCombination => 1000795,
            ScanCombination::Sum => 1000571,
            ScanCombination::Median => 1000573,
        }
    }

    pub fn to_param(&self) -> Param {
        Param {
            name: self.name().to_string(),
            value: Default::default(),
            accession: Some(self.accession()),
            controlled_vocabulary: Some(ControlledVocabulary::MS),
            unit: Unit::Unknown,
        }
    }
}

#[derive(Default, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// Describe the series of acquisition events that constructed the spectrum
/// being described.
pub struct Acquisition {
    /// The list of scans that were acquired and combined to make a spectrum
    pub scans: ScanEventList,
    /// How the scans were combined to make the single spectrum.
    pub combination: ScanCombination,
    /// Lazily initialized [`ParamList`]
    pub params: Option<Box<ParamList>>,
}

impl Acquisition {
    /// Get the [`ScanEvent::start_time`] of [`Self::first_scan`] or 0.0 if empty.
    pub fn start_time(&self) -> f64 {
        self.first_scan().map(|v| v.start_time).unwrap_or_default()
    }

    /// An alias of `self.scans.first()`
    pub fn first_scan(&self) -> Option<&ScanEvent> {
        self.scans.first()
    }

    /// If the `self.scans.is_empty()`, create a new default [`ScanEvent`], and then
    /// `self.scans.first_mut()`
    pub fn first_scan_mut(&mut self) -> Option<&mut ScanEvent> {
        if self.scans.is_empty() {
            self.scans.push(ScanEvent::default());
        }
        self.scans.first_mut()
    }

    /// As [`Self::first_scan`] but for `last`
    pub fn last_scan(&self) -> Option<&ScanEvent> {
        self.scans.last()
    }

    /// As [`Self::first_scan_mut`] but for `last`. Also creates a [`ScanEvent`]
    /// if it is missing.
    pub fn last_scan_mut(&mut self) -> Option<&mut ScanEvent> {
        if self.scans.is_empty() {
            self.scans.push(ScanEvent::default());
        }
        self.scans.last_mut()
    }

    /// Get the list of [`InstrumentConfiguration::id`] referenced by this set of scans
    pub fn instrument_configuration_ids(&self) -> Vec<u32> {
        self.scans
            .iter()
            .map(|s| s.instrument_configuration_id)
            .collect()
    }

    /// The number of scans in the acquisition
    pub const fn len(&self) -> usize {
        self.scans.len()
    }

    /// An alias for `self.scans.is_empty()`
    pub fn is_empty(&self) -> bool {
        self.scans.is_empty()
    }

    /// Iterate over references in [`Self::scans`]
    pub fn iter(&self) -> std::slice::Iter<'_, ScanEvent> {
        self.scans.iter()
    }

    /// Iterate over mutable references in [`Self::scans`]
    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, ScanEvent> {
        self.scans.iter_mut()
    }
}

/// Describe the precursor ion that this entity represents
pub trait IonProperties {
    /// The selected ion m/z
    fn mz(&self) -> f64;
    /// The selected ion's estimated neutral mass, given the m/z and charge
    fn neutral_mass(&self) -> f64;
    /// The expected charge state of the selected ion, if known
    fn charge(&self) -> Option<i32>;
    fn has_charge(&self) -> bool {
        self.charge().is_some()
    }
}

#[derive(Debug, Clone, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// Describes a single selected ion from a precursor isolation
pub struct SelectedIon {
    /// The selected ion's m/z as reported, may not be the monoisotopic peak.
    pub mz: f64,
    /// The reported intensity of the selected ion's peak
    pub intensity: f32,
    /// The reported precursor ion's charge state. May be absent in
    /// some source files.
    pub charge: Option<i32>,
    /// Additional lazily initialized [`ParamList`]
    pub params: Option<Box<ParamList>>,
}

impl IonProperties for SelectedIon {
    #[inline]
    fn mz(&self) -> f64 {
        self.mz
    }

    #[inline]
    fn neutral_mass(&self) -> f64 {
        mzdata_bindata::utils::neutral_mass(self.mz, self.charge.unwrap_or(1))
    }

    #[inline]
    fn charge(&self) -> Option<i32> {
        self.charge
    }
}

impl IonMobilityMeasure for SelectedIon {}

#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// Describes the activation method used to dissociate the precursor ion
pub struct Activation {
    _methods: Vec<DissociationMethodTerm>,
    /// The energy used to dissociate the precursor(s). This will eventually cease to be a raw `f32`.
    pub energy: f32,
    /// Any additional [`Param`] describing the activation process
    pub params: ParamList,
}

impl Activation {
    /// Get a reference to the first activation method, if it exists
    pub fn method(&self) -> Option<&DissociationMethodTerm> {
        self._methods.first()
    }

    /// Get a mutable reference to the first activation method, if it exists
    pub fn method_mut(&mut self) -> Option<&mut DissociationMethodTerm> {
        self._methods.first_mut()
    }

    /// Get a slice over all of the activation methods used.
    pub fn methods(&self) -> &[DissociationMethodTerm] {
        &self._methods
    }

    /// Get a mutable reference to a [`Vec`] of activation methods, which may be useful
    /// for adding or removing methods.
    pub fn methods_mut(&mut self) -> &mut Vec<DissociationMethodTerm> {
        &mut self._methods
    }

    /// Check if multiple dissociation methods were used
    pub fn is_combined(&self) -> bool {
        self._methods.len() > 1
    }

    /// Check if a [`ParamLike`] type references an activation method
    pub fn is_param_activation<P: ParamLike>(p: &P) -> bool {
        if p.is_controlled() && p.controlled_vocabulary().unwrap() == ControlledVocabulary::MS {
            Self::accession_to_activation(p.accession().unwrap())
        } else {
            false
        }
    }

    /// Translate an integer accession ID into a [`DissociationMethodTerm`] if possible to detect
    /// if it refers to a dissociation method.
    pub fn accession_to_activation(accession: AccessionIntCode) -> bool {
        DissociationMethodTerm::from_accession(accession).is_some()
    }

    pub fn _extract_methods_from_params(&mut self) {
        let mut methods = Vec::with_capacity(1);
        let mut rest = Vec::with_capacity(self.params.len());
        for p in self.params.drain(..) {
            if Self::is_param_activation(&p) {
                methods.push(p.into())
            } else {
                rest.push(p)
            }
        }
        self.params = rest;
        self._methods = methods;
    }

    /// The energy used to dissociate the precursor(s)
    pub fn energy(&self) -> f32 {
        self.energy
    }
}

#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// Describes the precursor ion of the owning spectrum.
pub struct Precursor {
    /// Describes the selected ion's properties
    pub ions: Vec<SelectedIon>,
    /// Describes the isolation window around the selected ion
    pub isolation_window: IsolationWindow,
    /// The precursor scan ID, if given
    pub precursor_id: Option<String>,
    /// The product scan ID, if given
    pub product_id: Option<String>,
    /// The activation process applied to the precursor ion
    pub activation: Activation,
}

impl Precursor {
    // /// Given a [`SpectrumSource`] object, look up the precursor scan in it.
    // /// This is useful when examining the area *around* where the precursor
    // /// ion was or to obtain a snapshot of the retention time when the spectrum
    // /// was scheduled.
    // pub fn precursor_spectrum<C, D, S, R>(&self, source: &mut R) -> Option<S>
    // where
    //     C: CentroidPeakAdapting,
    //     D: DeconvolutedPeakAdapting,
    //     S: SpectrumLike<C, D>,
    //     R: SpectrumSource<C, D, S>,
    // {
    //     match self.precursor_id.as_ref() {
    //         Some(id) => source.get_spectrum_by_id(id),
    //         None => None,
    //     }
    // }

    /// Check if this precursor selection selected any ions
    pub fn has_ions(&self) -> bool {
        self.ions.is_empty()
    }

    // /// Given a [`SpectrumSource`] object, look up the product scan in it.
    // /// This is rarely needed unless you have manually separated [`Precursor`]
    // /// objects from their spectra.
    // pub fn product_spectrum<C, D, S, R>(&self, source: &mut R) -> Option<S>
    // where
    //     C: CentroidPeakAdapting,
    //     D: DeconvolutedPeakAdapting,
    //     S: SpectrumLike<C, D>,
    //     R: SpectrumSource<C, D, S>,
    // {
    //     match self.product_id.as_ref() {
    //         Some(id) => source.get_spectrum_by_id(id),
    //         None => None,
    //     }
    // }
}

/**

A trait for abstracting over how a precursor ion is described, immutably.
*/
pub trait PrecursorSelection {
    /// Describes the selected ion's properties
    fn ion(&self) -> Option<&SelectedIon>;
    /// Describes the isolation window around the selected ion
    fn isolation_window(&self) -> &IsolationWindow;
    /// The precursor scan ID, if given
    fn precursor_id(&self) -> Option<&String>;
    /// The product scan ID, if given
    fn product_id(&self) -> Option<&String>;
    /// The activation process applied to the precursor ion
    fn activation(&self) -> &Activation;

    fn iter(&self) -> impl Iterator<Item = &SelectedIon>;

    /// Check if this precursor selection selected any ions
    fn has_ions(&self) -> bool {
        self.iter().count() > 0
    }

    fn last_ion(&self) -> Option<&SelectedIon> {
        self.iter().last()
    }

    fn iter_mut(&mut self) -> impl Iterator<Item = &mut SelectedIon>;
    fn ion_mut(&mut self) -> Option<&mut SelectedIon>;
    fn activation_mut(&mut self) -> &mut Activation;
    fn isolation_window_mut(&mut self) -> &mut IsolationWindow;
    fn add_ion(&mut self, ion: SelectedIon);
    fn last_ion_mut(&mut self) -> Option<&mut SelectedIon> {
        self.iter_mut().last()
    }
}

impl PrecursorSelection for Precursor {
    fn ion(&self) -> Option<&SelectedIon> {
        self.ions.first()
    }

    fn isolation_window(&self) -> &IsolationWindow {
        &self.isolation_window
    }

    fn precursor_id(&self) -> Option<&String> {
        self.precursor_id.as_ref()
    }

    fn product_id(&self) -> Option<&String> {
        self.product_id.as_ref()
    }

    fn activation(&self) -> &Activation {
        &self.activation
    }

    fn ion_mut(&mut self) -> Option<&mut SelectedIon> {
        if self.ions.is_empty() {
            self.ions.push(SelectedIon::default())
        }
        self.ions.first_mut()
    }

    fn activation_mut(&mut self) -> &mut Activation {
        &mut self.activation
    }

    fn isolation_window_mut(&mut self) -> &mut IsolationWindow {
        &mut self.isolation_window
    }

    fn iter(&self) -> impl Iterator<Item = &SelectedIon> {
        self.ions.iter()
    }

    fn iter_mut(&mut self) -> impl Iterator<Item = &mut SelectedIon> {
        self.ions.iter_mut()
    }

    fn add_ion(&mut self, ion: SelectedIon) {
        self.ions.push(ion);
    }

    fn last_ion_mut(&mut self) -> Option<&mut SelectedIon> {
        if self.ions.is_empty() {
            self.ions.push(SelectedIon::default())
        }
        self.iter_mut().last()
    }
}

/**

Describes the polarity of a mass spectrum. A spectrum is either `Positive` (1+), `Negative` (-1)
or `Unknown` (0). The `Unknown` state is the default.
*/
#[repr(i8)]
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ScanPolarity {
    #[default]
    /// The polarity of the spectrum is unknown
    Unknown = 0,
    /// The polarity is positive, where charge states represent the addition of positive charge
    Positive = 1,
    /// The polarity is negative, where the charge states reprsent the addition of electrons or other
    /// negatively charged adduction
    Negative = -1,
}

impl ScanPolarity {
    /// Get a signed integer representing the polarity of the spectrum. This
    /// assumes that unknown spectra are more likely to be positive so it
    /// is distinct from the raw integer value of the enum where [`Unknown`](Self::Unknown)
    /// is 0.
    pub fn sign(&self) -> i32 {
        match self {
            ScanPolarity::Unknown => 1,
            ScanPolarity::Positive => 1,
            ScanPolarity::Negative => -1,
        }
    }
}

impl Display for ScanPolarity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

/**

Describes the initial representation of the signal of a spectrum.

Though most formats explicitly have a method of either conveying a processing level
or an assumed level, the `Unknown` option is retained for partial initialization.
*/
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SignalContinuity {
    #[default]
    Unknown = 0,
    /// The spectrum is centroided, indicating that its primary representation is that of a
    /// discrete peak list. There may be multiple peak lists and a profile spectrum may still
    /// be present on the same spectrum.
    Centroid = 3,
    /// The spectrum is profile, indicating that its primary representation is a continuous
    /// profile.
    Profile = 5,
}

impl SignalContinuity {
    pub const fn is_profile(&self) -> bool {
        matches!(self, Self::Profile)
    }

    pub const fn is_centroid(&self) -> bool {
        matches!(self, Self::Centroid)
    }
}

impl Display for SignalContinuity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// An adapter type to make it possible to pass an `Option<Precursor>`, `Vec<Precursor>`,
/// or [`Precursor`] in an argument context.
#[derive(Debug)]
pub enum AsPrecursorCollection {
    /// A single [`Precursor`]
    Single(Option<Precursor>),
    /// Multiple [`Precursor`], denoting higher order MSn
    Multiple(Vec<Precursor>),
}

impl From<AsPrecursorCollection> for Vec<Precursor> {
    fn from(value: AsPrecursorCollection) -> Self {
        match value {
            AsPrecursorCollection::Single(precursor) => {
                precursor.map(|v| vec![v]).unwrap_or_default()
            }
            AsPrecursorCollection::Multiple(precursors) => precursors,
        }
    }
}

impl From<Precursor> for AsPrecursorCollection {
    fn from(value: Precursor) -> Self {
        Self::Single(Some(value))
    }
}

impl From<Option<Precursor>> for AsPrecursorCollection {
    fn from(value: Option<Precursor>) -> Self {
        Self::Single(value)
    }
}

impl From<Vec<Precursor>> for AsPrecursorCollection {
    fn from(value: Vec<Precursor>) -> Self {
        Self::Multiple(value)
    }
}

/**

The set of descriptive metadata that give context for how a mass spectrum was acquired
within a particular run. This forms the basis for a large portion of the [`SpectrumLike`]
trait.
*/
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SpectrumDescription {
    /// The spectrum's native identifier
    pub id: String,
    /// The ordinal sequence number for the spectrum
    pub index: usize,
    /// The degree of exponentiation of the spectrum, e.g MS1, MS2, MS3, etc
    pub ms_level: u8,

    /// The spectrum is in positive or negative mode
    pub polarity: ScanPolarity,

    /// The spectrum's main representation is as a peak list or a continuous
    /// profile
    pub signal_continuity: SignalContinuity,

    /// A set of controlled or uncontrolled descriptors of the spectrum not already
    /// covered by fields
    pub params: ParamList,

    /// A description of how the spectrum was acquired including time, scan windows, and more
    pub acquisition: Acquisition,

    /// The parent ion or ions and their isolation and activation description
    pub precursor: Vec<Precursor>,
}

impl SpectrumDescription {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: String,
        index: usize,
        ms_level: u8,
        polarity: ScanPolarity,
        signal_continuity: SignalContinuity,
        params: ParamList,
        acquisition: Acquisition,
        precursor: impl Into<AsPrecursorCollection>,
    ) -> Self {
        Self {
            id,
            index,
            ms_level,
            polarity,
            signal_continuity,
            params,
            acquisition,
            precursor: precursor.into().into(),
        }
    }

    find_param_method!(title, &SCAN_TITLE, |p| p.as_str(), Option<Cow<'_, str>>);

    /// Find the type of spectrum described.
    ///
    /// A spectrum in `mzdata` is *usually* a mass spectrum of some sort, but that's not guaranteed
    /// to be the case. `mzdata` can handle non-MS spectra, but little of the signal processing
    /// machinery it provides currently supports those other kinds of data.
    pub fn spectrum_type(&self) -> Option<mzdata_meta::SpectrumType> {
        const SPECTRUM_TYPES: &[(mzdata_meta::SpectrumType, crate::params::ParamCow<'static>)] =
            mzdata_meta::SpectrumType::all_types();

        let conv_table: HashMap<CURIE, mzdata_meta::SpectrumType> = SPECTRUM_TYPES
            .iter()
            .map(|(t, v)| (v.curie().unwrap(), *t))
            .collect();

        for param in self.params().iter() {
            if let Some(c) = param.curie() {
                if let Some(t) = conv_table.get(&c) {
                    return Some(*t);
                }
            }
        }
        None
    }

    /// Set the kind of spectrum represented.
    pub fn set_spectrum_type(&mut self, spectrum_type: mzdata_meta::SpectrumType) {
        const SPECTRUM_TYPES: &[(mzdata_meta::SpectrumType, crate::params::ParamCow<'static>)] =
            mzdata_meta::SpectrumType::all_types();

        let to_insert: crate::params::ParamCow<'_> = spectrum_type.to_param();

        let conv_table: HashSet<CURIE> = SPECTRUM_TYPES
            .iter()
            .map(|(_, v)| v.curie().unwrap())
            .collect();

        for param in self.params_mut().iter_mut() {
            if let Some(c) = param.curie() {
                if conv_table.contains(&c) {
                    *param = to_insert.into();
                    return;
                }
            }
        }

        self.add_param(to_insert.into());
    }
}

impl_param_described!(Activation, SpectrumDescription);
impl_param_described_deferred!(SelectedIon, Acquisition, ScanEvent);

/// Types of chromatograms enumerated in the PSI-MS controlled vocabulary
#[derive(Debug, Clone, Copy, PartialEq, Default, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ChromatogramType {
    #[default]
    Unknown,
    /// The sum of all intensity at each time point
    TotalIonCurrentChromatogram,
    /// The most intense peak at each time point
    BasePeakChromatogram,
    /// The intensity of selected ion at each time point
    SelectedIonCurrentChromatogram,
    /// The intensity of selected ion at each time point
    SelectedIonMonitoringChromatogram,
    /// The intensity of selected ion and its products at each time point
    SelectedReactionMonitoringChromatogram,
    AbsorptionChromatogram,
    EmissionChromatogram,
    /// The flow rate at each time point
    FlowRateChromatogram,
    /// The pressure at each time point
    PressureChromatogram,
    /// The temperature of an element at each time point
    TemperatureChromatogram,
    /// The intensity of the signal for a specific wavelength of EMR at each time point
    ElectromagneticRadiationChromatogram,
}

impl ChromatogramType {
    /// Construct a [`ChromatogramType`] from a PSI-MS controlled vocabulary ID
    pub fn from_accession(accession: AccessionIntCode) -> Option<Self> {
        let tp = match accession {
            1000235 => Self::TotalIonCurrentChromatogram,
            1000628 => Self::BasePeakChromatogram,
            1000627 => Self::SelectedIonCurrentChromatogram,
            1001472 => Self::SelectedIonMonitoringChromatogram,
            1001473 => Self::SelectedReactionMonitoringChromatogram,
            1000812 => Self::AbsorptionChromatogram,
            1000813 => Self::EmissionChromatogram,
            1003020 => Self::FlowRateChromatogram,
            1003019 => Self::PressureChromatogram,
            1000811 => Self::ElectromagneticRadiationChromatogram,
            1000626 => Self::Unknown,
            1002715 => Self::TemperatureChromatogram,
            _ => return None,
        };
        Some(tp)
    }

    /// Construct a [`ChromatogramType`] from a PSI-MS controlled vocabulary [`CURIE`]
    pub fn from_curie(curie: CURIE) -> Option<Self> {
        match curie.controlled_vocabulary() {
            ControlledVocabulary::MS => Self::from_accession(curie.accession_int()),
            _ => None,
        }
    }

    /// Test if the chromatogram is a measure of EMR
    pub fn is_electromagnetic_radiation(&self) -> bool {
        matches!(
            self,
            Self::AbsorptionChromatogram
                | Self::EmissionChromatogram
                | Self::ElectromagneticRadiationChromatogram
        )
    }

    /// Test if the chromatogram is an aggregation across multiple elements, specifically
    /// [`Self::TotalIonCurrentChromatogram`] or [`Self::BasePeakChromatogram`]
    pub fn is_aggregate(&self) -> bool {
        matches!(
            self,
            Self::TotalIonCurrentChromatogram
                | Self::BasePeakChromatogram
        )
    }

    /// Test if the chromatogram tracks an ionization process
    pub fn is_ion_current(&self) -> bool {
        matches!(
            self,
            Self::SelectedIonCurrentChromatogram
                | Self::SelectedIonMonitoringChromatogram
                | Self::SelectedReactionMonitoringChromatogram
                | Self::TotalIonCurrentChromatogram
                | Self::BasePeakChromatogram
        )
    }

    /// Convert this [`ChromatogramType`] to a [`CURIE`]
    pub fn to_curie(&self) -> CURIE {
        match self {
            Self::TotalIonCurrentChromatogram => CURIE::new(ControlledVocabulary::MS, 1000235),
            Self::BasePeakChromatogram => CURIE::new(ControlledVocabulary::MS, 1000628),
            Self::SelectedIonCurrentChromatogram => CURIE::new(ControlledVocabulary::MS, 1000627),
            Self::SelectedIonMonitoringChromatogram => {
                CURIE::new(ControlledVocabulary::MS, 1000472)
            }
            Self::SelectedReactionMonitoringChromatogram => {
                CURIE::new(ControlledVocabulary::MS, 1000473)
            }
            Self::AbsorptionChromatogram => CURIE::new(ControlledVocabulary::MS, 1000812),
            Self::ElectromagneticRadiationChromatogram => {
                CURIE::new(ControlledVocabulary::MS, 1000811)
            }
            Self::EmissionChromatogram => CURIE::new(ControlledVocabulary::MS, 1000813),
            Self::FlowRateChromatogram => CURIE::new(ControlledVocabulary::MS, 1003020),
            Self::PressureChromatogram => CURIE::new(ControlledVocabulary::MS, 1003019),
            Self::TemperatureChromatogram => CURIE::new(ControlledVocabulary::MS, 1002715),
            Self::Unknown => CURIE::new(ControlledVocabulary::MS, 1000626),
        }
    }
}

/// A product ion isolated in lock-step from the precursor, as in selected reaction monitoring (SRM)
/// or multiple reaction monitoring (MRM).
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Product {
    /// The product ion's isolation window.
    pub isolation_window: IsolationWindow,
}

impl From<IsolationWindow> for Product {
    fn from(isolation_window: IsolationWindow) -> Self {
        Self { isolation_window }
    }
}

impl Product {
    pub fn new(isolation_window: IsolationWindow) -> Self {
        Self { isolation_window }
    }
}

/// The set of descriptive metadata that give context for how a chromatogram was
/// recorded.
///
/// Chromatograms record measures over time, and may be derived from mass spectra or
/// other forms of detectors.
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ChromatogramDescription {
    /// The locally unique identifier for this chromatogram
    pub id: String,
    /// The ordinal index for this chromatogram
    pub index: usize,
    /// The MS level, if any, for this chromatogram
    pub ms_level: Option<u8>,
    /// The MS polarity, if any, for this chromatogram
    pub polarity: ScanPolarity,
    /// The kind of chromatogram this is
    pub chromatogram_type: ChromatogramType,

    /// Additional [`Param`] that describe this chromatogram
    pub params: ParamList,
    /// Any [`Precursor`] that describe the derivation of this chromatogram
    pub precursor: Vec<Precursor>,
    /// Any reaction monitoring linked to this chromatogram
    pub products: Vec<Product>,
}

impl ChromatogramDescription {
    /// See [`ChromatogramType::is_aggregate`]
    pub fn is_aggregate(&self) -> bool {
        self.chromatogram_type.is_aggregate()
    }

    /// See [`ChromatogramType::is_electromagnetic_radiation`]
    pub fn is_electromagnetic_radiation(&self) -> bool {
        self.chromatogram_type.is_electromagnetic_radiation()
    }

    /// See [`ChromatogramType::is_ion_current`]
    pub fn is_ion_current(&self) -> bool {
        self.chromatogram_type.is_ion_current()
    }
}

impl_param_described!(ChromatogramDescription);

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

    // Regression tests for the isolation/scan-window `contains` membership check. A prior bug used
    // `lower <= point && upper <= point`, which wrongly excluded interior points and wrongly included
    // points above the window; `contains` must be an inclusive `[lower, upper]` test.

    #[test]
    fn isolation_window_contains_is_inclusive_range() {
        let window = IsolationWindow::around(810.789, 1.0); // [809.789, 811.789]
        assert!(window.contains(window.target), "target must be inside");
        assert!(
            window.contains(window.lower_bound),
            "lower bound is inclusive"
        );
        assert!(
            window.contains(window.upper_bound),
            "upper bound is inclusive"
        );
        assert!(window.contains(810.0_f64), "interior point");
        assert!(!window.contains(809.0_f64), "below the lower bound");
        assert!(!window.contains(812.0_f64), "above the upper bound");
    }

    #[test]
    fn scan_window_contains_is_inclusive_range() {
        let window = ScanWindow::new(200.0, 2000.0);
        assert!(window.contains(1100.0_f64), "interior point");
        assert!(window.contains(200.0_f64), "lower bound is inclusive");
        assert!(window.contains(2000.0_f64), "upper bound is inclusive");
        assert!(!window.contains(199.0_f64), "below the lower bound");
        assert!(
            !window.contains(2500.0_f64),
            "above the upper bound (the old bug returned true here)"
        );
    }
}