psamm.formula – Chemical compound formula

Parser and representation of chemical formulas.

Chemical formulas (Formula) are represented as a number of FormulaElements with associated counts. A Formula is itself a FormulaElement so a formula can contain subformulas. This allows some simple structure to be represented.

class psamm.formula.Atom(symbol)

Represent an atom in a chemical formula

>>> hydrogen = Atom.H
>>> oxygen = Atom.O
>>> str(oxygen | 2*hydrogen)

Atom symbol

>>> Atom.H.symbol
class psamm.formula.Formula(values={})

Representation of a chemial formula

This is represented as a number of FormulaElements with associated counts.

>>> f = Formula({Atom.C: 6, Atom.H: 12, Atom.O: 6})
>>> str(f)
classmethod balance(lhs, rhs)

Return formulas that need to be added to balance given formulas

Given complete formulas for right side and left side of a reaction, calculate formulas for the missing compounds on both sides. Return as a left, right tuple. Formulas can be flattened before balancing to disregard grouping structure.


Return formula where subformulas have been flattened

>>> str(Formula.parse('(CH2)(CH2)2').flattened())
get(element, default=None)

Return value for element or default if not in the formula.


Iterate over (FormulaElement, value)-pairs

classmethod parse(s)

Parse a formula string (e.g. C6H10O2).

class psamm.formula.FormulaElement

Base class representing elements of a formula


Repeat formula element by creating a subformula


Return formula element with substitutions performed


Iterator over variables in formula element

exception psamm.formula.ParseError(*args, **kwargs)

Signals error parsing formula.

class psamm.formula.Radical(symbol)

Represents a radical or other unknown subformula


Radical symbol

>>> Radical('R1').symbol