envipat.formula¶
Chemical formula string helpers.
Port of R’s check_chemform, check_ded, mergeform, subform
and multiform.
check_chemform validates and normalizes a chemical formula string (an
optional [NN] isotope-mass-number prefix, one capital letter, zero or
more lowercase letters, and an optional integer count – repeated, and
optionally grouped in round brackets with their own trailing count, e.g.
"(NH4)2SO4") and computes its monoisotopic mass from an isotopes
reference table. check_ded, mergeform, subform and
multiform are formula-algebra helpers built on the same element/count
grammar, but – like their R originals – they operate on already
normalized, fully counted formulas (no round brackets, every element
followed by an explicit count) such as check_chemform’s own
new_formula output; they are typically used downstream of it (e.g. for
adduct arithmetic, see adducts).
Tokenizer, not a character-by-character port¶
R’s originals re-scan the formula character by character (substr(x, j,
j)) through several sequential passes (validate characters, validate
bracket balance, insert implicit 1``s, expand ``(...)N groups
textually, then disassemble into element/count pairs). This module instead
parses each formula once with a small recursive-descent tokenizer
(_parse_flat for the four flat-formula helpers, _parse_nested for
check_chemform), but reproduces R’s exact normalization rules:
an omitted count after an element or a
(...)group defaults to 1 (“implicit 1 insertion”);(...)Ngroups multiply every element count inside them by N, with correct nesting ("((CH2)2O)3"->"C6H12O3");Dis substituted for[2]H(a literal text substitution) in all five functions, consistently:check_chemform(both at the top level and inside a(...)group),check_ded(both its deduct and its formulas argument),mergeform,subformandmultiform. Every one of these substitutions uses a negative lookahead (D(?![a-z])) so as not to clobber a longer symbol starting with “D” – e.g. “Dy” (dysprosium, present inisotopes).This is a deliberate, disclosed divergence from R (issue #14): R’s five functions disagree with each other about
D–check_chemform’s top level looks"D"up directly as its ownisotopesrow instead of substituting it (socheck_chemform(isotopes, "D2O1")reports formula"D2O1", not"[2]H2O1", with a very slightly different mass, because theDand[2]Hrows ofisotopescarry mass values differing in their last digit), only its internal bracket-multiplier helper substitutesD->[2]H(so R’s owncheck_chemformalready normalizes"(D2)3"to"[2]H6", not"D6"); and R’scheck_dedsubstitutesD->[2]HindeductbutD-> plainHinformula1. Issue #14 resolved this by canonicalizing:Dnow means deuterium ([2]H) everywhere in this Python port, in every function and every argument. This is a real, permanent behavioural difference from R for any formula containing a literalD– not just a bug fix like the “Dy” guard below.Separately, R’s own
gsub("D", ...)calls lack the “Dy” guard above incheck_ded/mergeform/subformand silently corrupt any formula containing “Dy” there (only R’smultiformguards against it); this port applies the guard everywhere aDsubstitution happens, which – unlike the canonicalization above – is a plain bug fix, flagged as a divergence from R like theadducts.csvfix.check_chemformmerges repeated elements in a formula, summing their counts and keeping the position of first occurrence ("C2C3"->"C5").mergeformdoes not do this for you: a repeated element within a single input formula (already-normalized formulas are not supposed to have one) raisesValueErrorinstead of being silently merged – seemergeform().
Reference mass lookup¶
Each element symbol’s reference mass for the monoisotopic-mass sum is the
mass of its most abundant isotope row in isotopes (this is what
makes an isotope-labelled symbol like "[13]C" – which appears in
isotopes as its own single row with abundance 1 – resolve to that
row’s own mass, while a plain "C" resolves to natural carbon’s
most-abundant isotope, 12C). This mirrors R’s check_chemform
internals exactly.
- envipat.formula.check_chemform(isotopes, chemforms, get_sorted=False, get_list=False)[source]¶
Check and normalize chemical formulas; compute monoisotopic mass.
Port of R’s
check_chemform.- Parameters:
- isotopes
Isotope reference table (columns, by position: element, isotope, mass, abundance, …), e.g.
envipat.data.isotopes.- chemforms
A single formula string or an iterable of formula strings.
- get_sorted
If True, reorder each formula’s elements into the order they first appear in
isotopes(both in the returned formula string and, forget_list=True, in the returned element/count mapping) instead of the order they first appear in the input formula. This also changes floating-point summation order and therefore, in rare cases, the last bit(s) ofmonoisotopic_mass.- get_list
If True, return a
list[dict[str, int]](one dict of element -> count per input formula, in input order; an empty dict for an invalid formula) instead of a DataFrame.
- Returns:
- pandas.DataFrame
Columns
warning(bool),new_formula(str) andmonoisotopic_mass(float), one row per input formula, whenget_list=False. For an invalid formula,warningis True,new_formulaechoes the original (unmodified) input string andmonoisotopic_massis -9999 – matching R exactly.- list[dict[str, int]]
When
get_list=True.
- Raises:
- ValueError
If any formula contains a space (matches R’s hard
stop()).
- envipat.formula.check_ded(formulas, deduct)[source]¶
Check whether
deductis fully contained in each offormulas.Port of R’s
check_ded.formulasanddeductmust already be fully counted, unbracketed formulas (as produced bycheck_chemform()).Dis substituted for[2]Hbefore tokenizing, in bothdeductand each offormulas. R’s original substitutesD->[2]HindeductbutD-> plainHinformula1; this port canonicalizes both sides to deuterium instead (issue #14), so e.g.check_ded(["C4D10"], "C4H10")now reportsTrue(deduct’sH10is not contained in the formula’s[2]H10), unlike R.- Parameters:
- formulas
A single formula string or an iterable of formula strings (the “containing” side).
- deduct
A single formula string (the “deduct”).
- Returns:
- list[bool]
One entry per formula in
formulas: True ifdeductis not fully contained in that formula, False if it is.
- envipat.formula.mergeform(formula1, formula2)[source]¶
Combine chemical formulas by summing element counts.
Port of R’s
mergeform. Both arguments must already be fully counted, unbracketed formulas.Unlike R’s original – which, given a formula with an internally repeated, un-merged element (e.g. R’s
adducts"M+H+NH4"->"H1N1H4"), silently corrupts every element processed afterwards via vector recycling (see MR !7 for the full trace) – this raisesValueErrorpromptly instead of “fixing” the corruption by merging the duplicate for the caller. Normalize withcheck_chemform()first if a formula may contain repeats.- Parameters:
- formula1
A single formula string or an iterable of formula strings.
- formula2
A single formula string, merged into each of
formula1.
- Returns:
- list[str]
One merged formula string per entry in
formula1.
- Raises:
- ValueError
If a formula omits an explicit count after some element, or if either
formula1orformula2contains the same element symbol more than once as separate tokens.
- envipat.formula.multiform(formula_in, fact)[source]¶
Multiply every element count in a chemical formula by a factor.
Port of R’s
multiform. Must already be a fully counted, unbracketed formula.- Parameters:
- formula_in
A single formula string or an iterable of formula strings.
- fact
Scalar factor to multiply every element count by (need not be an integer; R’s own examples pass
factthrough unchanged intocount * fact, so e.g.fact=0.5halves every count without any rounding).
- Returns:
- list[str]
One multiplied formula string per entry in
formula_in.
- envipat.formula.subform(formula1, formula2)[source]¶
Subtract
formula2from each offormula1.Port of R’s
subform. Both arguments must already be fully counted, unbracketed formulas. Elements whose count drops to (or was already) zero are dropped from the result, matching R.- Parameters:
- formula1
A single formula string or an iterable of formula strings (the “minuend” side).
- formula2
A single formula string, subtracted from each of
formula1.
- Returns:
- list[str]
One entry per formula in
formula1: the subtracted formula string ifformula2was fully contained in it, otherwise a human-readable message describing why not (matching R, which returns a message string instead of raising) – e.g."Cl1 from formula 2 not part of formula1"or"Atom number of C from formula 2 not fully subset of formula1 atom number".