pymatgen.core.composition module

class ChemicalPotential(*args, **kwargs)[source]

Bases: dict, monty.json.MSONable

Class to represent set of chemical potentials. Can be: multiplied/divided by a Number multiplied by a Composition (returns an energy) added/subtracted with other ChemicalPotentials.

Parameters:**kwargs (*args,) –

any valid dict init arguments

get_energy(composition, strict=True)[source]

Calculates the energy of a composition.

  • composition (Composition) – input composition
  • strict (bool) – Whether all potentials must be specified
class Composition(*args, **kwargs)[source]

Bases:,, monty.json.MSONable

Represents a Composition, which is essentially a {element:amount} mapping type. Composition is written to be immutable and hashable, unlike a standard Python dict.

Note that the key can be either an Element or a Specie. Elements and Specie are treated differently. i.e., a Fe2+ is not the same as a Fe3+ Specie and would be put in separate keys. This differentiation is deliberate to support using Composition to determine the fraction of a particular Specie.

Works almost completely like a standard python dictionary, except that __getitem__ is overridden to return 0 when an element is not found. (somewhat like a defaultdict, except it is immutable).

Also adds more convenience methods relevant to compositions, e.g., get_fraction.

It should also be noted that many Composition related functionality takes in a standard string as a convenient input. For example, even though the internal representation of a Fe2O3 composition is {Element(“Fe”): 2, Element(“O”): 3}, you can obtain the amount of Fe simply by comp[“Fe”] instead of the more verbose comp[Element(“Fe”)].

>>> comp = Composition("LiFePO4")
>>> comp.get_atomic_fraction(Element("Li"))
>>> comp.num_atoms
>>> comp.reduced_formula
>>> comp.formula
'Li1 Fe1 P1 O4'
>>> comp.get_wt_fraction(Element("Li"))
>>> comp.num_atoms

Very flexible Composition construction, similar to the built-in Python dict(). Also extended to allow simple string init.

  • form supported by the Python built-in dict() function. (Any) –
  • A dict of either {Element/Specie (1.) –


    {string symbol:amount}, or {atomic number:amount} or any mixture of these. E.g., {Element(“Li”):2 ,Element(“O”):1}, {“Li”:2, “O”:1}, {3:2, 8:1} all result in a Li2O composition.

  • Keyword arg initialization, similar to a dict, e.g., (2.) – Composition(Li = 2, O = 1)
  • addition, the Composition constructor also allows a single (In) –
  • as an input formula. E.g., Composition (string) –
  • allow_negative – Whether to allow negative compositions. This argument must be popped from the **kwargs due to *args ambiguity.
almost_equals(other, rtol=0.1, atol=1e-08)[source]

Returns true if compositions are equal within a tolerance.

  • other (Composition) – Other composition to check
  • rtol (float) – Relative tolerance
  • atol (float) – Absolute tolerance

Returns a formula string, with elements sorted by alphabetically e.g., Fe4 Li4 O16 P4.

amount_tolerance = 1e-08

Special formula handling for peroxides and certain elements. This is so that formula output does not write LiO instead of Li2O2 for example.


An anonymized formula. Unique species are arranged in ordering of increasing amounts and assigned ascending alphabets. Useful for prototyping formulas. For example, all stoichiometric perovskites have anonymized_formula ABC3.

Returns:dict with species symbol and (unreduced) amount e.g., {“Fe”: 4.0, “O”:6.0} or {“Fe3+”: 4.0, “O2-“:6.0}

Returns the composition replacing any species by the corresponding element.


Returns view of elements in Composition.


Returns a formula string, with elements sorted by electronegativity, e.g., Li4 Fe4 P4 O16.


Returns the normalized composition which the number of species sum to 1.

Returns:Normalized composition which the number of species sum to 1.
classmethod from_dict(d)[source]

Creates a composition from a dict generated by as_dict(). Strictly not necessary given that the standard constructor already takes in such an input, but this method preserves the standard pymatgen API of having from_dict methods to reconstitute objects generated by as_dict(). Allows for easier introspection.

Parameters:d (dict) – {symbol: amount} dict.

Calculate atomic fraction of an Element or Specie.

Parameters:el (Element/Specie) – Element or Specie to get fraction for.
Returns:Atomic fraction for element el in Composition
Returns:Dict with element symbol and (unreduced) amount e.g., {“Fe”: 4.0, “O”:6.0} or {“Fe3+”: 4.0, “O2-“:6.0}

Calculates an integer formula and factor.

Parameters:max_denominator (int) – all amounts in the el:amt dict are first converted to a Fraction with this maximum denominator
Returns:A pretty normalized formula and a multiplicative factor, i.e., Li0.5O0.25 returns (Li2O, 0.25). O0.25 returns (O2, 0.125)

Calculates a reduced composition and factor.

Returns:A normalized composition and a multiplicative factor, i.e., Li4Fe4P4O16 returns (Composition(“LiFePO4”), 4).

Calculates a reduced formula and factor.

Returns:A pretty normalized formula and a multiplicative factor, i.e., Li4Fe4P4O16 returns (LiFePO4, 4).

Calculate weight fraction of an Element or Specie.

Parameters:el (Element/Specie) – Element or Specie to get fraction for.
Returns:Weight fraction for element el in Composition

True if composition is for an element.


Total number of atoms in Composition. For negative amounts, sum of absolute values

oxi_prob = None
oxi_state_guesses(oxi_states_override=None, target_charge=0, all_oxi_states=False, max_sites=None)[source]

Checks if the composition is charge-balanced and returns back all charge-balanced oxidation state combinations. Composition must have integer values. Note that more num_atoms in the composition gives more degrees of freedom. e.g., if possible oxidation states of element X are [2,4] and Y are [-3], then XY is not charge balanced but X2Y2 is. Results are returned from most to least probable based on ICSD statistics. Use max_sites to improve performance if needed.

  • oxi_states_override (dict) – dict of str->list to override an element’s common oxidation states, e.g. {“V”: [2,3,4,5]}
  • target_charge (int) – the desired total charge on the structure. Default is 0 signifying charge balance.
  • all_oxi_states (bool) – if True, an element defaults to all oxidation states in pymatgen Element.icsd_oxidation_states. Otherwise, default is Element.common_oxidation_states. Note that the full oxidation state list is very inclusive and can produce nonsensical results.
  • max_sites (int) – if possible, will reduce Compositions to at most this many many sites to speed up oxidation state guesses. Set to -1 to just reduce fully.

A list of dicts - each dict reports an element symbol and average

oxidation state across all sites in that composition. If the composition is not charge balanced, an empty list is returned.

static ranked_compositions_from_indeterminate_formula(fuzzy_formula, lock_if_strict=True)[source]

Takes in a formula where capitilization might not be correctly entered, and suggests a ranked list of potential Composition matches. Author: Anubhav Jain

  • fuzzy_formula (str) – A formula string, such as “co2o3” or “MN”, that may or may not have multiple interpretations
  • lock_if_strict (bool) – If true, a properly entered formula will only return the one correct interpretation. For example, “Co1” will only return “Co1” if true, but will return both “Co1” and “C1 O1” if false.

A ranked list of potential Composition matches


Returns the reduced composition,i.e. amounts normalized by greatest common denominator. e.g., Composition(“FePO4”) for Composition(“Fe4P4O16”).


Returns a pretty normalized formula, i.e., LiFePO4 instead of Li4Fe4P4O16.

special_formulas = {'LiO': 'Li2O2', 'NaO': 'Na2O2', 'KO': 'K2O2', 'HO': 'H2O2', 'CsO': 'Cs2O2', 'RbO': 'Rb2O2', 'O': 'O2', 'N': 'N2', 'F': 'F2', 'Cl': 'Cl2', 'H': 'H2'}

Returns – A dict with many keys and values relating to Composition/Formula, including reduced_cell_composition, unit_cell_composition, reduced_cell_formula, elements and nelements.


Returns – Dict with element symbol and reduced amount e.g., {“Fe”: 2.0, “O”:3.0}

exception CompositionError[source]

Bases: Exception

Exception class for composition errors


Helper method to reduce a sym_amt dict to a reduced formula and factor.

Parameters:sym_amt (dict) – {symbol: amount}.
Returns:(reduced_formula, factor).