# 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)
'H2O'

symbol

Atom symbol

>>> Atom.H.symbol
'H'

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)
'C6H12O6'

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.

flattened()

Return formula where subformulas have been flattened

>>> str(Formula.parse('(CH2)(CH2)2').flattened())
'C3H6'

get(element, default=None)

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

items()

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(count)

Repeat formula element by creating a subformula

substitute(mapping)

Return formula element with substitutions performed

variables()

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

symbol

>>> Radical('R1').symbol