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
use chemistry_consts::ElementProperties;
use core::{
fmt::{Display, Formatter},
str::FromStr,
};
use nohash_hasher::IntMap;
// TODO: make this a parameter
const PRECISION: f64 = 1000.0;
#[derive(Clone, Debug, PartialEq)]
pub struct MolecularFormula {
elements: IntMap<u8, usize>,
}
impl MolecularFormula {
pub fn new() -> Self {
MolecularFormula {
elements: IntMap::default(),
}
}
pub fn elements(&self) -> &IntMap<u8, usize> {
&self.elements
}
/// Merges two molecular formulas.
///
/// # Examples
/// ```
/// use molecules::molecular_formula::MolecularFormula;
/// let water = "H2O".parse::<MolecularFormula>().unwrap();
/// let methane = "CH4".parse::<MolecularFormula>().unwrap();
/// let mut water_methane = water.clone();
/// water_methane.merge(&methane);
/// assert_eq!(water_methane, "CH4H2O".parse::<MolecularFormula>().unwrap());
/// assert_eq!(water, "H2O".parse::<MolecularFormula>().unwrap());
/// assert_eq!(methane, "CH4".parse::<MolecularFormula>().unwrap());
/// assert_eq!(water_methane, "CH4H2O".parse::<MolecularFormula>().unwrap());
///
/// ```
pub fn merge(&mut self, other: &MolecularFormula) {
for (atom, count) in &other.elements {
*self.elements.entry(*atom).or_insert(0) += count;
}
}
/// Combines two molecular formulas.
/// # Examples
/// ```
/// use molecules::molecular_formula::MolecularFormula;
/// let water = "H2O".parse::<MolecularFormula>().unwrap();
/// let methane = "CH4".parse::<MolecularFormula>().unwrap();
/// let water_methane = water.combine(&methane);
/// assert_eq!(water_methane, "CH4H2O".parse::<MolecularFormula>().unwrap());
/// ```
pub fn combine(&self, other: &MolecularFormula) -> Self {
let mut combined = MolecularFormula::new();
for (atom, count) in &self.elements {
*combined.elements.entry(*atom).or_insert(0) += count;
}
for (atom, count) in &other.elements {
*combined.elements.entry(*atom).or_insert(0) += count;
}
combined
}
/// Calculates the monoisotopic mass of the molecular formula.
///
/// # Examples
/// ```
/// use molecules::molecular_formula::MolecularFormula;
/// let water = "H2O".parse::<MolecularFormula>().unwrap();
/// let methane = "CH4".parse::<MolecularFormula>().unwrap();
/// println!("{:?}", water);
/// assert_eq!(water.monoisotopic_mass().round(), 18.0);
/// assert_eq!(methane.monoisotopic_mass().round(), 16.0);
///
/// ```
pub fn monoisotopic_mass(&self) -> f64 {
self.elements.iter().fold(0.0, |acc, (atom, count)| {
acc + atom.monoisotopic_mass().unwrap() * *count as f64
})
}
/// Calculates the molecular mass of the molecular formula.
/// Since some elements do not have a standard atomic weight, this function returns an Option.
/// # Examples
/// ```
/// use molecules::molecular_formula::MolecularFormula;
/// let water = "H2O".parse::<MolecularFormula>().unwrap();
/// let methane = "CH4".parse::<MolecularFormula>().unwrap();
/// assert_eq!(water.molecular_mass().unwrap().round(), 18.0);
/// assert_eq!(methane.molecular_mass().unwrap().round(), 16.0);
pub fn molecular_mass(&self) -> Option<f64> {
self
.elements
.iter()
.try_fold(0.0, |acc, (atom, count)| {
let standard_atomic_weight = atom.standard_atomic_weight()?;
Some(acc + standard_atomic_weight * *count as f64)
})
}
//This is commented out due to a saftey issue with the fft crate
// Calculates the isotopic pattern of the molecular formula.
//
// # Arguments
// * `max_mass_difference` - The maximum mass difference between the monoisotopic peak and the
// last peak in the isotopic pattern to be calculated.
// # Examples
// ```
// use molecules::molecular_formula::MolecularFormula;
// let water = "H2O".parse::<MolecularFormula>().unwrap();
// let isotopic_pattern_h2o = water.isotopic_pattern(3,1);
//
// println!("{:?}", isotopic_pattern_h2o);
// println!("{:?}", water);
// assert!(isotopic_pattern_h2o.len() == 3);
//
// let methane = "CH4".parse::<MolecularFormula>().unwrap();
// let isotopic_pattern_methane = methane.isotopic_pattern(3,1);
// println!("{:?}", isotopic_pattern_methane);
// assert!(isotopic_pattern_methane.len() == 3);
// println!("{:?}", water);
// ```
// pub fn isotopic_pattern(
// &self,
// max_mass_difference: usize,
// resolution: usize,
// ) -> Vec<(f64, f64)> {
// let min_mass: usize = self.monoisotopic_mass().round() as usize;
// let max_mass = min_mass + max_mass_difference;
// let mut total_distribution = Array1::<f64>::zeros(max_mass * resolution + 1);
// total_distribution[0] = 1.0;
// let mut planner = FftPlanner::new();
// let fft = planner.plan_fft_forward(total_distribution.len());
// let ifft = planner.plan_fft_inverse(total_distribution.len());
// let mut atom_distribution = Array1::<f64>::zeros(max_mass * resolution + 1);
// for (atomic_number, count) in self.elements.iter() {
// if let Some(atom) = ISOTOPES.get(*atomic_number as usize) {
// for _ in 0..*count {
// atom_distribution.fill(0.0);
// for isotope in atom.iter().flatten() {
// atom_distribution[(isotope.mass * resolution as f64).round() as usize] =
// isotope.abundance;
// }
// // Preparing input for FFT
// let mut distribution_fft = total_distribution
// .iter()
// .map(|&v| Complex::new(v, 0.0))
// .collect::<Vec<Complex<f64>>>();
// let mut atom_distribution_fft = atom_distribution
// .iter()
// .map(|&v| Complex::new(v, 0.0))
// .collect::<Vec<Complex<f64>>>();
// // Apply FFT
// fft.process(&mut distribution_fft);
// fft.process(&mut atom_distribution_fft);
// // Convolution in the frequency domain
// let mut convoluted = distribution_fft
// .iter()
// .zip(atom_distribution_fft.iter())
// .map(|(a, b)| a * b)
// .collect::<Vec<Complex<f64>>>();
// // Apply inverse FFT
// ifft.process(&mut convoluted);
// total_distribution =
// Array1::from(convoluted.iter().map(|v| v.re).collect::<Vec<f64>>());
// }
// }
// }
// // Normalization
// let sum = total_distribution.sum();
// total_distribution
// .slice(s![min_mass * resolution..max_mass * resolution])
// .mapv(|v| v / sum)
// .into_iter()
// .zip(
// (min_mass * resolution..max_mass * resolution)
// .map(|v| v as f64 / resolution as f64),
// )
// .collect::<Vec<(f64, f64)>>()
// }
// pub fn isotopic_pattern(&self, max_mass_difference: usize, resolution: usize) -> Vec<f64> {
// let min_mass: usize = self.monoisotopic_mass().round() as usize;
// let max_mass = min_mass + max_mass_difference;
// let mut total_distribution = Array1::<f64>::zeros(max_mass * resolution + 1);
// total_distribution[0] = 1.0;
// for (atomic_number, count) in self.elements.iter() {
// if let Some(atom) = ISOTOPES.get(*atomic_number as usize) {
// for _ in 0..*count {
// let mut atom_distribution = Array1::<f64>::zeros(max_mass * resolution + 1);
// for isotope in atom {
// let Some(isotope) = isotope else {
// break
// };
// atom_distribution[(isotope.mass * resolution as f64).round() as usize] =
// isotope.abundance;
// }
// let mut planner = FftPlanner::new();
// let fft = planner.plan_fft_forward(total_distribution.len());
// let ifft = planner.plan_fft_inverse(total_distribution.len());
// let mut input1: Vec<Complex<f64>> = total_distribution
// .iter()
// .map(|&v| Complex::new(v, 0.0))
// .collect();
// let mut input2: Vec<Complex<f64>> = atom_distribution
// .iter()
// .map(|&v| Complex::new(v, 0.0))
// .collect();
// fft.process(&mut input1);
// fft.process(&mut input2);
// let mut output: Vec<Complex<f64>> = input1
// .iter()
// .zip(input2.iter())
// .map(|(a, b)| a * b)
// .collect();
// ifft.process(&mut output);
// total_distribution =
// Array1::from(output.iter().map(|v| v.re).collect::<Vec<f64>>());
// }
// }
// }
// total_distribution
// .slice(s![min_mass * resolution..max_mass * resolution])
// .mapv(|v| v / total_distribution.sum())
// .to_vec()
// }
}
impl Default for MolecularFormula {
fn default() -> Self {
Self::new()
}
}
impl Display for MolecularFormula {
// TODO make this more efficient
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut elements = self
.elements
.iter()
.map(|(&atom, &count)| (atom.atomic_symbol().unwrap().into(), count))
.collect::<Vec<(String,usize)>>();
elements.sort_by(|(atom1, _),(atom2, _)| atom1.cmp(atom2));
for (atom, count) in elements {
write!(f, "{}{}", atom, count)?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct ParseFormulaError;
impl std::fmt::Display for ParseFormulaError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"could not parse the provided string as a molecular formula"
)
}
}
impl std::error::Error for ParseFormulaError {}
impl FromStr for MolecularFormula {
type Err = ParseFormulaError;
/// Parses a molecular formula from a string.
///
/// # Panics
///
/// This function does not panic. But it will ignore everything that is neither a number nor a
/// letter
///
/// # Examples
/// ```
/// use molecules::molecular_formula::MolecularFormula;
/// let water = "H2O".parse::<MolecularFormula>().unwrap();
/// let methane = "CH4".parse::<MolecularFormula>().unwrap();
/// assert_eq!(water.monoisotopic_mass(), 18.01056468403);
/// assert_eq!(methane.monoisotopic_mass(), 16.03130012892);
///
/// ```
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty() {
return Ok(MolecularFormula::new());
}
let mut number_buffer = String::new();
let mut element_buffer = String::new();
let mut elements: IntMap<u8, usize> = IntMap::default();
s.chars().for_each(|c| {
if c.is_alphabetic() {
if !element_buffer.is_empty() && c.is_uppercase() {
let atomic_number = element_buffer.as_str().atomic_number().expect("Invalid element");
let count = if !number_buffer.is_empty() {
number_buffer.parse::<usize>().unwrap_or(1)
} else {
1
};
*elements.entry(atomic_number).or_insert(0) += count;
number_buffer.clear();
element_buffer.clear();
}
element_buffer.push(c);
} else if c.is_numeric() {
number_buffer.push(c);
}
});
if !element_buffer.is_empty() {
let atomic_number = element_buffer.as_str().atomic_number().expect("Invalid element");
let count = if !number_buffer.is_empty() {
number_buffer.parse::<usize>().unwrap_or(1)
} else {
1
};
*elements.entry(atomic_number).or_insert(0) += count;
}
Ok(MolecularFormula { elements })
}
}
#[derive(Debug, Clone, Default)]
pub struct IsotopicPattern {
pub buckets: IntMap<usize, (f64, f64)>,
}
impl IsotopicPattern {
pub fn new(abundances: Vec<f64>, masses: Vec<f64>) -> Self {
let mut buckets = IntMap::default();
for (&intensity, &mass) in abundances.iter().zip(masses.iter()) {
let mass_index = (PRECISION * mass).round() as usize;
match buckets.entry(mass_index) {
std::collections::hash_map::Entry::Occupied(mut entry) => {
let bucket: &mut (f64, f64) = entry.get_mut();
let mass_sum = mass * intensity + bucket.0 * bucket.1;
let intensity_sum = intensity + bucket.1;
bucket.0 = mass_sum / intensity_sum;
bucket.1 += intensity;
}
std::collections::hash_map::Entry::Vacant(entry) => {
entry.insert((mass, intensity));
}
}
}
IsotopicPattern { buckets }
}
pub fn to_vec(&self) -> Vec<(f64, f64)> {
let mut vec = self.buckets.values().cloned().collect::<Vec<_>>();
vec.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
vec
}
/// Merge two isotopic patterns into one.
///
/// # Examples
/// ```
/// use molecules::molecular_formula::IsotopicPattern;
/// let mut pattern1 = IsotopicPattern::new(vec![0.5, 0.5], vec![1.0, 2.0]);
/// let pattern2 = IsotopicPattern::new(vec![0.5, 0.5], vec![3.0, 4.0]);
/// let merged = pattern1.add(&pattern2);
/// ```
pub fn add(&mut self, other: &IsotopicPattern) {
for (mass_index, &(mass, abundance)) in other.buckets.iter() {
let mut bucket = *self.buckets.entry(*mass_index).or_insert((mass, 0.0));
bucket.1 += abundance;
bucket.0 = (bucket.0 * bucket.1 + mass * abundance) / bucket.1;
}
}
/// Add a single entry to the isotopic pattern, this will merge two buckets if they have the
/// same mass
///
/// # Examples
/// ```
/// use molecules::molecular_formula::IsotopicPattern; let mut pattern = IsotopicPattern::new(vec![0.5, 0.5], vec![1.0, 2.0]);
/// pattern.add_entry(1.0, 0.5);
/// assert_eq!(pattern.buckets.len(), 2);
/// ```
///
///
pub fn add_entry(&mut self, mass: f64, abundance: f64) {
let mass_index = (mass * PRECISION).round() as usize;
let bucket = self.buckets.entry(mass_index).or_insert((mass, 0.0));
let new_abundance = bucket.1 + abundance;
bucket.0 = (bucket.0 * bucket.1 + mass * abundance) / new_abundance;
bucket.1 = new_abundance;
}
pub fn normalize(&mut self) {
let total_abundance: f64 = self.buckets.values().map(|&(_, a)| a).sum();
for bucket in self.buckets.values_mut() {
bucket.1 /= total_abundance;
}
}
pub fn normalize_to_highest(&mut self) {
let max_abundance: f64 = self
.buckets
.values()
.map(|&(_, a)| a)
.max_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap();
for bucket in self.buckets.values_mut() {
bucket.1 /= max_abundance;
}
}
pub fn len(&self) -> usize {
self.buckets.len()
}
pub fn is_empty(&self) -> bool {
self.buckets.is_empty()
}
fn combine(&self, other: &Self, n_peaks: usize) -> Self {
let mut combined = IsotopicPattern::default();
let min_mass = (self.buckets.keys().min().unwrap() + other.buckets.keys().min().unwrap())
as f64
/ PRECISION;
let max_mass = min_mass + n_peaks as f64;
for (&_, &(mass_self, abundance_self)) in &self.buckets {
for (&_, &(mass_other, abundance_other)) in &other.buckets {
let combined_mass = mass_self + mass_other;
if combined_mass <= max_mass {
let combined_prob = abundance_self * abundance_other;
combined.add_entry(combined_mass, combined_prob);
}
}
}
combined
}
pub fn shift(&mut self, shift: f64) {
let mut new_buckets = IntMap::default();
for bucket in self.buckets.values_mut() {
let mass = bucket.0 + shift;
let mass_index = (PRECISION * mass).round() as usize;
new_buckets.entry(mass_index).or_insert((mass, 0.0)).1 += bucket.1;
}
self.buckets = new_buckets;
}
}
#[derive(Debug, Clone)]
pub struct Isotope {
pub mass: f64,
pub abundance: f64,
}
impl Isotope {
pub const fn new(mass: f64, abundance: f64) -> Isotope {
Isotope { mass, abundance }
}
}
impl From<[f64; 2]> for Isotope {
fn from(isotope: [f64; 2]) -> Self {
Isotope {
mass: isotope[0],
abundance: isotope[1],
}
}
}