chemical_elements 0.7.0

A library for representing chemical compositions and generating isotopic patterns
Documentation
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
#![allow(unused)]
use std::fmt::Display;
use std::ops::{Add, AddAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign};
use std::slice::{Iter, IterMut};
use std::str::FromStr;

#[cfg(feature = "serde")]
use serde_with::{DeserializeFromStr, SerializeDisplay};

use crate::element_specification::{ElementSpecification, ElementSpecificationLike};
use crate::formula::FormulaParser;
use crate::{FormulaParserError, PeriodicTable, PERIODIC_TABLE};

#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(DeserializeFromStr, SerializeDisplay))]
/**
Represents a collection of element-count pairs as found in a flat
chemical formula. Built atop [`std::collections::HashMap`], and
support addition and subtraction with other instances of the same type
and multiplication by integers.
*/
pub struct ChemicalCompositionVec<'a> {
    pub composition: Vec<(ElementSpecification<'a>, i32)>,
    mass_cache: Option<f64>,
}

/**
# Basic Operations
*/
impl<'lifespan> ChemicalCompositionVec<'lifespan> {
    /// Create a new, empty [`ChemicalCompositionVec`]
    pub fn new() -> ChemicalCompositionVec<'lifespan> {
        ChemicalCompositionVec {
            ..Default::default()
        }
    }

    fn find(&self, elt_spec: &ElementSpecification<'lifespan>) -> Option<usize> {
        let found = self
            .composition
            .iter()
            .enumerate()
            .find(|(_, (e, _))| elt_spec == e);
        if let Some((index, _)) = found {
            Some(index)
        } else {
            None
        }
    }

    fn find_str(&self, elt_str: &str) -> &i32 {
        if let Some((_, c)) = self.composition.iter().find(|(e, _)| e == elt_str) {
            c
        } else {
            &ZERO
        }
    }

    pub fn get_str(&self, elt_str: &str) -> i32 {
        *self.find_str(elt_str)
    }

    #[inline]
    /// Access a specific element's count, or `0` if that element is absent
    /// from the composition
    pub fn get(&self, elt_spec: &ElementSpecification<'lifespan>) -> i32 {
        if let Some((_, c)) = self.composition.iter().find(|(e, _)| elt_spec == e) {
            *c
        } else {
            0
        }
    }

    #[inline]
    /// Set the count for a specific element. This will invalidate the mass cache.
    pub fn set(&mut self, elt_spec: ElementSpecification<'lifespan>, count: i32) {
        if let Some(i) = self.find(&elt_spec) {
            self.composition[i].1 = count
        } else {
            self.composition.push((elt_spec, count));
        }
        self.mass_cache = None;
    }

    #[inline]
    /// Add some value to the count of the specified element. This will invalidate the
    /// mass cache.
    pub fn inc(&mut self, elt_spec: ElementSpecification<'lifespan>, count: i32) {
        let i = self.get(&elt_spec);
        self.set(elt_spec, i + count);
    }

    #[inline]
    pub fn iter(&self) -> Iter<(ElementSpecification<'lifespan>, i32)> {
        (self.composition).iter()
    }

    pub fn iter_mut(&mut self) -> IterMut<(ElementSpecification<'lifespan>, i32)> {
        self.composition.iter_mut()
    }

    pub(crate) fn get_ref(&self) -> &[(ElementSpecification<'lifespan>, i32)] {
        &self.composition
    }

    #[allow(unused)]
    pub(crate) fn get_mut(&mut self) -> &mut [(ElementSpecification<'lifespan>, i32)] {
        &mut self.composition
    }

    /**
    Return [`self.composition`], consuming the object
    */
    pub fn into_inner(self) -> Vec<(ElementSpecification<'lifespan>, i32)> {
        self.composition
    }

    /*
    # Mass calculation Methods

    [`ChemicalCompositionVec`] has three methods for computing the monoisotopic
    mass of the composition it represents to handle mutability.
    */

    #[inline]
    /**
    Explicitly calculate the mass of the chemical composition, ignoring
    any caching.
    */
    pub fn calc_mass(&self) -> f64 {
        let mut total = 0.0;
        for (elt_spec, count) in &self.composition {
            let element = elt_spec.element;
            total = if elt_spec.isotope == 0 {
                element.most_abundant_mass
            } else {
                element.isotopes[&elt_spec.isotope].mass
            }
            .mul_add(*count as f64, total);
        }
        total
    }

    #[inline]
    /**
    Get the mass of this chemical composition. If the mass cache
    has been populated, return that instead of repeating the calculation.
    */
    pub fn mass(&self) -> f64 {
        match self.mass_cache {
            None => self.calc_mass(),
            Some(val) => val,
        }
    }

    #[inline]
    /**
    Get the mass of this chemical composition, and cache it,
    or reuse the cached value. This requires mutability, so this method
    must be called explicitly.
    */
    pub fn fmass(&mut self) -> f64 {
        match self.mass_cache {
            None => {
                let total = self.mass();
                self.mass_cache = Some(total);
                total
            }
            Some(val) => val,
        }
    }

    #[inline]
    /// Test if the mass cache is populated.
    pub fn has_mass_cached(&self) -> bool {
        self.mass_cache.is_some()
    }
}

const ZERO: i32 = 0;

impl<'lifespan> Index<&ElementSpecification<'lifespan>> for ChemicalCompositionVec<'lifespan> {
    type Output = i32;

    #[inline]
    fn index(&self, key: &ElementSpecification<'lifespan>) -> &Self::Output {
        if let Some(i) = self.find(key) {
            let (_, out) = self.composition.get(i).unwrap();
            out
        } else {
            &ZERO
        }
    }
}

impl<'lifespan> IndexMut<&ElementSpecification<'lifespan>> for ChemicalCompositionVec<'lifespan> {
    #[inline]
    fn index_mut(&mut self, key: &ElementSpecification<'lifespan>) -> &mut Self::Output {
        self.mass_cache = None;
        if let Some(i) = self.find(key) {
            let (_, out) = self.composition.get_mut(i).unwrap();
            out
        } else {
            self.set(*key, 0);
            let i = self.composition.len() - 1;
            let (_, out) = self.composition.get_mut(i).unwrap();
            out
        }
    }
}

impl Index<&str> for ChemicalCompositionVec<'_> {
    type Output = i32;

    /**
    Using the [`Index`] trait to access element counts with a [`&str`] is more
    flexible than [`ChemicalCompositionVec::get_str`], supporting fixed
    isotope strings, but does slightly more string checking up-front.
    */
    #[inline]
    fn index(&self, key: &str) -> &Self::Output {
        match ElementSpecification::quick_check_str(key) {
            ElementSpecificationLike::Yes => self.find_str(key),
            ElementSpecificationLike::No => &ZERO,
            ElementSpecificationLike::Maybe => {
                let spec = key.parse::<ElementSpecification>();
                match spec {
                    Ok(spec) => self.index(&spec),
                    Err(_err) => &ZERO,
                }
            }
        }
    }
}

impl IndexMut<&str> for ChemicalCompositionVec<'_> {
    /** Using [`IndexMut`] with a [`&str`] will always construct a new
    [`ElementSpecification`] from the provided `&str`, in order to
    maintain the contract with with [`std::ops::Index`]
    */
    #[inline]
    fn index_mut(&mut self, key: &str) -> &mut Self::Output {
        self.mass_cache = None;
        let key = key.parse::<ElementSpecification>().unwrap();
        let entry = self.index_mut(&key);
        entry
    }
}

impl<'lifespan, 'transient, 'outer: 'transient> ChemicalCompositionVec<'lifespan> {
    #[inline]
    pub(crate) fn _add_from(
        &'outer mut self,
        other: &'transient ChemicalCompositionVec<'lifespan>,
    ) {
        for (key, val) in other.iter() {
            self.inc(*key, *val);
        }
    }

    #[inline]
    pub(crate) fn _sub_from(
        &'outer mut self,
        other: &'transient ChemicalCompositionVec<'lifespan>,
    ) {
        for (key, val) in other.iter() {
            self.inc(*key, -(*val));
        }
    }

    #[inline]
    pub(crate) fn _mul_by(&mut self, scaler: i32) {
        self.composition.iter_mut().for_each(|(_, v)| {
            *v *= scaler;
        })
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.composition.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.composition.is_empty()
    }
}

impl<'lifespan> PartialEq<ChemicalCompositionVec<'lifespan>> for ChemicalCompositionVec<'lifespan> {
    #[inline]
    fn eq(&self, other: &ChemicalCompositionVec<'lifespan>) -> bool {
        if self.len() != other.len() {
            false
        } else {
            self.iter().all(|(k, v)| other.get(k) == *v)
        }
    }
}

impl<'lifespan> FromIterator<(ElementSpecification<'lifespan>, i32)>
    for ChemicalCompositionVec<'lifespan>
{
    #[inline]
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = (ElementSpecification<'lifespan>, i32)>,
    {
        let mut composition = ChemicalCompositionVec::new();
        for (k, v) in iter {
            composition.inc(k, v);
        }
        composition
    }
}

impl<'lifespan> FromIterator<(&'lifespan str, i32)> for ChemicalCompositionVec<'lifespan> {
    #[inline]
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = (&'lifespan str, i32)>,
    {
        let mut composition = ChemicalCompositionVec::new();
        for (k, v) in iter {
            let elt_spec = ElementSpecification::parse(k).unwrap();
            composition.inc(elt_spec, v);
        }
        composition
    }
}

impl<'lifespan> From<Vec<(&'lifespan str, i32)>> for ChemicalCompositionVec<'lifespan> {
    #[inline]
    fn from(elements: Vec<(&'lifespan str, i32)>) -> Self {
        elements.iter().cloned().collect()
    }
}

impl<'lifespan> From<Vec<(ElementSpecification<'lifespan>, i32)>>
    for ChemicalCompositionVec<'lifespan>
{
    fn from(elements: Vec<(ElementSpecification<'lifespan>, i32)>) -> Self {
        ChemicalCompositionVec {
            composition: elements,
            mass_cache: None,
        }
    }
}

impl FromStr for ChemicalCompositionVec<'_> {
    type Err = FormulaParserError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parser = FormulaParser::default();
        parser.parse_formula_with_table_generic(s, &PERIODIC_TABLE)
    }
}

impl Display for ChemicalCompositionVec<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&crate::formula::to_formula(self))
    }
}

#[cfg(test)]
mod test {
    use super::*;

    // #[test]
    // fn test_parse() {
    //     let case = ChemicalComposition::parse("H2O").expect("Failed to parse");
    //     let mut ctrl = ChemicalComposition::new();
    //     ctrl.set(("O").parse::<ElementSpecification>().unwrap(), 1);
    //     ctrl.set(("H").parse::<ElementSpecification>().unwrap(), 2);
    //     assert_eq!(case, ctrl);
    //     let case = ChemicalComposition::parse("H2O1").expect("Failed to parse");
    //     assert_eq!(case, ctrl);
    //     let case = ChemicalComposition::parse("(H)2O1").expect("Failed to parse");
    //     assert_eq!(case, ctrl);
    // }

    #[test]
    fn test_from_vec_str() {
        let case = ChemicalCompositionVec::from(vec![("O", 1), ("H", 2)]);
        let mut ctrl = ChemicalCompositionVec::new();
        ctrl.set(("O").parse::<ElementSpecification>().unwrap(), 1);
        ctrl.set(("H").parse::<ElementSpecification>().unwrap(), 2);
        assert_eq!(case, ctrl);
    }

    #[test]
    fn test_from_vec_elt_spec() {
        let hydrogen = ("H").parse::<ElementSpecification>().unwrap();
        let oxygen = ("O").parse::<ElementSpecification>().unwrap();
        let case = ChemicalCompositionVec::from(vec![(oxygen, 1), (hydrogen, 2)]);
        let mut ctrl = ChemicalCompositionVec::new();

        let hydrogen = ("H").parse::<ElementSpecification>().unwrap();
        let oxygen = ("O").parse::<ElementSpecification>().unwrap();
        ctrl.set(oxygen, 1);
        ctrl.set(hydrogen, 2);
        assert_eq!(case, ctrl);
    }

    #[test]
    fn test_mass() {
        let case = ChemicalCompositionVec::from(vec![("O", 1), ("H", 2)]);
        let mass = 18.0105646837;

        let calc = case.mass();
        assert!((mass - calc).abs() < 1e-6);
    }

    #[test]
    fn test_fmass() {
        let mut case: ChemicalCompositionVec = (vec![("O", 1), ("H", 2)]).into();
        let mass = 18.0105646837;

        let calc = case.fmass();
        assert!((mass - calc).abs() < 1e-6);
    }

    #[test]
    fn test_add() {
        let case = ChemicalCompositionVec::from(vec![("O", 1), ("H", 2)]);
        let ctrl = ChemicalCompositionVec::from(vec![("O", 2), ("H", 4)]);

        let combo = &case + &case;
        assert_eq!(ctrl, combo);
    }

    #[test]
    fn test_sub() {
        let case = ChemicalCompositionVec::from(vec![("O", 2), ("H", 4)]);
        let ctrl = ChemicalCompositionVec::from(vec![("O", 1), ("H", 2)]);

        let combo = &case - &ctrl;
        assert_eq!(ctrl, combo);
    }

    #[test]
    fn test_mul() {
        let case = ChemicalCompositionVec::from(vec![("O", 1), ("H", 2)]);
        let ctrl = ChemicalCompositionVec::from(vec![("O", 2), ("H", 4)]);

        let combo = &case * 2;
        assert_eq!(ctrl, combo);
    }
}