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
use std::borrow::{Borrow, Cow};

use super::bindata::{ArrayRetrievalError, ArrayType, BinaryArrayMap, ByteArrayView};
use crate::params::{Param, ParamDescribed};
use crate::spectrum::scan_properties::{
    ChromatogramDescription, ChromatogramType, Precursor, ScanPolarity,
};
use mzpeaks::coordinate::{Time, MZ};
use mzpeaks::feature::{FeatureView, SimpleFeature, TimeInterval};

#[derive(Debug, Default, Clone)]
pub struct Chromatogram {
    description: ChromatogramDescription,
    pub arrays: BinaryArrayMap,
}

const EMPTY: &[f64] = &[0.0];

macro_rules! as_feature_view {
    ($chromatogram:ident, $view:ident => $then:tt) => {
        if let Ok(t) = $chromatogram.time() {
            if let Ok(i) = $chromatogram.intensity() {
                let $view = FeatureView::<Time, Time>::new(t.borrow(), t.borrow(), i.borrow());
                Some($then)
            } else {
                None
            }
        } else {
            None
        }
    };
}

#[allow(unused)]
pub(crate) fn as_simple_feature(chromatogram: &Chromatogram) -> Option<SimpleFeature<MZ, Time>> {
    if let Ok(t) = chromatogram.time() {
        if let Ok(i) = chromatogram.intensity() {
            let mut f = SimpleFeature::<MZ, Time>::empty(0.0);
            f.extend(t.iter().zip(i.iter()).map(|(y, z)| (0.0f64, *y, *z)));
            return Some(f);
        }
    }
    None
}

impl TimeInterval<Time> for Chromatogram {
    fn start_time(&self) -> Option<f64> {
        if let Ok(t) = self.time() {
            t.first().copied()
        } else {
            None
        }
    }

    fn end_time(&self) -> Option<f64> {
        if let Ok(t) = self.time() {
            t.last().copied()
        } else {
            None
        }
    }

    fn apex_time(&self) -> Option<f64> {
        as_feature_view!(self, view => {
            view.apex_time()
        })?
    }

    fn area(&self) -> f32 {
        as_feature_view!(self, view => {
            view.area()
        })
        .unwrap()
    }

    fn iter_time(&self) -> impl Iterator<Item = f64> {
        if let Ok(t) = self.time() {
            // Not ideal, but we cannot know if the time array is materialized at this point.
            Vec::from(t).into_iter()
        } else {
            Vec::from(EMPTY).into_iter()
        }
    }
}

pub trait ChromatogramLike {
    /// The method to access the spectrum description itself, which supplies
    /// the data for most other methods on this trait.
    fn description(&self) -> &ChromatogramDescription;

    fn description_mut(&mut self) -> &mut ChromatogramDescription;

    /// Access the precursor information, if it exists.
    #[inline]
    fn precursor(&self) -> Option<&Precursor> {
        let desc = self.description();
        if let Some(precursor) = &desc.precursor {
            Some(precursor)
        } else {
            None
        }
    }

    #[inline]
    fn start_time(&self) -> Option<f64> {
        if let Ok(t) = self.time() {
            t.first().copied()
        } else {
            None
        }
    }

    #[inline]
    fn end_time(&self) -> Option<f64> {
        if let Ok(t) = self.time() {
            t.last().copied()
        } else {
            None
        }
    }

    /// Access the MS exponentiation level
    #[inline]
    fn ms_level(&self) -> Option<u8> {
        self.description().ms_level
    }

    /// Access the native ID string for the spectrum
    #[inline]
    fn id(&self) -> &str {
        &self.description().id
    }

    #[inline]
    fn chromatogram_typ(&self) -> ChromatogramType {
        self.description().chromatogram_type
    }

    /// Access the index of the spectrum in the source file
    #[inline]
    fn index(&self) -> usize {
        self.description().index
    }

    #[inline]
    fn polarity(&self) -> ScanPolarity {
        self.description().polarity
    }

    fn is_aggregate(&self) -> bool {
        self.description().is_aggregate()
    }

    fn is_electromagnetic_radiation(&self) -> bool {
        self.description().is_electromagnetic_radiation()
    }

    fn is_ion_current(&self) -> bool {
        self.description().is_ion_current()
    }

    fn time(&self) -> Result<Cow<'_, [f64]>, ArrayRetrievalError>;
    fn intensity(&self) -> Result<Cow<'_, [f32]>, ArrayRetrievalError>;
}

impl Chromatogram {
    pub fn new(description: ChromatogramDescription, arrays: BinaryArrayMap) -> Self {
        Self {
            description,
            arrays,
        }
    }

    pub fn time(&self) -> Result<Cow<'_, [f64]>, ArrayRetrievalError> {
        if let Some(a) = self.arrays.get(&ArrayType::TimeArray) {
            a.to_f64()
        } else {
            Err(ArrayRetrievalError::NotFound(ArrayType::TimeArray))
        }
    }

    pub fn intensity(&self) -> Result<Cow<'_, [f32]>, ArrayRetrievalError> {
        if let Some(a) = self.arrays.get(&ArrayType::IntensityArray) {
            a.to_f32()
        } else {
            Err(ArrayRetrievalError::NotFound(ArrayType::IntensityArray))
        }
    }

    pub fn apex_time(&self) -> Option<f64> {
        TimeInterval::apex_time(&self)
    }

    pub fn area(&self) -> f32 {
        TimeInterval::area(&self)
    }
}

impl ChromatogramLike for Chromatogram {
    fn description(&self) -> &ChromatogramDescription {
        &self.description
    }

    fn time(&self) -> Result<Cow<'_, [f64]>, ArrayRetrievalError> {
        self.time()
    }

    fn intensity(&self) -> Result<Cow<'_, [f32]>, ArrayRetrievalError> {
        self.intensity()
    }

    fn description_mut(&mut self) -> &mut ChromatogramDescription {
        &mut self.description
    }
}

impl ParamDescribed for Chromatogram {
    fn params(&self) -> &[Param] {
        self.description.params()
    }

    fn params_mut(&mut self) -> &mut crate::ParamList {
        self.description.params_mut()
    }
}