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”);

  • (...)N groups multiply every element count inside them by N, with correct nesting ("((CH2)2O)3" -> "C6H12O3");

  • D is 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, subform and multiform. 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 in isotopes).

    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 own isotopes row instead of substituting it (so check_chemform(isotopes, "D2O1") reports formula "D2O1", not "[2]H2O1", with a very slightly different mass, because the D and [2]H rows of isotopes carry mass values differing in their last digit), only its internal bracket-multiplier helper substitutes D -> [2]H (so R’s own check_chemform already normalizes "(D2)3" to "[2]H6", not "D6"); and R’s check_ded substitutes D -> [2]H in deduct but D -> plain H in formula1. Issue #14 resolved this by canonicalizing: D now 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 literal D – not just a bug fix like the “Dy” guard below.

    Separately, R’s own gsub("D", ...) calls lack the “Dy” guard above in check_ded/mergeform/subform and silently corrupt any formula containing “Dy” there (only R’s multiform guards against it); this port applies the guard everywhere a D substitution happens, which – unlike the canonicalization above – is a plain bug fix, flagged as a divergence from R like the adducts.csv fix.

  • check_chemform merges repeated elements in a formula, summing their counts and keeping the position of first occurrence ("C2C3" -> "C5"). mergeform does not do this for you: a repeated element within a single input formula (already-normalized formulas are not supposed to have one) raises ValueError instead of being silently merged – see mergeform().

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, for get_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) of monoisotopic_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) and monoisotopic_mass (float), one row per input formula, when get_list=False. For an invalid formula, warning is True, new_formula echoes the original (unmodified) input string and monoisotopic_mass is -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 deduct is fully contained in each of formulas.

Port of R’s check_ded. formulas and deduct must already be fully counted, unbracketed formulas (as produced by check_chemform()).

D is substituted for [2]H before tokenizing, in both deduct and each of formulas. R’s original substitutes D -> [2]H in deduct but D -> plain H in formula1; this port canonicalizes both sides to deuterium instead (issue #14), so e.g. check_ded(["C4D10"], "C4H10") now reports True (deduct’s H10 is 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 if deduct is 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 raises ValueError promptly instead of “fixing” the corruption by merging the duplicate for the caller. Normalize with check_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 formula1 or formula2 contains 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 fact through unchanged into count * fact, so e.g. fact=0.5 halves every count without any rounding).

Returns:
list[str]

One multiplied formula string per entry in formula_in.

envipat.formula.subform(formula1, formula2)[source]

Subtract formula2 from each of formula1.

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 if formula2 was 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".