Skip to main content

ionic/ion/decoder/utilities/
spectrum_source.rs

1use crate::{
2    accessions as acc_const,
3    ion::attr_meta::parse_accession_tail,
4    mzml::structs::{CvParam, Spectrum},
5};
6
7#[inline]
8fn acc(s: Option<&str>) -> u32 {
9    parse_accession_tail(s).raw()
10}
11
12#[non_exhaustive]
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum TimeUnit {
15    Second,
16    Minute,
17    Millisecond,
18    Other,
19}
20
21impl TimeUnit {
22    pub(crate) fn code(self) -> u8 {
23        match self {
24            TimeUnit::Other => 0,
25            TimeUnit::Second => 1,
26            TimeUnit::Minute => 2,
27            TimeUnit::Millisecond => 3,
28        }
29    }
30
31    pub(crate) fn from_code(code: u8) -> Self {
32        match code {
33            1 => TimeUnit::Second,
34            2 => TimeUnit::Minute,
35            3 => TimeUnit::Millisecond,
36            _ => TimeUnit::Other,
37        }
38    }
39}
40
41#[non_exhaustive]
42#[derive(Debug, Clone, Copy)]
43pub struct ScanSummary {
44    pub rt: f64,
45    pub rt_unit: TimeUnit,
46    pub ms_level: u8,
47    pub polarity: u8,
48    pub selected_ion_mz: f64,
49    pub base_peak_mz: f64,
50    pub base_peak_int: f64,
51    pub total_ion_current: f64,
52    pub position_x: u32,
53    pub position_y: u32,
54    pub position_z: u32,
55}
56
57pub(crate) fn summary_from_spectrum(spectrum: &Spectrum) -> ScanSummary {
58    let mut rt = f64::NAN;
59    let mut rt_unit = TimeUnit::Other;
60    let mut ms_level = spectrum
61        .ms_level
62        .and_then(|level| u8::try_from(level).ok())
63        .unwrap_or(0);
64    let mut polarity = 0u8;
65    let mut base_peak_mz = f64::NAN;
66    let mut base_peak_int = f64::NAN;
67    let mut total_ion_current = f64::NAN;
68
69    for param in &spectrum.cv_params {
70        match acc(param.accession.as_deref()) {
71            acc_const::MS_LEVEL => {
72                if let Some(value) = param.value.as_deref().and_then(|v| v.parse().ok()) {
73                    ms_level = value;
74                }
75            }
76            acc_const::BASE_PEAK_MZ => base_peak_mz = parse_f64(param.value.as_deref()),
77            acc_const::BASE_PEAK_INT => base_peak_int = parse_f64(param.value.as_deref()),
78            acc_const::TOTAL_ION_CURRENT => total_ion_current = parse_f64(param.value.as_deref()),
79            acc_const::POSITIVE_SCAN => polarity = 1,
80            acc_const::NEGATIVE_SCAN => polarity = 2,
81            _ => {}
82        }
83    }
84
85    let scan_list = spectrum.scan_list.as_ref().or_else(|| {
86        spectrum
87            .spectrum_description
88            .as_ref()
89            .and_then(|d| d.scan_list.as_ref())
90    });
91
92    'find_rt: {
93        let Some(scan_list) = scan_list else {
94            break 'find_rt;
95        };
96        for scan in &scan_list.scans {
97            if let Some((value, unit)) = rt_from_params(&scan.cv_params) {
98                rt = value;
99                rt_unit = unit;
100                break 'find_rt;
101            }
102        }
103        if let Some((value, unit)) = rt_from_params(&scan_list.cv_params) {
104            rt = value;
105            rt_unit = unit;
106        }
107    }
108
109    let mut position_x = 0u32;
110    let mut position_y = 0u32;
111    let mut position_z = 0u32;
112    if let Some(scan_list) = scan_list {
113        for scan in &scan_list.scans {
114            for param in &scan.cv_params {
115                match acc(param.accession.as_deref()) {
116                    acc_const::POSITION_X => position_x = parse_u32(param.value.as_deref()),
117                    acc_const::POSITION_Y => position_y = parse_u32(param.value.as_deref()),
118                    acc_const::POSITION_Z => position_z = parse_u32(param.value.as_deref()),
119                    _ => {}
120                }
121            }
122        }
123    }
124
125    let selected_ion_mz = spectrum
126        .precursor_list
127        .as_ref()
128        .and_then(|precursor_list| precursor_list.precursors.first())
129        .and_then(|precursor| precursor.selected_ion_list.as_ref())
130        .and_then(|selected_ion_list| selected_ion_list.selected_ions.first())
131        .map(|selected_ion| {
132            selected_ion
133                .cv_params
134                .iter()
135                .find(|param| acc(param.accession.as_deref()) == acc_const::SELECTED_ION_MZ)
136                .and_then(|param| param.value.as_deref()?.parse().ok())
137                .unwrap_or(f64::NAN)
138        })
139        .unwrap_or(f64::NAN);
140
141    ScanSummary {
142        rt,
143        rt_unit,
144        ms_level,
145        polarity,
146        base_peak_mz,
147        base_peak_int,
148        total_ion_current,
149        selected_ion_mz,
150        position_x,
151        position_y,
152        position_z,
153    }
154}
155
156#[inline]
157fn rt_from_params(params: &[CvParam]) -> Option<(f64, TimeUnit)> {
158    for param in params {
159        if acc(param.accession.as_deref()) == acc_const::SCAN_START_TIME {
160            let value: f64 = param.value.as_deref()?.parse().ok()?;
161            if !value.is_finite() {
162                return None;
163            }
164            let unit = time_unit_from(param.unit_accession.as_deref(), param.unit_name.as_deref());
165            return Some((value, unit));
166        }
167    }
168    None
169}
170
171fn time_unit_from(unit_accession: Option<&str>, unit_name: Option<&str>) -> TimeUnit {
172    match acc(unit_accession) {
173        acc_const::UNIT_MINUTE => TimeUnit::Minute,
174        acc_const::UNIT_SECOND => TimeUnit::Second,
175        acc_const::UNIT_MS => TimeUnit::Millisecond,
176        _ => match unit_name {
177            Some("minute" | "minutes") => TimeUnit::Minute,
178            Some("second" | "seconds") => TimeUnit::Second,
179            Some("millisecond" | "milliseconds") => TimeUnit::Millisecond,
180            _ => TimeUnit::Other,
181        },
182    }
183}
184
185#[inline]
186fn parse_f64(s: Option<&str>) -> f64 {
187    s.and_then(|v| v.parse().ok()).unwrap_or(f64::NAN)
188}
189
190#[inline]
191fn parse_u32(s: Option<&str>) -> u32 {
192    s.and_then(|v| v.parse().ok()).unwrap_or(0)
193}
194
195pub(crate) fn f16_bits_to_f64(bits: u16) -> f64 {
196    let sign = ((bits & 0x8000) as u32) << 16;
197    let exp = (bits & 0x7C00) >> 10;
198    let mant = (bits & 0x03FF) as u32;
199    let bits32 = match exp {
200        0 if mant == 0 => sign,
201        0 => {
202            let mut mantissa = mant;
203            let mut exponent_shift = 0u32;
204            while mantissa & 0x400 == 0 {
205                mantissa <<= 1;
206                exponent_shift += 1;
207            }
208            sign | ((127 - 14 - exponent_shift) << 23) | ((mantissa & 0x03FF) << 13)
209        }
210        31 => sign | 0x7F80_0000 | (mant << 13),
211        exponent => sign | ((exponent as u32 + 112) << 23) | (mant << 13),
212    };
213    f32::from_bits(bits32) as f64
214}