use crate::mass::PROTON;
use crate::residue::{peptide_composition, residue_composition, Composition};
const AB_C: [f64; 2] = [0.9893, 0.0107];
const AB_H: [f64; 2] = [0.999_885, 0.000_115];
const AB_N: [f64; 2] = [0.996_36, 0.003_64];
const AB_O: [f64; 3] = [0.997_57, 0.000_38, 0.002_05];
const AB_S: [f64; 5] = [0.9499, 0.0075, 0.0425, 0.0, 0.0001];
const AB_P: [f64; 1] = [1.0];
pub const NEUTRON: f64 = 1.003_355;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnvelopeError {
UnknownResidue(char),
SeleniumUnsupported,
}
impl std::fmt::Display for EnvelopeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EnvelopeError::UnknownResidue(c) => write!(f, "unknown residue {c:?}"),
EnvelopeError::SeleniumUnsupported => {
write!(f, "selenium isotope envelope not supported (see ms_chem::isotope docs)")
}
}
}
}
impl std::error::Error for EnvelopeError {}
fn convolve(a: &[f64], b: &[f64], depth: usize) -> Vec<f64> {
let mut out = vec![0.0; depth];
for (i, &x) in a.iter().enumerate() {
if x == 0.0 {
continue;
}
for (j, &y) in b.iter().enumerate() {
if i + j >= depth {
break;
}
out[i + j] += x * y;
}
}
out
}
fn self_convolve(dist: &[f64], n: u32, depth: usize) -> Vec<f64> {
let mut result = vec![0.0; depth];
result[0] = 1.0;
if n == 0 {
return result;
}
let mut base = {
let mut b = vec![0.0; depth];
for (i, &v) in dist.iter().take(depth).enumerate() {
b[i] = v;
}
b
};
let mut e = n;
while e > 0 {
if e & 1 == 1 {
result = convolve(&result, &base, depth);
}
e >>= 1;
if e > 0 {
base = convolve(&base, &base, depth);
}
}
result
}
pub fn envelope_of(c: Composition, depth: usize) -> Result<Vec<f64>, EnvelopeError> {
if c.se > 0 {
return Err(EnvelopeError::SeleniumUnsupported);
}
let depth = depth.max(1);
let mut dist = self_convolve(&AB_C, c.c, depth);
for (ab, n) in [
(&AB_H[..], c.h),
(&AB_N[..], c.n),
(&AB_O[..], c.o),
(&AB_S[..], c.s),
(&AB_P[..], c.p),
] {
if n > 0 {
dist = convolve(&dist, &self_convolve(ab, n, depth), depth);
}
}
let total: f64 = dist.iter().sum();
Ok(dist.iter().map(|v| v / total).collect())
}
pub fn envelope(sequence: &str, depth: usize) -> Result<Vec<f64>, EnvelopeError> {
let c = peptide_composition(sequence).ok_or_else(|| {
let bad = sequence
.bytes()
.find(|&b| residue_composition(b).is_none())
.unwrap_or(b'?');
EnvelopeError::UnknownResidue(bad as char)
})?;
envelope_of(c, depth)
}
pub fn peak_mz(mono_mass: f64, charge: u32, k: usize) -> f64 {
assert!(charge >= 1, "charge must be >= 1");
(mono_mass + k as f64 * NEUTRON + charge as f64 * PROTON) / charge as f64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn envelope_sums_to_one_and_starts_positive() {
let e = envelope("PEPTIDER", 6).unwrap();
let sum: f64 = e.iter().sum();
assert!((sum - 1.0).abs() < 1e-9);
assert!(e[0] > 0.5); }
#[test]
fn selenium_is_deferred_cleanly() {
assert_eq!(envelope("UGG", 6), Err(EnvelopeError::SeleniumUnsupported));
assert!(matches!(envelope("PZP", 6), Err(EnvelopeError::UnknownResidue('Z'))));
}
}