use crate::mass::{UnknownResidue, PROTON, WATER};
use crate::residue::residue_monoisotopic_mass;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum IonType {
B,
Y,
}
impl IonType {
pub fn as_str(&self) -> &'static str {
match self {
IonType::B => "b",
IonType::Y => "y",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Fragment {
pub ion_type: IonType,
pub ordinal: u16,
pub charge: u8,
pub mz: f64,
}
pub fn fragment_ions(sequence: &str, max_charge: u8) -> Result<Vec<Fragment>, UnknownResidue> {
assert!(max_charge >= 1, "max_charge must be >= 1");
let bytes = sequence.as_bytes();
let n = bytes.len();
let res: Vec<f64> = bytes
.iter()
.map(|&b| residue_monoisotopic_mass(b).ok_or(UnknownResidue(b as char)))
.collect::<Result<_, _>>()?;
let mut out = Vec::new();
if n < 2 {
return Ok(out);
}
for z in 1..=max_charge {
let zf = z as f64;
let mut acc = 0.0;
for i in 0..n - 1 {
acc += res[i];
out.push(Fragment {
ion_type: IonType::B,
ordinal: (i + 1) as u16,
charge: z,
mz: (acc + zf * PROTON) / zf,
});
}
let mut acc = 0.0;
for j in 0..n - 1 {
acc += res[n - 1 - j];
out.push(Fragment {
ion_type: IonType::Y,
ordinal: (j + 1) as u16,
charge: z,
mz: (acc + WATER + zf * PROTON) / zf,
});
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mass::monoisotopic;
#[test]
fn b1_and_y1_of_a_known_peptide() {
let f = fragment_ions("PEPTIDER", 1).unwrap();
let b1 = f.iter().find(|x| x.ion_type == IonType::B && x.ordinal == 1).unwrap();
let y1 = f.iter().find(|x| x.ion_type == IonType::Y && x.ordinal == 1).unwrap();
assert!((b1.mz - 98.06004).abs() < 1e-4, "b1={}", b1.mz);
assert!((y1.mz - 175.11895).abs() < 1e-4, "y1={}", y1.mz);
}
#[test]
fn complementarity_holds_by_construction() {
let seq = "PEPTIDER";
let n = seq.len();
let m = monoisotopic(seq).unwrap();
let f = fragment_ions(seq, 1).unwrap();
for i in 1..n {
let bi = f.iter().find(|x| x.ion_type == IonType::B && x.ordinal == i as u16);
let yni = f.iter().find(|x| x.ion_type == IonType::Y && x.ordinal == (n - i) as u16);
if let (Some(b), Some(y)) = (bi, yni) {
assert!((b.mz + y.mz - (m + 2.0 * PROTON)).abs() < 1e-9);
}
}
}
#[test]
fn short_peptides_and_errors() {
assert!(fragment_ions("A", 1).unwrap().is_empty());
assert_eq!(fragment_ions("AZ", 1), Err(UnknownResidue('Z')));
}
}