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
//! A type system implementation of a coordinate system that attempts to deal with the different dimensions
//! an observation may be placed in simultaneously.
use std::{
    error::Error,
    fmt::Display,
    marker::PhantomData,
    num::ParseFloatError,
    ops::{Bound, Range, RangeBounds, RangeTo},
    str::FromStr,
};

#[derive(Default, Debug, Clone, Copy, PartialEq, PartialOrd)]
/// The Mass To Charge Ratio (m/z) coordinate system
pub struct MZ();

impl MZ {
    /// Access the m/z of the coordinate type
    #[inline]
    pub fn coordinate<T: CoordinateLike<MZ>>(inst: &T) -> f64 {
        CoordinateLike::<MZ>::coordinate(inst)
    }
}

#[derive(Default, Debug, Clone, Copy)]
/// The Mass coordinate system
pub struct Mass();

impl Mass {
    /// Access the neutral mass of the coordinate type
    #[inline]
    pub fn coordinate<T: CoordinateLike<Mass>>(inst: &T) -> f64 {
        CoordinateLike::<Mass>::coordinate(inst)
    }
}

#[derive(Default, Debug, Clone, Copy)]
/// The Event Time coordinate system
pub struct Time();
impl Time {
    /// Access the elapsed time of the coordinate type
    #[inline]
    pub fn coordinate<T: CoordinateLike<Time>>(inst: &T) -> f64 {
        CoordinateLike::<Time>::coordinate(inst)
    }
}

#[derive(Default, Debug, Clone, Copy)]
/// The Ion Mobility Time coordinate system
pub struct IonMobility();
impl IonMobility {
    /// Access the ion mobility time unit of the coordinate type
    #[inline]
    pub fn coordinate<T: CoordinateLike<IonMobility>>(inst: &T) -> f64 {
        CoordinateLike::<IonMobility>::coordinate(inst)
    }
}

pub trait CoordinateSystem : Sized {

    #[inline]
    fn coordinate<T: CoordinateLike<Self>>(&self, inst: &T) -> f64 {
        CoordinateLike::<Self>::coordinate(inst)
    }

    fn coordinate_mut<'a, T: CoordinateLikeMut<Self>>(&self, inst: &'a mut T) -> &'a mut f64 {
        CoordinateLikeMut::<Self>::coordinate_mut(inst)
    }
}

impl CoordinateSystem for MZ {}
impl CoordinateSystem for Mass {}
impl CoordinateSystem for Time {}
impl CoordinateSystem for IonMobility {}

/// Denote a type has a coordinate value on coordinate system `T`
pub trait CoordinateLike<T>: PartialOrd {
    /// The trait method for accessing the coordinate of the object on coordinate
    /// system `T`
    fn coordinate(&self) -> f64;
}

/// A [`CoordinateLike`] structure whose coordinate is mutable
pub trait CoordinateLikeMut<T>: CoordinateLike<T> {
    fn coordinate_mut(&mut self) -> &mut f64;
}

/// A named coordinate system membership for neutral mass
pub trait MassLocated: CoordinateLike<Mass> {
    #[inline]
    fn neutral_mass(&self) -> f64 {
        CoordinateLike::<Mass>::coordinate(self)
    }
}

/// A named coordinate system membership for m/z
pub trait MZLocated: CoordinateLike<MZ> {
    #[inline]
    fn mz(&self) -> f64 {
        CoordinateLike::<MZ>::coordinate(self)
    }
}

pub trait TimeLocated: CoordinateLike<Time> {
    #[inline]
    fn time(&self) -> f64 {
        CoordinateLike::<Time>::coordinate(self)
    }
}

pub trait IonMobilityLocated: CoordinateLike<IonMobility> {
    #[inline]
    fn ion_mobility(&self) -> f64 {
        CoordinateLike::<IonMobility>::coordinate(self)
    }
}

impl<T: CoordinateLike<C>, C> CoordinateLike<C> for &T {
    fn coordinate(&self) -> f64 {
        (*self).coordinate()
    }
}

impl<T: CoordinateLike<C>, C> CoordinateLike<C> for &mut T {
    fn coordinate(&self) -> f64 {
        CoordinateLike::<C>::coordinate(*self)
    }
}

impl<T: CoordinateLikeMut<C>, C> CoordinateLikeMut<C> for &mut T {
    fn coordinate_mut(&mut self) -> &mut f64 {
        CoordinateLikeMut::<C>::coordinate_mut(*self)
    }
}

impl<T: CoordinateLike<Mass>> MassLocated for T {}
impl<T: CoordinateLike<MZ>> MZLocated for T {}

impl<T: CoordinateLike<Time>> TimeLocated for T {}
impl<T: CoordinateLike<IonMobility>> IonMobilityLocated for T {}

/// A type alias for the index in an [`IndexedCoordinate`] structure
pub type IndexType = u32;

/// Indicate that an object may be indexed by coordinate system `T`
pub trait IndexedCoordinate<T>: CoordinateLike<T> {
    fn get_index(&self) -> IndexType;
    fn set_index(&mut self, index: IndexType);
}

impl<T: IndexedCoordinate<C>, C> IndexedCoordinate<C> for &T {
    fn get_index(&self) -> IndexType {
        (*self).get_index()
    }

    fn set_index(&mut self, _index: IndexType) {}
}

/// An interval within a single dimension
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct CoordinateRange<C> {
    pub start: Option<f64>,
    pub end: Option<f64>,
    coord: PhantomData<C>,
}

impl<C> CoordinateRange<C> {
    pub fn new(start: Option<f64>, end: Option<f64>) -> Self {
        Self {
            start,
            end,
            coord: PhantomData,
        }
    }

    pub fn contains<T: CoordinateLike<C>>(&self, point: &T) -> bool {
        let x = CoordinateLike::<C>::coordinate(point);
        RangeBounds::<f64>::contains(&self, &x)
    }

    pub fn contains_raw(&self, x: &f64) -> bool {
        RangeBounds::<f64>::contains(&self, x)
    }

    pub fn overlaps<T: RangeBounds<f64>>(&self, interval: &T) -> bool {
        let interval_start = match interval.start_bound() {
            Bound::Included(x) => *x,
            Bound::Excluded(x) => *x,
            Bound::Unbounded => 0.0,
        };

        let interval_end = match interval.end_bound() {
            Bound::Included(y) => *y,
            Bound::Excluded(y) => *y,
            Bound::Unbounded => f64::INFINITY,
        };
        self.end.unwrap_or(f64::INFINITY) >= interval_start
            && interval_end >= self.start.unwrap_or(0.0)
    }
}

impl<C> Default for CoordinateRange<C> {
    fn default() -> Self {
        Self {
            start: None,
            end: None,
            coord: PhantomData,
        }
    }
}

#[derive(Debug)]
pub enum CoordinateRangeParseError {
    MalformedStart(ParseFloatError),
    MalformedEnd(ParseFloatError),
}

impl Display for CoordinateRangeParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CoordinateRangeParseError::MalformedStart(e) => {
                write!(f, "Failed to parse range start {e}")
            }
            CoordinateRangeParseError::MalformedEnd(e) => {
                write!(f, "Failed to parse range end {e}")
            }
        }
    }
}

impl Error for CoordinateRangeParseError {}

impl<C> FromStr for CoordinateRange<C> {
    type Err = CoordinateRangeParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut tokens = if s.contains(' ') {
            s.split(' ')
        } else if s.contains(':') {
            s.split(':')
        } else if s.contains('-') {
            s.split('-')
        } else {
            s.split(' ')
        };
        let start_s = tokens.next().unwrap();
        let start_t = if start_s.is_empty() {
            None
        } else {
            match start_s.parse() {
                Ok(val) => Some(val),
                Err(e) => return Err(CoordinateRangeParseError::MalformedStart(e)),
            }
        };
        let end_s = tokens.next().unwrap();
        let end_t = if end_s.is_empty() {
            None
        } else {
            match end_s.parse() {
                Ok(val) => Some(val),
                Err(e) => return Err(CoordinateRangeParseError::MalformedEnd(e)),
            }
        };
        Ok(CoordinateRange {
            start: start_t,
            end: end_t,
            coord: PhantomData,
        })
    }
}

impl<C> From<RangeTo<f64>> for CoordinateRange<C> {
    fn from(value: RangeTo<f64>) -> Self {
        Self::new(None, Some(value.end))
    }
}

impl<C> From<Range<f64>> for CoordinateRange<C> {
    fn from(value: Range<f64>) -> Self {
        Self::new(Some(value.start), Some(value.end))
    }
}

impl<C> RangeBounds<f64> for CoordinateRange<C> {
    fn start_bound(&self) -> Bound<&f64> {
        if let Some(start) = self.start.as_ref() {
            Bound::Included(start)
        } else {
            Bound::Unbounded
        }
    }

    fn end_bound(&self) -> Bound<&f64> {
        if let Some(end) = self.end.as_ref() {
            Bound::Included(end)
        } else {
            Bound::Unbounded
        }
    }
}

impl<C> RangeBounds<f64> for &CoordinateRange<C> {
    fn start_bound(&self) -> Bound<&f64> {
        (*self).start_bound()
    }

    fn end_bound(&self) -> Bound<&f64> {
        (*self).end_bound()
    }
}

impl<C> From<(f64, f64)> for CoordinateRange<C> {
    fn from(value: (f64, f64)) -> Self {
        Self::new(Some(value.0), Some(value.1))
    }
}

impl<C> From<CoordinateRange<C>> for Range<f64> {
    fn from(value: CoordinateRange<C>) -> Self {
        let start = value.start.unwrap_or(0.0);
        let end = value.end.unwrap_or(f64::INFINITY);

        start..end
    }
}


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

    fn check_coord<C: CoordinateSystem, P: CoordinateLike<C>>(peak: &P, cs: &C) -> f64 {
        cs.coordinate(peak)
    }

    #[test]
    fn test_coordinate_system() {
        let mut peak = DeconvolutedPeak::new(204.09, 300.0, 2, 0);
        let mass = check_coord(&peak, &Mass());
        let mz = check_coord(&peak, &MZ());

        assert_eq!(peak.neutral_mass(), mass);
        assert_eq!(peak.mz(), mz);

        *Mass().coordinate_mut(&mut peak) = 9001.0;
    }

}