mzcore 0.2.0

Core logic for handling massspectrometry in Rust.
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
use std::{
    fmt::Write,
    hash::Hash,
    num::NonZeroU16,
    ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign},
};

use ordered_float::OrderedFloat;
use serde::{Deserialize, Serialize};
use thin_vec::ThinVec;

use crate::{
    chemistry::{Element, MassMode, MassOutputType},
    glycan::{GlycanPosition, MonoSaccharide},
    sequence::{AminoAcid, CrossLinkName, SequencePosition},
    space::{Space, UsedSpace},
    system::{Mass, f64},
};

/// A molecular formula, a selection of elements of specified isotopes together forming a structure
#[allow(clippy::unsafe_derive_deserialize)]
#[derive(Clone, Default, Deserialize, Hash, Ord, PartialOrd, Serialize)]
pub struct MolecularFormula {
    /// Save all constituent parts as the element in question, the isotope (or None for natural
    /// distribution), and the number of this part The elements will be sorted on
    /// element/isotope and deduplicated, guaranteed to only contain valid isotopes.
    // TODO: this structure can be shrunk to half its size by using an i8 to indicate the isotope
    // (n-Z-32) and switch to i16 amounts and allow overflow into multiple entries
    pub(in super::super) elements: ThinVec<(Element, Option<NonZeroU16>, i32)>,
    /// Any additional mass, defined to be monoisotopic
    pub(in super::super) additional_mass: OrderedFloat<f64>,
    /// The labels of sources of ambiguity/multiplicity
    #[serde(default)]
    pub(in super::super) labels: ThinVec<AmbiguousLabel>,
}

impl PartialEq for MolecularFormula {
    fn eq(&self, other: &Self) -> bool {
        self.elements == other.elements && self.additional_mass == other.additional_mass
    }
}

impl Eq for MolecularFormula {}

impl std::fmt::Debug for MolecularFormula {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use itertools::Itertools;
        write!(
            f,
            "{} [{}]",
            self.hill_notation(),
            self.labels.iter().map(ToString::to_string).join(",")
        )
    }
}

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

impl Space for MolecularFormula {
    fn space(&self) -> UsedSpace {
        (self.elements.space() + self.additional_mass.space() + self.labels.space())
            .set_total::<Self>()
    }
}

impl MassOutputType for MolecularFormula {
    fn labels(&self) -> &[AmbiguousLabel] {
        &self.labels
    }

    fn with_label(mut self, label: AmbiguousLabel) -> Self {
        self.labels.push(label);
        self
    }

    fn with_labels(mut self, labels: &[AmbiguousLabel]) -> Self {
        self.labels.extend_from_slice(labels);
        self
    }

    /// Create a new molecular formula with the given global isotope modifications. If the given
    /// isotope is not valid for this element it returns `None`.
    fn with_global_isotope_modifications(
        self,
        substitutions: &[(Element, Option<NonZeroU16>)],
    ) -> Option<Self> {
        if substitutions.is_empty() {
            Some(self.clone())
        } else if substitutions.iter().all(|e| e.0.is_valid(e.1)) {
            let mut new_elements = self.elements.clone();
            for item in &mut new_elements {
                for (substitute_element, substitute_species) in substitutions {
                    if item.0 == *substitute_element {
                        item.1 = *substitute_species;
                    }
                }
            }
            let result = Self {
                elements: new_elements,
                additional_mass: self.additional_mass,
                labels: self.labels.clone(),
            };
            Some(result.simplify())
        } else {
            None
        }
    }

    /// Get the number of electrons (the only charged species, any ionic species is saved as that
    /// element +/- the correct number of electrons). The inverse of that number is given as the
    /// charge.
    fn charge(&self) -> crate::system::isize::Charge {
        -self
            .elements
            .iter()
            .find(|el| el.0 == Element::Electron)
            .map_or_else(crate::system::isize::Charge::default, |el| {
                crate::system::isize::Charge::new::<crate::system::charge::e>(el.2 as isize)
            })
    }

    /// Check if this formula contains a negative number of any element (ignores a negative number
    /// of electrons).
    fn contains_negative_amount(&self) -> bool {
        self.elements().iter().any(|e| e.0 != Element::Electron && e.2 < 0)
    }

    fn as_formula(&self) -> MolecularFormula {
        self.clone()
    }

    fn mass(&self, mode: MassMode) -> Mass {
        match mode {
            MassMode::Monoisotopic => self.monoisotopic_mass(),
            MassMode::Average => self.average_weight(),
            #[cfg(feature = "isotopes")]
            MassMode::MostAbundant => self.most_abundant_mass(),
        }
    }
}

/// Keep track of what ambiguous option is used
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum AmbiguousLabel {
    /// An ambiguous amino acid, with the actual amino acid used tracked
    AminoAcid {
        /// Which amino acid is used
        option: AminoAcid,
        /// What location in the sequence are we talking about
        sequence_index: usize,
        /// Peptidoform index
        peptidoform_index: usize,
        /// Peptidoform ion index
        peptidoform_ion_index: usize,
    },
    /// An ambiguous modification, with the actual position
    Modification {
        /// Which ambiguous modification
        id: usize,
        /// Which location
        sequence_index: SequencePosition,
        /// Peptidoform index
        peptidoform_index: usize,
        /// Peptidoform ion index
        peptidoform_ion_index: usize,
    },
    /// The actual charge used, when there are multiple charge carriers
    ChargeCarrier(MolecularFormula),
    /// An intact cross-link
    CrossLinkBound(CrossLinkName),
    /// A broken cross-link, having the name and the stub that was left in its place
    CrossLinkBroken(CrossLinkName, MolecularFormula),
    /// A glycan fragment on a peptide fragment, with the Y breakages that lead to that fragment
    GlycanFragment(Vec<GlycanPosition>),
    /// A glycan fragment on a peptide fragment, with the monosaccharides that make up the fragment
    GlycanFragmentComposition(Vec<(MonoSaccharide, isize)>),
}

impl Space for AmbiguousLabel {
    fn space(&self) -> UsedSpace {
        (UsedSpace::stack(1)
            + match self {
                Self::AminoAcid {
                    option,
                    sequence_index,
                    peptidoform_index,
                    peptidoform_ion_index,
                } => {
                    option.space()
                        + sequence_index.space()
                        + peptidoform_index.space()
                        + peptidoform_ion_index.space()
                }
                Self::Modification {
                    id,
                    sequence_index,
                    peptidoform_index,
                    peptidoform_ion_index,
                } => {
                    id.space()
                        + sequence_index.space()
                        + peptidoform_index.space()
                        + peptidoform_ion_index.space()
                }
                Self::ChargeCarrier(f) => f.space(),
                Self::CrossLinkBound(n) => n.space(),
                Self::CrossLinkBroken(n, f) => n.space() + f.space(),
                Self::GlycanFragment(f) => f.space(),
                Self::GlycanFragmentComposition(f) => f.space(),
            })
        .set_total::<Self>()
    }
}

/// The errors that can occur when adding molecular formulas.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MolecularFormulaError {
    /// If the element for an added element is not valid, see [`Element::is_valid`].
    ElementWithoutDefinedMass,
    /// If the isotope for an added element is not valid, see [`Element::is_valid`].
    IsotopeWithoutDefinedMass,
    /// If overflow occurred.
    Overflow,
}

impl MolecularFormulaError {
    /// A human friendly description of the error
    pub const fn reason(self) -> &'static str {
        match self {
            Self::ElementWithoutDefinedMass => "An element without a defined mass was used",
            Self::IsotopeWithoutDefinedMass => "An isotope without a defined mass was used",
            Self::Overflow => {
                "The total amount for this element overflowed the underlying storage type"
            }
        }
    }
}

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

impl MolecularFormula {
    /// Create a new molecular formula, if the chosen isotopes are not valid it returns None
    pub fn new(
        elements: &[(Element, Option<NonZeroU16>, i32)],
        labels: &[AmbiguousLabel],
    ) -> Option<Self> {
        if elements.iter().any(|e| !e.0.is_valid(e.1)) {
            None
        } else {
            let result = Self {
                elements: elements.into(),
                additional_mass: 0.0.into(),
                labels: labels.into(),
            };
            Some(result.simplify())
        }
    }

    // The elements will be sorted on element/isotope and deduplicated
    #[must_use]
    pub(super) fn simplify(mut self) -> Self {
        self.elements.retain(|el| el.2 != 0);
        self.elements.sort_by(|a, b| {
            if a.0 == b.0 {
                // If the elements are the same sort on the isotope number
                a.1.cmp(&b.1)
            } else {
                a.0.cmp(&b.0)
            }
        });
        // Deduplicate
        let mut max = self.elements.len().saturating_sub(1);
        let mut index = 0;
        while index < max {
            let this = self.elements[index];
            let next = self.elements[index + 1];
            if this.0 == next.0 && this.1 == next.1 {
                self.elements[index].2 += next.2;
                self.elements.remove(index + 1);
                max = max.saturating_sub(1);
            } else {
                index += 1;
            }
        }
        self.elements
            .retain(|el: &(Element, Option<std::num::NonZero<u16>>, i32)| el.2 != 0);
        self
    }

    /// Get an empty molecular formula with only a mass of unspecified origin
    #[must_use]
    pub fn with_additional_mass(additional_mass: f64) -> Self {
        Self {
            elements: ThinVec::new(),
            additional_mass: OrderedFloat(additional_mass),
            labels: ThinVec::new(),
        }
    }

    /// Add the given element to this formula (while keeping it ordered and simplified).
    /// # Errors
    /// If the added element does not have a defined mass, or if the added element
    /// overflows the total for that element.
    pub fn add(
        &mut self,
        element: (Element, Option<NonZeroU16>, i32),
    ) -> Result<(), MolecularFormulaError> {
        if element.0.is_valid(element.1) {
            let mut index = 0;
            let mut done = false;
            let (el, i, n) = element;
            while !done {
                let base = self.elements.get(index).copied();
                if let Some((re, ri, _)) = base {
                    if el > re || (el == re && i > ri) {
                        index += 1;
                    } else if el == re && i == ri {
                        if let Some(n) = self.elements[index].2.checked_add(n) {
                            self.elements[index].2 = n;
                        } else {
                            return Err(MolecularFormulaError::Overflow);
                        }
                        done = true;
                    } else {
                        self.elements.insert(index, (el, i, n));
                        done = true;
                    }
                } else {
                    self.elements.push((el, i, n));
                    done = true;
                }
            }
            Ok(())
        } else {
            Err(if element.1.is_some() {
                MolecularFormulaError::IsotopeWithoutDefinedMass
            } else {
                MolecularFormulaError::ElementWithoutDefinedMass
            })
        }
    }

    /// Add the given monoisotopic weight to this formula
    pub fn add_mass(&mut self, mass: OrderedFloat<f64>) {
        self.additional_mass += mass;
    }

    /// Get the elements making this formula
    pub fn elements(&self) -> &[(Element, Option<NonZeroU16>, i32)] {
        &self.elements
    }

    /// Get the elements making this formula
    pub fn elements_mut(&mut self) -> &mut [(Element, Option<NonZeroU16>, i32)] {
        &mut self.elements
    }

    /// Get the additional mass of this formula
    pub const fn additional_mass(&self) -> OrderedFloat<f64> {
        self.additional_mass
    }

    /// Set the charge. Only changes the number of electrons.
    pub fn set_charge(&mut self, charge: crate::system::isize::Charge) {
        if let Some(el) = self.elements.iter_mut().find(|e| e.0 == Element::Electron) {
            el.2 = -charge.value as i32;
        } else {
            self.elements.push((Element::Electron, None, -charge.value as i32));
        }
    }

    /// Check if the formula is empty (no elements and no additional mass)
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty() && self.additional_mass == 0.0
    }

    /// The generic backbone to do the Hill notation sorting
    pub(in super::super) fn hill_notation_generic(
        &self,
        f: impl Fn(&(Element, Option<NonZeroU16>, i32), &mut String),
        separator: &str,
        show_mass: bool,
        show_charge: bool,
    ) -> String {
        let mut buffer = String::new();
        if let Some(carbon) = self.elements.iter().find(|e| e.0 == Element::C && e.1.is_none()) {
            if carbon.2 != 0 {
                f(carbon, &mut buffer);
            }
            if let Some(hydrogen) =
                self.elements.iter().find(|e| e.0 == Element::H && e.1.is_none())
                && hydrogen.2 != 0
            {
                if !buffer.is_empty() {
                    buffer.push_str(separator);
                }
                f(hydrogen, &mut buffer);
            }
            for element in self.elements.iter().filter(|e| {
                !((e.0 == Element::H || e.0 == Element::C || e.0 == Element::Electron)
                    && e.1.is_none())
                    && e.2 != 0
            }) {
                if !buffer.is_empty() {
                    buffer.push_str(separator);
                }
                f(element, &mut buffer);
            }
        } else {
            for element in &self.elements {
                if element.2 != 0 && element.0 != Element::Electron {
                    if !buffer.is_empty() {
                        buffer.push_str(separator);
                    }
                    f(element, &mut buffer);
                }
            }
        }
        if show_mass && self.additional_mass != 0.0 {
            write!(&mut buffer, "{:+}", self.additional_mass).unwrap();
        }
        if show_charge && self.charge().value != 0 {
            write!(&mut buffer, ":z{:+}", self.charge().value).unwrap();
        }
        buffer
    }
}

impl Neg for &MolecularFormula {
    type Output = MolecularFormula;

    fn neg(self) -> Self::Output {
        let mut res = self.clone();
        for element in &mut res.elements {
            element.2 = -element.2;
        }
        res
    }
}

impl Neg for MolecularFormula {
    type Output = Self;

    fn neg(mut self) -> Self::Output {
        for element in &mut self.elements {
            element.2 = -element.2;
        }
        self
    }
}

impl Add<&MolecularFormula> for &MolecularFormula {
    type Output = MolecularFormula;

    fn add(self, rhs: &MolecularFormula) -> Self::Output {
        self.clone().checked_add(rhs).expect("Overflow in adding MolecularFormula")
    }
}

impl Sub<&MolecularFormula> for &MolecularFormula {
    type Output = MolecularFormula;

    fn sub(self, rhs: &MolecularFormula) -> Self::Output {
        let mut result = (*self).clone();
        result.labels.extend_from_slice(&rhs.labels);
        let mut index_result = 0;
        let mut index_rhs = 0;
        result.additional_mass -= rhs.additional_mass;
        while index_rhs < rhs.elements.len() {
            let (el, i, n) = rhs.elements[index_rhs];
            if index_result < result.elements.len() {
                let (re, ri, _) = result.elements[index_result];
                if el > re || (el == re && i > ri) {
                    index_result += 1;
                } else if el == re && i == ri {
                    result.elements[index_result].2 -= n;
                    index_rhs += 1;
                } else {
                    result.elements.insert(index_result, (el, i, -n));
                    index_rhs += 1;
                }
            } else {
                result.elements.push((el, i, -n));
                index_rhs += 1;
            }
        }
        result.elements.retain(|el| el.2 != 0);
        result
    }
}

impl Mul<&isize> for &MolecularFormula {
    type Output = MolecularFormula;

    fn mul(self, rhs: &isize) -> Self::Output {
        self.checked_mul_isize(*rhs)
            .expect("Overflow in multiplying MolecularFormula")
    }
}

impl Mul<&i32> for &MolecularFormula {
    type Output = MolecularFormula;

    fn mul(self, rhs: &i32) -> Self::Output {
        self.checked_mul_i32(*rhs)
            .expect("Overflow in multiplying MolecularFormula")
    }
}

impl Mul<&u16> for &MolecularFormula {
    type Output = MolecularFormula;

    fn mul(self, rhs: &u16) -> Self::Output {
        self.checked_mul_u16(*rhs)
            .expect("Overflow in multiplying MolecularFormula")
    }
}

impl MolecularFormula {
    /// Do checked multiplication to handle overflows gracefully
    pub fn checked_mul_isize(&self, rhs: isize) -> Option<Self> {
        self.checked_mul_i32(i32::try_from(rhs).ok()?)
    }

    /// Do checked multiplication to handle overflows gracefully
    pub fn checked_mul_i32(&self, rhs: i32) -> Option<Self> {
        Some(Self {
            additional_mass: self.additional_mass * f64::from(rhs),
            elements: self
                .elements
                .iter()
                .copied()
                .map(|part| Some((part.0, part.1, part.2.checked_mul(rhs)?)))
                .collect::<Option<_>>()?,
            labels: self.labels.clone(),
        })
    }

    /// Do checked multiplication to handle overflows gracefully
    pub fn checked_mul_u16(&self, rhs: u16) -> Option<Self> {
        Some(Self {
            additional_mass: self.additional_mass * f64::from(rhs),
            elements: self
                .elements
                .iter()
                .copied()
                .map(|part| Some((part.0, part.1, part.2.checked_mul(i32::from(rhs))?)))
                .collect::<Option<_>>()?,
            labels: self.labels.clone(),
        })
    }

    /// Do checked add to handle overflows gracefully
    pub fn checked_add(mut self, rhs: &Self) -> Option<Self> {
        self.ref_mut_checked_add(rhs).map(|()| self)
    }

    /// Do checked add to handle overflows gracefully
    pub fn ref_mut_checked_add(&mut self, rhs: &Self) -> Option<()> {
        self.labels.extend_from_slice(&rhs.labels);
        let mut index_result = 0;
        let mut index_rhs = 0;
        self.additional_mass += rhs.additional_mass;

        while index_rhs < rhs.elements.len() {
            let (el, i, n) = rhs.elements[index_rhs];
            if index_result < self.elements.len() {
                let (re, ri, _) = self.elements[index_result];
                if el > re || (el == re && i > ri) {
                    index_result += 1;
                } else if el == re && i == ri {
                    self.elements[index_result].2 = self.elements[index_result].2.checked_add(n)?;
                    index_rhs += 1;
                } else {
                    self.elements.insert(index_result, (el, i, n));
                    index_rhs += 1;
                }
            } else {
                self.elements.push((el, i, n));
                index_rhs += 1;
            }
        }
        self.elements.retain(|el| el.2 != 0);
        Some(())
    }

    /// Do checked sub to handle overflows gracefully
    pub fn checked_sub(mut self, rhs: &Self) -> Option<Self> {
        self.ref_mut_checked_sub(rhs).map(|()| self)
    }

    /// Do checked sub to handle overflows gracefully
    pub fn ref_mut_checked_sub(&mut self, rhs: &Self) -> Option<()> {
        self.labels.extend_from_slice(&rhs.labels);
        let mut index_result = 0;
        let mut index_rhs = 0;
        self.additional_mass -= rhs.additional_mass;
        while index_rhs < rhs.elements.len() {
            let (el, i, n) = rhs.elements[index_rhs];
            if index_result < self.elements.len() {
                let (re, ri, _) = self.elements[index_result];
                if el > re || (el == re && i > ri) {
                    index_result += 1;
                } else if el == re && i == ri {
                    self.elements[index_result].2 = self.elements[index_result].2.checked_sub(n)?;
                    index_rhs += 1;
                } else {
                    self.elements.insert(index_result, (el, i, -n));
                    index_rhs += 1;
                }
            } else {
                self.elements.push((el, i, -n));
                index_rhs += 1;
            }
        }
        self.elements.retain(|el| el.2 != 0);
        Some(())
    }
}

impl Mul<&i8> for &MolecularFormula {
    type Output = MolecularFormula;

    fn mul(self, rhs: &i8) -> Self::Output {
        MolecularFormula {
            additional_mass: self.additional_mass * f64::from(*rhs),
            elements: self
                .elements
                .iter()
                .copied()
                .map(|part| (part.0, part.1, part.2 * i32::from(*rhs)))
                .collect(),
            labels: self.labels.clone(),
        }
    }
}

impl_binop_ref_cases!(impl Add, add for MolecularFormula, MolecularFormula, MolecularFormula);
impl_binop_ref_cases!(impl Sub, sub for MolecularFormula, MolecularFormula, MolecularFormula);
impl_binop_ref_cases!(impl Mul, mul for MolecularFormula, isize, MolecularFormula);
impl_binop_ref_cases!(impl Mul, mul for MolecularFormula, i32, MolecularFormula);
impl_binop_ref_cases!(impl Mul, mul for MolecularFormula, u16, MolecularFormula);
impl_binop_ref_cases!(impl Mul, mul for MolecularFormula, i8, MolecularFormula);

impl AddAssign<&Self> for MolecularFormula {
    fn add_assign(&mut self, rhs: &Self) {
        self.ref_mut_checked_add(rhs).expect("Overflow in adding MolecularFormula");
    }
}

impl SubAssign<&Self> for MolecularFormula {
    fn sub_assign(&mut self, rhs: &Self) {
        self.ref_mut_checked_sub(rhs)
            .expect("Overflow in subtracting MolecularFormula");
    }
}

impl AddAssign<Self> for MolecularFormula {
    fn add_assign(&mut self, rhs: Self) {
        *self += &rhs;
    }
}

impl SubAssign<Self> for MolecularFormula {
    fn sub_assign(&mut self, rhs: Self) {
        *self -= &rhs;
    }
}

impl std::iter::Sum<Self> for MolecularFormula {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        let mut res = Self::default();
        iter.for_each(|v| res += v);
        res
    }
}

#[macro_export]
/// Easily define molecular formulas using the following syntax: `<element> <num>` or `[<isotope>
/// <element> <num>]`. The spaces are required by the Rust compiler.
/// ```
/// use mzcore::prelude::*;
/// molecular_formula!(C 12 [13 C 1] H 24);
/// molecular_formula!(C 12 [13 C 1] H 24 :z+2);
/// molecular_formula!(H 2 O);
/// ```
/// # Panics
/// It panics if the defined molecular formula is not valid. A formula is not valid if non existing
/// isotopes are used or if an element is used that does not have a defined molecular weight (does
/// not have natural abundance).
macro_rules! molecular_formula {
    ($($tail:tt)*) => {
        $crate::formula_internal!([$($tail)*] -> [])
    };
}

#[doc(hidden)]
#[macro_export]
/// Internal code for the [`molecular_formula`] macro.
macro_rules! formula_internal {
    ([$e:ident $n:literal $($tail:tt)*] -> [$($output:tt)*]) => {
        $crate::formula_internal!([$($tail)*] -> [$($output)*($crate::chemistry::Element::$e, None, $n),])
    };
    ([$e:ident $($tail:tt)*] -> [$($output:tt)*]) => {
        $crate::formula_internal!([$($tail)*] -> [$($output)*($crate::chemistry::Element::$e, None, 1),])
    };
    ([[$i:literal $e:ident $n:literal] $($tail:tt)*] -> [$($output:tt)*]) => {
        $crate::formula_internal!([$($tail)*] -> [$($output)*($crate::chemistry::Element::$e, Some(std::num::NonZeroU16::new($i).unwrap()), $n),])
    };
    ([$e:ident $n:expr] -> [$($output:tt)*]) =>{
        $crate::formula_internal!([] -> [$($output)*($crate::chemistry::Element::$e, None, $n),])
    };
    ([$e:ident] -> [$($output:tt)*]) =>{
        $crate::formula_internal!([] -> [$($output)*($crate::chemistry::Element::$e, None, 1),])
    };
    ([[$i:literal $e:ident] $n:expr] -> [$($output:tt)*]) =>{
        $crate::formula_internal!([] -> [$($output)*($crate::chemistry::Element::$e, Some(std::num::NonZeroU16::new($i).unwrap()), $n),])
    };
    ([:z+$charge:literal] -> [$($output:tt)*]) =>{
        $crate::formula_internal!([] -> [$($output)*($crate::chemistry::Element::Electron, None, -$charge),])
    };
    ([:z-$charge:literal] -> [$($output:tt)*]) =>{
        $crate::formula_internal!([] -> [$($output)*($crate::chemistry::Element::Electron, None, $charge),])
    };
    ([] -> [$($output:tt)*]) =>{
        $crate::chemistry::MolecularFormula::new(&[$($output)*], &[]).unwrap()
    };
    ([($($l:expr),*)] -> [$($output:tt)*]) =>{
        $crate::chemistry::MolecularFormula::new(&[$($output)*], &[$($l),*]).unwrap()
    };
}

/// A label for a satellite ion, none for most amino acids but a or b for Thr and Ile
#[derive(
    Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize, Default,
)]
pub enum SatelliteLabel {
    /// No label needed
    #[default]
    None,
    /// Heaviest of the two options
    A,
    /// Lightest of the two options
    B,
}

impl std::fmt::Display for SatelliteLabel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", match self {
            Self::None => "",
            Self::A => "a",
            Self::B => "b",
        })
    }
}