Skip to main content

ms_chem/
modification.rs

1//! Modifications — a single coverage-consistent table pairing mass **and** composition.
2//!
3//! Per `CHEM_PARITY.md` finding: mscore split modifications across two disjoint tables (1028 masses,
4//! 17 compositions) — GG/121 had a composition but no mass, Trimethyl/37 the reverse. A modification
5//! is not a scalar: its composition reshapes the isotope envelope (phospho adds HPO₃, GG adds
6//! C₄H₆N₂O₂), so mass and composition must travel together. ms-chem adopts timsim-chem's pattern:
7//! each [`Modification`] carries both, and [`Modification::validate`] cross-checks them at load — the
8//! composition's monoisotopic mass must equal the declared `mass_delta`, so a typo in either is
9//! caught immediately instead of silently shifting a modified precursor's m/z.
10
11use crate::formula;
12
13/// One modification: UNIMOD id, the residues it targets, and the two independent routes to its mass
14/// (declared `mass_delta` and elemental `composition`) that must agree.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct Modification {
17    pub unimod_id: u32,
18    pub name: &'static str,
19    /// Residues it can sit on, e.g. `"STY"` for phospho. Empty means a terminal modification.
20    pub targets: &'static str,
21    pub mass_delta: f64,
22    /// Elemental composition of the delta, e.g. `"HO3P"` for phospho.
23    pub composition: &'static str,
24}
25
26impl Modification {
27    /// Cross-check the two routes to the modification's mass. The composition's monoisotopic mass
28    /// (from [`crate::formula`], built on the same element table as everything else) must equal the
29    /// declared `mass_delta` within 1e-3 Da.
30    pub fn validate(&self) -> Result<(), String> {
31        let from_comp = formula::monoisotopic_mass(self.composition)
32            .map_err(|e| format!("{} (id {}): composition {:?}: {e}", self.name, self.unimod_id, self.composition))?;
33        let d = (from_comp - self.mass_delta).abs();
34        if d > 1e-3 {
35            return Err(format!(
36                "{} (id {}): composition {} weighs {from_comp:.5} but mass_delta = {:.5} (Δ{d:.2e})",
37                self.name, self.unimod_id, self.composition, self.mass_delta
38            ));
39        }
40        Ok(())
41    }
42}
43
44/// The curated catalog of sim-relevant modifications, each with mass AND composition. Unlike either
45/// of mscore's tables alone, every entry here is coverage-consistent — GG (121) has both, so does
46/// Trimethyl (37). (The long tail of UNIMOD masses for search/annotation is a separate mass-only
47/// lookup, ported in a follow-up.)
48pub const BUILTIN: &[Modification] = &[
49    Modification { unimod_id: 1, name: "Acetyl", targets: "K", mass_delta: 42.01057, composition: "C2H2O" },
50    Modification { unimod_id: 4, name: "Carbamidomethyl", targets: "C", mass_delta: 57.02146, composition: "C2H3NO" },
51    Modification { unimod_id: 21, name: "Phospho", targets: "STY", mass_delta: 79.96633, composition: "HO3P" },
52    Modification { unimod_id: 35, name: "Oxidation", targets: "M", mass_delta: 15.99491, composition: "O" },
53    Modification { unimod_id: 37, name: "Trimethyl", targets: "K", mass_delta: 42.04695, composition: "C3H6" },
54    Modification { unimod_id: 121, name: "GG", targets: "K", mass_delta: 114.04293, composition: "C4H6N2O2" },
55];
56
57/// Look up a builtin modification by UNIMOD id.
58pub fn by_id(id: u32) -> Option<Modification> {
59    BUILTIN.iter().copied().find(|m| m.unimod_id == id)
60}
61
62
63/// Elemental compositions (signed — losses use negative counts) for a curated set of modifications,
64/// keyed by UNIMOD id. Ported from mscore's `modification_atomic_composition`. 10 also appear in
65/// [`crate::unimod::UNIMOD_MASS`] and cross-check against it; 5 (58/121/122/312/747) are
66/// composition-only — the R1 Gate 3 coverage gap, preserved faithfully rather than silently changed.
67pub const MODIFICATION_COMPOSITION: &[(u32, &'static [(&'static str, i32)])] = &[
68    (1, &[("C", 2), ("H", 2), ("O", 1)]), // Acetyl
69    (3, &[("N", 2), ("C", 10), ("H", 14), ("O", 2), ("S", 1)]), // Biotinylation
70    (4, &[("C", 2), ("H", 3), ("O", 1), ("N", 1)]),
71    (7, &[("H", -1), ("N", -1), ("O", 1)]), // Hydroxylation
72    (21, &[("H", 1), ("O", 3), ("P", 1)]), // Phosphorylation
73    (34, &[("H", 2), ("C", 1)]), // Methylation
74    (35, &[("O", 1)]), // Hydroxylation
75    (58, &[("C", 3), ("H", 4), ("O", 1)]), // Propionyl
76    (121, &[("C", 4), ("H", 6), ("O", 2), ("N", 2)]), // ubiquitinylation residue
77    (122, &[("C", 1), ("O", 1)]), // Formylation
78    (312, &[("C", 3), ("H", 5), ("O", 2), ("N", 1), ("S", 1)]), // Cysteinyl
79    (354, &[("H", -1), ("O", 2), ("N", 1)]), // Oxidation to nitro
80    (747, &[("C", 3), ("H", 2), ("O", 3)]), // Malonylation
81    (1289, &[("C", 4), ("H", 6), ("O", 1)]), // Butyryl
82    (1363, &[("C", 4), ("H", 4), ("O", 1)]), // Crotonylation
83];
84
85/// Signed elemental composition of a modification by UNIMOD id, or `None` if not tabulated.
86pub fn atomic_composition(id: u32) -> Option<&'static [(&'static str, i32)]> {
87    MODIFICATION_COMPOSITION.iter().find(|&&(i, _)| i == id).map(|&(_, c)| c)
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn every_builtin_cross_checks() {
96        // the coverage-consistency guarantee: mass and composition agree for every entry
97        for m in BUILTIN {
98            m.validate().unwrap_or_else(|e| panic!("{e}"));
99        }
100    }
101
102    #[test]
103    fn compositions_cross_check_mass_table() {
104        use crate::elements::monoisotopic_mass;
105        let mut overlap = 0;
106        for &(id, comp) in MODIFICATION_COMPOSITION {
107            let mass: f64 = comp
108                .iter()
109                .map(|&(e, c)| monoisotopic_mass(e).expect("element") * c as f64)
110                .sum();
111            if let Some(tab) = crate::unimod::mass_delta(id) {
112                assert!((mass - tab).abs() < 1e-3, "UNIMOD:{id} composition {mass} vs table {tab}");
113                overlap += 1;
114            }
115        }
116        // 10 overlap the mass table (agree); the other 5 are the documented composition-only gap
117        assert_eq!(overlap, 10, "expected 10 of 15 compositions to overlap the mass table");
118        assert!(atomic_composition(21).is_some() && atomic_composition(9_999_999).is_none());
119    }
120
121    #[test]
122    fn ids_are_unique_and_lookup_works() {
123        let mut ids: Vec<u32> = BUILTIN.iter().map(|m| m.unimod_id).collect();
124        let n = ids.len();
125        ids.sort_unstable();
126        ids.dedup();
127        assert_eq!(ids.len(), n, "duplicate unimod ids");
128        assert_eq!(by_id(21).unwrap().name, "Phospho");
129        assert_eq!(by_id(999999), None);
130    }
131}