mzpeaks/
peak.rs

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
//! A peak is the most atomic unit of a (processed) mass spectrum. It represents
//! a location in one (or more) coordinate spaces with an measured intensity value
//!
//! All peak-like types implement [`PartialEq`], [`PartialOrd`], and [`CoordinateLike`]
//!

use std::cmp::Ordering;
use std::fmt;

use crate::coordinate::{CoordinateLike, IndexType, IndexedCoordinate, Mass, MZ};
use crate::{implement_centroidlike_inner, implement_deconvoluted_centroidlike_inner, CoordinateLikeMut, IonMobility};
use crate::{MZLocated, MassLocated};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// An intensity measurement is an entity that has a measured intensity
/// of whateger it is.
pub trait IntensityMeasurement {
    fn intensity(&self) -> f32;
}

pub trait IntensityMeasurementMut: IntensityMeasurement {
    fn intensity_mut(&mut self) -> &mut f32;
}

impl<T: IntensityMeasurement> IntensityMeasurement for &T {
    fn intensity(&self) -> f32 {
        (*self).intensity()
    }
}

impl<T: IntensityMeasurement> IntensityMeasurement for &mut T {
    fn intensity(&self) -> f32 {
        IntensityMeasurement::intensity(*self)
    }
}

impl<T: IntensityMeasurementMut> IntensityMeasurementMut for &mut T {
    fn intensity_mut(&mut self) -> &mut f32 {
        IntensityMeasurementMut::intensity_mut(*self)
    }
}

/// A [`CentroidLike`] entity is indexed in m/z coordinate space and
/// is an [`IntensityMeasurement`]
pub trait CentroidLike: IndexedCoordinate<MZ> + IntensityMeasurement {
    #[inline]
    fn as_centroid(&self) -> CentroidPeak {
        CentroidPeak {
            mz: self.coordinate(),
            intensity: self.intensity(),
            index: self.get_index(),
        }
    }
}

/// A known charge has a determined charge state value
pub trait KnownCharge {
    fn charge(&self) -> i32;
}

impl<T: KnownCharge> KnownCharge for &T {
    fn charge(&self) -> i32 {
        (*self).charge()
    }
}

pub trait KnownChargeMut: KnownCharge {
    fn charge_mut(&mut self) -> &mut i32;
}

impl<T: KnownCharge> KnownCharge for &mut T {
    fn charge(&self) -> i32 {
        KnownCharge::charge(*self)
    }
}

impl<T: KnownChargeMut> KnownChargeMut for &mut T {
    fn charge_mut(&mut self) -> &mut i32 {
        KnownChargeMut::charge_mut(*self)
    }
}

/// A [`DeconvolutedCentroidLike`] entity is indexed in the neutral mass
/// coordinate space, has known charge state and an aggregated intensity
/// measurement. Any [`DeconvolutedCentroidLike`] can be converted into
/// a [`DeconvolutedPeak`]
pub trait DeconvolutedCentroidLike:
    IndexedCoordinate<Mass> + IntensityMeasurement + KnownCharge
{
    fn as_centroid(&self) -> DeconvolutedPeak {
        DeconvolutedPeak {
            neutral_mass: self.coordinate(),
            intensity: self.intensity(),
            charge: self.charge(),
            index: self.get_index(),
        }
    }
}

/// Represent a single m/z coordinate with an
/// intensity and an index. Nearly the most basic
/// peak representation for peak-picked data.
#[derive(Default, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CentroidPeak {
    pub mz: f64,
    pub intensity: f32,
    pub index: IndexType,
}

impl CentroidPeak {
    #[inline]
    pub fn new(mz: f64, intensity: f32, index: IndexType) -> CentroidPeak {
        CentroidPeak {
            mz,
            intensity,
            index,
        }
    }
}

impl fmt::Display for CentroidPeak {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "CentroidPeak({}, {}, {})",
            self.mz, self.intensity, self.index
        )
    }
}

implement_centroidlike_inner!(CentroidPeak, true, false);

impl<T: IndexedCoordinate<MZ> + IntensityMeasurement> CentroidLike for T {}

impl<T: IndexedCoordinate<Mass> + IntensityMeasurement + KnownCharge> DeconvolutedCentroidLike
    for T
{
}

#[derive(Debug, Clone, Default, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MZPoint {
    pub mz: f64,
    pub intensity: f32,
}

impl MZPoint {
    #[inline]
    pub fn new(mz: f64, intensity: f32) -> MZPoint {
        MZPoint { mz, intensity }
    }
}

impl CoordinateLike<MZ> for MZPoint {
    fn coordinate(&self) -> f64 {
        self.mz
    }
}

impl IntensityMeasurement for MZPoint {
    #[inline]
    fn intensity(&self) -> f32 {
        self.intensity
    }
}

impl IntensityMeasurementMut for MZPoint {
    #[inline]
    fn intensity_mut(&mut self) -> &mut f32 {
        &mut self.intensity
    }
}

impl IndexedCoordinate<MZ> for MZPoint {
    #[inline]
    fn get_index(&self) -> IndexType {
        0
    }
    fn set_index(&mut self, _index: IndexType) {}
}

impl From<MZPoint> for CentroidPeak {
    fn from(peak: MZPoint) -> Self {
        CentroidPeak {
            mz: peak.mz,
            intensity: peak.intensity,
            index: 0,
        }
    }
}

impl From<CentroidPeak> for MZPoint {
    fn from(peak: CentroidPeak) -> Self {
        let mut inst = Self {
            mz: peak.coordinate(),
            intensity: peak.intensity(),
        };
        inst.set_index(peak.index);
        inst
    }
}

#[derive(Default, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// Represent a single neutral mass coordinate with an
/// intensity, a known charge and an index.
pub struct DeconvolutedPeak {
    pub neutral_mass: f64,
    pub intensity: f32,
    pub charge: i32,
    pub index: IndexType,
}

impl DeconvolutedPeak {
    pub fn new(neutral_mass: f64, intensity: f32, charge: i32, index: IndexType) -> Self {
        Self {
            neutral_mass,
            intensity,
            charge,
            index,
        }
    }

    pub fn mz(&self) -> f64 {
        let charge_carrier: f64 = 1.007276;
        let charge = self.charge as f64;
        (self.neutral_mass + charge_carrier * charge) / charge
    }
}

implement_deconvoluted_centroidlike_inner!(DeconvolutedPeak, true, false);

impl fmt::Display for DeconvolutedPeak {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "DeconvolutedPeak({}, {}, {}, {})",
            self.neutral_mass, self.intensity, self.charge, self.index
        )
    }
}

impl CoordinateLike<MZ> for DeconvolutedPeak {
    fn coordinate(&self) -> f64 {
        self.mz()
    }
}

/// A reference wrapper for [`CentroidLike`] peaks.
///
/// The wrapper has its own [`IndexedCoordinate`] implementation
/// managed separately from the source. This allows them to be re-sorted
/// and indexed independently.
#[derive(Debug, Clone, Copy)]
pub struct CentroidRef<'a, C: CentroidLike> {
    inner: &'a C,
    index: IndexType,
}

impl<'a, C: CentroidLike> PartialEq for CentroidRef<'a, C> {
    fn eq(&self, other: &Self) -> bool {
        if (self.mz() - other.coordinate()).abs() > 1e-3
            || (self.intensity() - other.intensity()).abs() > 1e-3
        {
            return false;
        }
        true
    }
}

impl<'a, C: CentroidLike> PartialOrd for CentroidRef<'a, C> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(
            self.mz()
                .total_cmp(&other.mz())
                .then_with(|| self.intensity().total_cmp(&other.intensity())),
        )
    }
}

impl<'a, C: CentroidLike> CentroidRef<'a, C> {
    pub fn new(inner: &'a C, index: IndexType) -> Self {
        Self { inner, index }
    }
}

impl<'a, C: CentroidLike> CoordinateLike<MZ> for CentroidRef<'a, C> {
    fn coordinate(&self) -> f64 {
        self.inner.mz()
    }
}

impl<'a, C: CentroidLike> IntensityMeasurement for CentroidRef<'a, C> {
    #[inline]
    fn intensity(&self) -> f32 {
        self.inner.intensity()
    }
}

impl<'a, C: CentroidLike> IndexedCoordinate<MZ> for CentroidRef<'a, C> {
    #[inline]
    fn get_index(&self) -> IndexType {
        self.index
    }
    fn set_index(&mut self, index: IndexType) {
        self.index = index
    }
}

/// A reference wrapper for [`DeconvolutedCentroidLike`] peaks.
///
/// The wrapper has its own [`IndexedCoordinate`] implementation
/// managed separately from the source. This allows them to be re-sorted
/// and indexed independently.
#[derive(Debug, Clone, Copy)]
pub struct DeconvolutedCentroidRef<'a, D: DeconvolutedCentroidLike> {
    inner: &'a D,
    index: IndexType,
}

impl<'a, D: DeconvolutedCentroidLike> PartialEq for DeconvolutedCentroidRef<'a, D> {
    fn eq(&self, other: &Self) -> bool {
        if (self.neutral_mass() - other.coordinate()).abs() > 1e-3
            || self.charge() != other.charge()
            || (self.intensity() - other.intensity()).abs() > 1e-3
        {
            return false;
        }
        true
    }
}

impl<'a, D: DeconvolutedCentroidLike> PartialOrd for DeconvolutedCentroidRef<'a, D> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(
            self.neutral_mass()
                .total_cmp(&other.neutral_mass())
                .then_with(|| self.intensity().total_cmp(&other.intensity())),
        )
    }
}

impl<'a, D: DeconvolutedCentroidLike> DeconvolutedCentroidRef<'a, D> {
    pub fn new(inner: &'a D, index: IndexType) -> Self {
        Self { inner, index }
    }
}

impl<'a, D: DeconvolutedCentroidLike> CoordinateLike<Mass> for DeconvolutedCentroidRef<'a, D> {
    fn coordinate(&self) -> f64 {
        self.inner.neutral_mass()
    }
}

impl<'a, D: DeconvolutedCentroidLike> KnownCharge for DeconvolutedCentroidRef<'a, D> {
    fn charge(&self) -> i32 {
        self.inner.charge()
    }
}

impl<'a, D: DeconvolutedCentroidLike> IntensityMeasurement for DeconvolutedCentroidRef<'a, D> {
    #[inline]
    fn intensity(&self) -> f32 {
        self.inner.intensity()
    }
}

impl<'a, D: DeconvolutedCentroidLike> IndexedCoordinate<Mass> for DeconvolutedCentroidRef<'a, D> {
    #[inline]
    fn get_index(&self) -> IndexType {
        self.index
    }
    fn set_index(&mut self, index: IndexType) {
        self.index = index
    }
}

impl<'a, D: DeconvolutedCentroidLike> CoordinateLike<MZ> for DeconvolutedCentroidRef<'a, D>
where
    D: CoordinateLike<MZ>,
{
    fn coordinate(&self) -> f64 {
        <D as CoordinateLike<MZ>>::coordinate(self.inner)
    }
}

/// Represent a single m/z coordinate and ion mobility coordinate with an
/// intensity and an index.
#[derive(Debug, Default, Clone, PartialEq, PartialOrd)]
pub struct IonMobilityAwareCentroidPeak {
    pub mz: f64,
    pub ion_mobility: f64,
    pub intensity: f32,
    pub index: u32,
}

impl CoordinateLike<MZ> for IonMobilityAwareCentroidPeak {
    fn coordinate(&self) -> f64 {
        self.mz
    }
}

impl CoordinateLike<IonMobility> for IonMobilityAwareCentroidPeak {
    fn coordinate(&self) -> f64 {
        self.ion_mobility
    }
}

impl IntensityMeasurement for IonMobilityAwareCentroidPeak {
    fn intensity(&self) -> f32 {
        self.intensity
    }
}

impl CoordinateLikeMut<MZ> for IonMobilityAwareCentroidPeak {
    fn coordinate_mut(&mut self) -> &mut f64 {
        &mut self.mz
    }
}

impl CoordinateLikeMut<IonMobility> for IonMobilityAwareCentroidPeak {
    fn coordinate_mut(&mut self) -> &mut f64 {
        &mut self.ion_mobility
    }
}

impl IndexedCoordinate<MZ> for IonMobilityAwareCentroidPeak {
    fn get_index(&self) -> IndexType {
        self.index
    }

    fn set_index(&mut self, index: IndexType) {
        self.index = index
    }
}

impl IntensityMeasurementMut for IonMobilityAwareCentroidPeak {
    fn intensity_mut(&mut self) -> &mut f32 {
        &mut self.intensity
    }
}

impl IonMobilityAwareCentroidPeak {
    pub fn new(mz: f64, ion_mobility: f64, intensity: f32, index: u32) -> Self {
        Self { mz, ion_mobility, intensity, index }
    }
}


/// Represent a single neutral mass coordinate and ion mobility coordinate with an
/// intensity, a known charge and an index.
#[derive(Debug, Default, Clone, PartialEq, PartialOrd)]
pub struct IonMobilityAwareDeconvolutedPeak {
    pub neutral_mass: f64,
    pub ion_mobility: f64,
    pub charge: i32,
    pub intensity: f32,
    pub index: u32,
}

impl IonMobilityAwareDeconvolutedPeak {
    pub fn new(neutral_mass: f64, ion_mobility: f64, charge: i32, intensity: f32, index: u32) -> Self {
        Self {
            neutral_mass,
            ion_mobility,
            charge,
            intensity,
            index,
        }
    }
}

impl CoordinateLike<Mass> for IonMobilityAwareDeconvolutedPeak {
    fn coordinate(&self) -> f64 {
        self.neutral_mass
    }
}

impl CoordinateLike<MZ> for IonMobilityAwareDeconvolutedPeak {
    fn coordinate(&self) -> f64 {
        self.as_centroid().mz()
    }
}

impl CoordinateLike<IonMobility> for IonMobilityAwareDeconvolutedPeak {
    fn coordinate(&self) -> f64 {
        self.ion_mobility
    }
}

impl CoordinateLikeMut<Mass> for IonMobilityAwareDeconvolutedPeak {
    fn coordinate_mut(&mut self) -> &mut f64 {
        &mut self.neutral_mass
    }
}

impl CoordinateLikeMut<IonMobility> for IonMobilityAwareDeconvolutedPeak {
    fn coordinate_mut(&mut self) -> &mut f64 {
        &mut self.ion_mobility
    }
}

impl From<IonMobilityAwareDeconvolutedPeak> for DeconvolutedPeak {
    fn from(value: IonMobilityAwareDeconvolutedPeak) -> Self {
        Self::new(
            value.neutral_mass,
            value.intensity,
            value.charge,
            value.index,
        )
    }
}

impl IntensityMeasurement for IonMobilityAwareDeconvolutedPeak {
    fn intensity(&self) -> f32 {
        self.intensity
    }
}

impl IntensityMeasurementMut for IonMobilityAwareDeconvolutedPeak {
    fn intensity_mut(&mut self) -> &mut f32 {
        &mut self.intensity
    }
}

impl KnownCharge for IonMobilityAwareDeconvolutedPeak {
    fn charge(&self) -> i32 {
        self.charge
    }
}

impl KnownChargeMut for IonMobilityAwareDeconvolutedPeak {
    fn charge_mut(&mut self) -> &mut i32 {
        &mut self.charge
    }
}

impl IndexedCoordinate<Mass> for IonMobilityAwareDeconvolutedPeak {
    fn get_index(&self) -> IndexType {
        self.index
    }

    fn set_index(&mut self, index: IndexType) {
        self.index = index;
    }
}


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

    #[test]
    fn test_conversion() {
        let x = CentroidPeak::new(204.07, 5000f32, 19);
        let y: MZPoint = x.clone().into();
        assert_eq!(y.mz, x.mz);
        assert_eq!(y.coordinate(), x.coordinate());
        assert_eq!(y.intensity(), x.intensity());
        // MZPoint doesn't use index
        let mut z: CentroidPeak = y.clone().into();
        assert_eq!(z, y);
        *z.intensity_mut() += 500.0;
        assert!(x < z);
        assert!(z > x);
        assert!(x == x);
        assert!(z != x);

        let xr = CentroidRef::new(&x, 0);
        let zr = CentroidRef::new(&z, 0);
        assert!(xr < zr);
        assert!(zr > xr);
        assert!(xr == xr);
        assert!(zr != xr);
    }

    #[test]
    fn test_to_string() {
        let x = CentroidPeak::new(204.07, 5000f32, 19);
        assert!(x.to_string().starts_with("CentroidPeak"));

        let x = DeconvolutedPeak {
            neutral_mass: 799.359964027,
            charge: 2,
            intensity: 5000f32,
            index: 1,
        };

        assert!(x.to_string().starts_with("DeconvolutedPeak"));
    }

    #[test]
    fn test_coordinate_context() {
        let x = DeconvolutedPeak {
            neutral_mass: 799.359964027,
            charge: 2,
            intensity: 5000f32,
            index: 1,
        };
        assert_eq!(x.neutral_mass, 799.359964027);
        assert_eq!(CoordinateLike::<Mass>::coordinate(&x), 799.359964027);
        assert_eq!(Mass::coordinate(&x), 799.359964027);
        assert!((x.mz() - 400.68725848027003).abs() < 1e-6);
        assert!((MZ::coordinate(&x) - 400.68725848027003).abs() < 1e-6);

        let mut y = x.as_centroid();
        *(&mut y).intensity_mut() += 500.0;
        assert!(x < y);
        assert!(y > x);
        assert!(x == x);
        assert!(y != x);

        let xr = DeconvolutedCentroidRef::new(&x, 0);
        let yr = DeconvolutedCentroidRef::new(&y, 0);
        assert!(xr < yr);
        assert!(yr > xr);
        assert!(xr == xr);
        assert!(yr != xr);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serialize() -> std::io::Result<()> {
        use serde_json;
        use std::io;
        use std::io::prelude::*;

        let mut buff = Vec::new();
        let buffer_writer = io::Cursor::new(&mut buff);
        let mut writer = io::BufWriter::new(buffer_writer);

        let x = CentroidPeak::new(204.07, 5000f32, 19);
        // let y: MZPoint = x.clone().into();
        serde_json::to_writer_pretty(&mut writer, &x)?;
        writer.flush()?;
        let view = String::from_utf8_lossy(writer.get_ref().get_ref());
        let peak: CentroidPeak = serde_json::from_str(&view)?;
        assert!((peak.mz() - x.mz()).abs() < 1e-6);
        Ok(())
    }
}