pymatgen.analysis namespace

Submodules

pymatgen.analysis.chempot_diagram module

This module implements the construction and plotting of chemical potential diagrams from a list of entries within a chemical system containing 2 or more elements. The chemical potential diagram is the mathematical dual to the traditional compositional phase diagram.

For more information, please cite/reference the paper below:

Todd, P. K., McDermott, M. J., Rom, C. L., Corrao, A. A., Denney, J. J., Dwaraknath, S. S., Khalifah, P. G., Persson, K. A., & Neilson, J. R. (2021). Selectivity in Yttrium Manganese Oxide Synthesis via Local Chemical Potentials in Hyperdimensional Phase Space. Journal of the American Chemical Society, 143(37), 15185-15194. https://doi.org/10.1021/jacs.1c06229

Please also consider referencing the original 1999 paper by H. Yokokawa, who outlined many of its possible uses:

Yokokawa, H. “Generalized chemical potential diagram and its applications to chemical reactions at interfaces between dissimilar materials.” JPE 20, 258 (1999). https://doi.org/10.1361/105497199770335794

class ChemicalPotentialDiagram(entries: list[PDEntry], limits: dict[Element, tuple[float, float]] | None = None, default_min_limit: float = -50.0, formal_chempots: bool = True)[source]

Bases: MSONable

The chemical potential diagram is the mathematical dual to the compositional phase diagram. To create the diagram, convex minimization is performed in energy (E) vs. chemical potential (μ) space by taking the lower convex envelope of hyperplanes. Accordingly, “points” on the compositional phase diagram become N-dimensional convex polytopes (domains) in chemical potential space.

For more information on this specific implementation of the algorithm, please cite/reference the paper below:

Todd, P. K., McDermott, M. J., Rom, C. L., Corrao, A. A., Denney, J. J., Dwaraknath, S. S., Khalifah, P. G., Persson, K. A., & Neilson, J. R. (2021). Selectivity in Yttrium Manganese Oxide Synthesis via Local Chemical Potentials in Hyperdimensional Phase Space. Journal of the American Chemical Society, 143(37), 15185-15194. https://doi.org/10.1021/jacs.1c06229

Parameters:
  • entries (list[PDEntry]) – PDEntry-like objects containing a composition and energy. Must contain elemental references and be suitable for typical phase diagram construction. Entries must be within a chemical system of with 2+ elements.

  • limits (dict[Element, float] | None) – Bounds of elemental chemical potentials (min, max), which are used to construct the border hyperplanes used in the HalfSpaceIntersection algorithm; these constrain the space over which the domains are calculated and also determine the size of the plotted diagram. Any elemental limits not specified are covered in the default_min_limit argument. e.g. {Element(“Li”): [-12.0, 0.0], …}

  • default_min_limit (float) – Default minimum chemical potential limit (i.e., lower bound) for unspecified elements within the “limits” argument.

  • formal_chempots (bool) – Whether to plot the formal (‘reference’) chemical potentials (i.e. μ_X - μ_X^0) or the absolute DFT reference energies (i.e. μ_X(DFT)). Default is True (i.e. plot formal chemical potentials).

property border_hyperplanes: ndarray[source]

Bordering hyperplanes.

property chemical_system: str[source]

The chemical system (A-B-C-…) of diagram object.

property domains: dict[str, ndarray][source]

Mapping of formulas to array of domain boundary points.

property el_refs: dict[Element, PDEntry][source]

A dictionary of elements and reference entries.

property entry_dict: dict[str, ComputedEntry][source]

Mapping between reduced formula and ComputedEntry.

get_plot(elements: list[Element | str] | None = None, label_stable: bool | None = True, formulas_to_draw: list[str] | None = None, draw_formula_meshes: bool | None = True, draw_formula_lines: bool | None = True, formula_colors: list[str] = ['rgb(27,158,119)', 'rgb(217,95,2)', 'rgb(117,112,179)', 'rgb(231,41,138)', 'rgb(102,166,30)', 'rgb(230,171,2)', 'rgb(166,118,29)', 'rgb(102,102,102)'], element_padding: float | None = 1.0) Figure[source]

Plot the 2-dimensional or 3-dimensional chemical potential diagram using an interactive Plotly interface.

Elemental axes can be specified; if none provided, will automatically default to first 2-3 elements within the “elements” attribute.

In 3D, this method also allows for plotting of lower-dimensional “slices” of hyperdimensional polytopes (e.g., the LiMnO2 domain within a Y-Mn-O diagram). This allows for visualization of some of the phase boundaries that can only be seen fully in high dimensional space; see the “formulas_to_draw” argument.

Parameters:
  • elements – list of elements to use as axes in the diagram. If None, automatically defaults to the first 2 or elements within the object’s “elements” attribute.

  • label_stable – whether to label stable phases by their reduced formulas. Defaults to True.

  • formulas_to_draw – for 3-dimensional diagrams, an optional list of formulas to plot on the diagram; if these are from a different chemical system a 3-d polyhedron “slice” will be plotted. Defaults to None.

  • draw_formula_meshes – whether to draw a colored mesh for the optionally specified formulas_to_draw. Defaults to True.

  • draw_formula_lines – whether to draw bounding lines for the optionally specified formulas_to_draw. Defaults to True.

  • formula_colors – a list of colors to use in the plotting of the optionally specified formulas_to-draw. Defaults to the Plotly Dark2 color scheme.

  • element_padding – if provided, automatically adjusts chemical potential axis limits of the plot such that elemental domains have the specified padding (in eV/atom), helping provide visual clarity. Defaults to 1.0.

Returns:

plotly.graph_objects.Figure

property hyperplane_entries: list[PDEntry][source]

List of entries corresponding to hyperplanes.

property hyperplanes: ndarray[source]

Array of hyperplane data.

property lims: ndarray[source]

Array of limits used in constructing hyperplanes.

get_2d_orthonormal_vector(line_pts: ndarray) ndarray[source]

Calculates a vector that is orthonormal to a line given by a set of points. Used for determining the location of an annotation on a 2-d chemical potential diagram.

Parameters:

line_pts – a 2x2 array in the form of [[x0, y0], [x1, y1]] giving the coordinates of a line

Returns:

A length-2 vector that is orthonormal to the line.

Return type:

np.ndarray

get_centroid_2d(vertices: ndarray) ndarray[source]

A bare-bones implementation of the formula for calculating the centroid of a 2D polygon. Useful for calculating the location of an annotation on a chemical potential domain within a 3D chemical potential diagram.

NOTE vertices must be ordered circumferentially!

Parameters:

vertices – array of 2-d coordinates corresponding to a polygon, ordered circumferentially

Returns:

Giving 2-d centroid coordinates.

Return type:

np.ndarray

simple_pca(data: ndarray, k: int = 2) tuple[ndarray, ndarray, ndarray][source]

A bare-bones implementation of principal component analysis (PCA) used in the ChemicalPotentialDiagram class for plotting.

Parameters:
  • data – array of observations

  • k – Number of principal components returned

Returns:

projected data, eigenvalues, eigenvectors

Return type:

tuple

pymatgen.analysis.phase_diagram module

This module defines tools to generate and analyze phase diagrams.

class CompoundPhaseDiagram(entries: Sequence[Entry], terminal_compositions: Sequence[Composition], normalize_terminal_compositions: bool = True)[source]

Bases: PhaseDiagram

Generates phase diagrams from compounds as terminations instead of elements.

Initialize a CompoundPhaseDiagram.

Parameters:
  • entries ([PDEntry]) – Sequence of input entries. For example, if you want a Li2O-P2O5 phase diagram, you might have all Li-P-O entries as an input.

  • terminal_compositions (list[Composition]) – Terminal compositions of phase space. In the Li2O-P2O5 example, these will be the Li2O and P2O5 compositions.

  • normalize_terminal_compositions (bool) – Whether to normalize the terminal compositions to a per atom basis. If normalized, the energy above hulls will be consistent for comparison across systems. Non-normalized terminals are more intuitive in terms of compositional breakdowns.

amount_tol: ClassVar[float] = 1e-05[source]
as_dict()[source]

Get MSONable dict representation of CompoundPhaseDiagram.

classmethod from_dict(dct: dict) Self[source]
Parameters:

dct (dict) – dictionary representation of CompoundPhaseDiagram.

Returns:

CompoundPhaseDiagram

static num2str(num)[source]

Convert number to a list of letter(s). First letter must be f.

Parameters:

int (num) – Number to convert

Return type:

str

:return Converted string

transform_entries(entries: Sequence[Entry], terminal_compositions: Sequence[Composition]) tuple[list[TransformedPDEntry], dict[Composition, DummySpecies]][source]

Method to transform all entries to the composition coordinate in the terminal compositions. If the entry does not fall within the space defined by the terminal compositions, they are excluded. For example, Li3PO4 is mapped into a Li2O:1.5, P2O5:0.5 composition. The terminal compositions are represented by DummySpecies.

TODO: update serialization here.

Parameters:
  • entries – Sequence of all input entries

  • terminal_compositions – Terminal compositions of phase space.

Returns:

Sequence of TransformedPDEntries falling within the phase space.

class GrandPotPDEntry(entry: PDEntry, chempots: dict[Element, float], name: str | None = None)[source]

Bases: PDEntry

A grand potential pd entry object encompassing all relevant data for phase diagrams. Chemical potentials are given as a element-chemical potential dict.

Parameters:
  • entry – A PDEntry-like object.

  • chempots – Chemical potential specification as {Element: float}.

  • name – Optional parameter to name the entry. Defaults to the reduced chemical formula of the original entry.

as_dict() dict[str, Any][source]

Get MSONable dict representation of GrandPotPDEntry.

property chemical_energy: float[source]

The chemical energy term mu*N in the grand potential.

Returns:

The chemical energy term mu*N in the grand potential

property composition: Composition[source]

The composition after removing free species.

Returns:

Composition

property energy: float[source]

Grand potential energy.

classmethod from_dict(dct: dict) Self[source]
Parameters:

dct (dict) – dictionary representation of GrandPotPDEntry.

Returns:

GrandPotPDEntry

class GrandPotentialPhaseDiagram(entries: Collection[Entry], chempots: dict[Element, float], elements: Collection[Element] | None = None, *, computed_data: dict[str, Any] | None = None)[source]

Bases: PhaseDiagram

A class representing a Grand potential phase diagram. Grand potential phase diagrams are essentially phase diagrams that are open to one or more components. To construct such phase diagrams, the relevant free energy is the grand potential, which can be written as the Legendre transform of the Gibbs free energy as follows.

Grand potential = G - u_X N_X

The algorithm is based on the work in the following papers:

  1. S. P. Ong, L. Wang, B. Kang, and G. Ceder, Li-Fe-P-O2 Phase Diagram from First Principles Calculations. Chem. Mater., 2008, 20(5), 1798-1807. doi:10.1021/cm702327g

  2. S. P. Ong, A. Jain, G. Hautier, B. Kang, G. Ceder, Thermal stabilities of delithiated olivine MPO4 (M=Fe, Mn) cathodes investigated using first principles calculations. Electrochem. Comm., 2010, 12(3), 427-430. doi:10.1016/j.elecom.2010.01.010

Standard constructor for grand potential phase diagram.

TODO: update serialization here.

Parameters:
  • entries (Sequence[Entry]) – A list of Entry objects having an energy, energy_per_atom and composition.

  • chempots (dict[Element, float]) – Specify the chemical potentials of the open elements.

  • elements (Sequence[Element]) – Optional list of elements in the phase diagram. If set to None, the elements are determined from the entries themselves.

  • computed_data (dict[str, Any]) – A dict containing pre-computed data. This allows PhaseDiagram object to be reconstituted without performing the expensive convex hull computation. The dict is the output from the PhaseDiagram._compute() method and is stored in PhaseDiagram.computed_data when generated for the first time.

as_dict()[source]

Get MSONable dict representation of GrandPotentialPhaseDiagram.

classmethod from_dict(dct: dict) Self[source]
Parameters:

dct (dict) – dictionary representation of GrandPotentialPhaseDiagram.

Returns:

GrandPotentialPhaseDiagram

class PDEntry(composition: CompositionLike, energy: float, name: str | None = None, attribute: object = None)[source]

Bases: Entry

An object encompassing all relevant data for phase diagrams.

composition[source]

The composition associated with the PDEntry.

Type:

Composition

energy[source]

The energy associated with the entry.

Type:

float

name[source]

A name for the entry. This is the string shown in the phase diagrams. By default, this is the reduced formula for the composition, but can be set to some other string for display purposes.

Type:

str

attribute[source]

A arbitrary attribute. Can be used to specify that the entry is a newly found compound, or to specify a particular label for the entry, etc. An attribute can be anything but must be MSONable.

Type:

MSONable

Parameters:
  • composition (CompositionLike) – Composition

  • energy (float) – Energy for composition.

  • name (str) – Optional parameter to name the entry. Defaults to the reduced chemical formula.

  • attribute – Optional attribute of the entry. Must be MSONable.

as_dict() dict[str, Any][source]

Get MSONable dict representation of PDEntry.

property energy: float[source]

The entry’s energy.

classmethod from_dict(dct: dict[str, Any]) Self[source]
Parameters:

dct (dict) – dictionary representation of PDEntry.

Returns:

PDEntry

class PDPlotter(phasediagram: PhaseDiagram, show_unstable: float = 0.2, backend: Literal['plotly', 'matplotlib'] = 'plotly', ternary_style: Literal['2d', '3d'] = '2d', **plotkwargs)[source]

Bases: object

A plotting class for compositional phase diagrams.

To use, initialize this class with a PhaseDiagram object containing 1-4 components and call get_plot() or show().

Parameters:
  • phasediagram (PhaseDiagram) – PhaseDiagram object (must be 1-4 components).

  • show_unstable (float) – Whether unstable (above the hull) phases will be plotted. If a number > 0 is entered, all phases with e_hull < show_unstable (eV/atom) will be shown.

  • backend ("plotly" | "matplotlib") – Python package to use for plotting. Defaults to “plotly”.

  • ternary_style ("2d" | "3d") – Ternary phase diagrams are typically plotted in two-dimensions (2d), but can be plotted in three dimensions (3d) to visualize the depth of the hull. This argument only applies when backend=”plotly”. Defaults to “2d”.

  • **plotkwargs (dict) –

    Keyword args passed to matplotlib.pyplot.plot (only applies when backend=”matplotlib”). Can be used to customize markers etc. If not set, the default is:

    {

    “markerfacecolor”: “#4daf4a”, “markersize”: 10, “linewidth”: 3

    }.

get_chempot_range_map_plot(elements: Sequence[Element], referenced: bool = True) plt.Axes[source]

Get a plot of the chemical potential range _map. Currently works only for 3-component PDs.

Note: this functionality is now included in the ChemicalPotentialDiagram class (pymatgen.analysis.chempot_diagram).

Parameters:
  • elements – Sequence of elements to be considered as independent variables. e.g. if you want to show the stability ranges of all Li-Co-O phases w.r.t. to uLi and uO, you will supply [Element(“Li”), Element(“O”)]

  • referenced – if True, gives the results with a reference being the energy of the elemental phase. If False, gives absolute values.

Returns:

matplotlib axes object.

Return type:

plt.Axes

get_contour_pd_plot() Axes[source]

Plot a contour phase diagram plot, where phase triangles are colored according to degree of instability by interpolation. Currently only works for 3-component phase diagrams.

Returns:

A matplotlib plot object.

get_plot(label_stable: bool = True, label_unstable: bool = True, ordering: Sequence[Literal['Up', 'Left', 'Right']] | None = None, energy_colormap: str | Colormap | None = None, process_attributes: bool = False, ax: plt.Axes | None = None, label_uncertainties: bool = False, fill: bool = True, highlight_entries: Collection[PDEntry] | None = None) go.Figure | plt.Axes | None[source]
Parameters:
  • label_stable – Whether to label stable compounds.

  • label_unstable – Whether to label unstable compounds.

  • ordering – Ordering of vertices, given as a list [“Up”, “Left”, “Right”] (matplotlib only).

  • energy_colormap – Colormap for coloring energy (matplotlib only).

  • process_attributes – Whether to process the attributes (matplotlib only).

  • ax – Existing matplotlib Axes object if plotting multiple phase diagrams (matplotlib only).

  • label_uncertainties – Whether to add error bars to the hull. For binaries, this also shades the hull with the uncertainty window. (plotly only).

  • fill – Whether to shade the hull. For ternary_2d and quaternary plots, this colors facets arbitrarily for visual clarity. For ternary_3d plots, this shades the hull by formation energy (plotly only).

  • highlight_entries – Entries to highlight in the plot (plotly only). This will create a new marker trace that is separate from the other entries.

Returns:

Plotly figure or matplotlib axes object depending on backend.

Return type:

go.Figure | plt.Axes

property pd_plot_data: tuple[list, dict, dict][source]

Plotting data for phase diagram. Cached for repetitive calls.

2-comp - Full hull with energies 3/4-comp - Projection into 2D or 3D Gibbs triangles

Returns:

  • lines: a list of list of coordinates for lines in the PD.

  • stable_entries: a dict of {coordinates: entry} for each stable node

    in the phase diagram. (Each coordinate can only have one stable phase)

  • unstable_entries: a dict of {entry: coordinates} for all unstable

    nodes in the phase diagram.

Return type:

A tuple containing three objects (lines, stable_entries, unstable_entries)

plot_chempot_range_map(elements: Sequence[Element], referenced: bool = True) None[source]

Plot the chemical potential range _map using matplotlib. Currently works only for 3-component PDs. This shows the plot but does not return it.

Note: this functionality is now included in the ChemicalPotentialDiagram class (pymatgen.analysis.chempot_diagram).

Parameters:
  • elements – Sequence of elements to be considered as independent variables. e.g. if you want to show the stability ranges of all Li-Co-O phases w.r.t. to uLi and uO, you will supply [Element(“Li”), Element(“O”)]

  • referenced – if True, gives the results with a reference being the energy of the elemental phase. If False, gives absolute values.

plot_element_profile(element: Element, comp: Composition, show_label_index: list[int] | None = None, xlim: float = 5) Axes[source]

Draw the element profile plot for a composition varying different chemical potential of an element.

X value is the negative value of the chemical potential reference to elemental chemical potential. For example, if choose Element(“Li”), X= -(μLi-μLi0), which corresponds to the voltage versus metal anode. Y values represent for the number of element uptake in this composition (unit: per atom). All reactions are printed to help choosing the profile steps you want to show label in the plot.

Parameters:
  • element (Element) – An element of which the chemical potential is considered. It also must be in the phase diagram.

  • comp (Composition) – A composition.

  • show_label_index (list of integers) – The labels for reaction products you want to show in the plot. Default to None (not showing any annotation for reaction products). For the profile steps you want to show the labels, just add it to the show_label_index. The profile step counts from zero. For example, you can set show_label_index=[0, 2, 5] to label profile step 0,2,5.

  • xlim (float) – The max x value. x value is from 0 to xlim. Default to 5 eV.

Returns:

Plot of element profile evolution by varying the chemical potential of an element.

show(*args, **kwargs) None[source]

Draw the phase diagram with the provided arguments and display it. This shows the figure but does not return it.

Parameters:
  • *args – Passed to get_plot.

  • **kwargs – Passed to get_plot.

write_image(stream: str | StringIO, image_format: str = 'svg', **kwargs) None[source]

Directly save the plot to a file. This is a wrapper for calling plt.savefig() or fig.write_image(), depending on the backend. For more customization, it is recommended to call those methods directly.

Parameters:
  • stream (str | StringIO) – Filename or StringIO stream.

  • image_format (str) – Can be any supported image format for the plotting backend. Defaults to ‘svg’ (vector graphics).

  • **kwargs – Optinoal kwargs passed to the get_plot function.

class PatchedPhaseDiagram(entries: Sequence[Entry] | set[Entry], elements: Sequence[Element] | None = None, keep_all_spaces: bool = False, verbose: bool = False, *, computed_data: dict[str, Any] | None = None)[source]

Bases: PhaseDiagram

Computing the Convex Hull of a large set of data in multiple dimensions is highly expensive. This class acts to breakdown large chemical spaces into smaller chemical spaces which can be computed much more quickly due to having both reduced dimensionality and data set sizes.

subspaces ({str

{Element, }}): Dictionary of the sets of elements for each of the PhaseDiagrams within the PatchedPhaseDiagram.

pds ({str

PhaseDiagram}): Dictionary of PhaseDiagrams within the PatchedPhaseDiagram.

all_entries[source]

All entries provided for Phase Diagram construction. Note that this does not mean that all these entries are actually used in the phase diagram. For example, this includes the positive formation energy entries that are filtered out before Phase Diagram construction.

Type:

list[PDEntry]

min_entries[source]

List of the lowest energy entries for each composition in the data provided for Phase Diagram construction.

Type:

list[PDEntry]

el_refs[source]

List of elemental references for the phase diagrams. These are entries corresponding to the lowest energy element entries for simple compositional phase diagrams.

Type:

list[PDEntry]

elements[source]

List of elements in the phase diagram.

Type:

list[Element]

NOTE following methods are inherited unchanged from PhaseDiagram:
  • __repr__

  • all_entries_hulldata

  • unstable_entries

  • stable_entries

  • get_form_energy

  • get_form_energy_per_atom

  • get_hull_energy

  • get_e_above_hull

  • get_decomp_and_e_above_hull

  • get_decomp_and_phase_separation_energy

  • get_phase_separation_energ

Parameters:
  • entries – A list of Entry objects.

  • elements – Optional list of elements in the phase diagram.

  • keep_all_spaces – Whether to keep chemical spaces that are subspaces of other spaces.

  • verbose – Whether to show progress bar during convex hull construction.

  • computed_data – Pre-computed internal state. When provided the expensive entry processing and convex hull calculations are skipped and all attributes are hydrated from this dict. Follows the same pattern as PhaseDiagram.

as_dict() dict[str, Any][source]

Write the entries and elements used to construct the PatchedPhaseDiagram to a dictionary.

classmethod from_dict(dct: dict) Self[source]

Reconstruct PatchedPhaseDiagram from dictionary serialization.

Parameters:

dct (dict) – dictionary representation of PatchedPhaseDiagram.

Returns:

PatchedPhaseDiagram

get_all_chempots()[source]

Not Implemented - See PhaseDiagram.

get_chempot_range_map()[source]

Not Implemented - See PhaseDiagram.

get_chempot_range_stability_phase()[source]

Not Implemented - See PhaseDiagram.

get_composition_chempots()[source]

Not Implemented - See PhaseDiagram.

get_critical_compositions()[source]

Not Implemented - See PhaseDiagram.

get_decomp_and_e_above_hull(entry: PDEntry, allow_negative: bool = False, check_stable: bool = False, on_error: Literal['raise', 'warn', 'ignore'] = 'raise') tuple[dict[PDEntry, float], float] | tuple[None, None][source]

Same as method on parent class PhaseDiagram except check_stable defaults to False for speed. See https://github.com/materialsproject/pymatgen/issues/2840 for details.

get_decomposition(comp: Composition) dict[PDEntry, float][source]

See PhaseDiagram.

Parameters:

comp (Composition) – A composition

Returns:

amount} where amount is the amount of the fractional composition.

Return type:

Decomposition as a dict of {PDEntry

get_element_profile()[source]

Not Implemented - See PhaseDiagram.

get_equilibrium_reaction_energy(entry: Entry) float[source]

See PhaseDiagram.

NOTE this is only approximately the same as the what we would get from PhaseDiagram as we make use of the slsqp approach inside get_phase_separation_energy().

Parameters:

entry (PDEntry) – A PDEntry like object

Returns:

Equilibrium reaction energy of entry. Stable entries should have equilibrium reaction energy <= 0. The energy is given per atom.

get_pd_for_entry(entry: Entry | Composition) PhaseDiagram[source]

Get the possible phase diagrams for an entry.

Parameters:

entry (PDEntry | Composition) – A PDEntry or Composition-like object

Returns:

phase diagram that the entry is part of

Return type:

PhaseDiagram

Raises:

ValueError – If no suitable PhaseDiagram is found for the entry.

get_transition_chempots()[source]

Not Implemented - See PhaseDiagram.

getmu_vertices_stability_phase()[source]

Not Implemented - See PhaseDiagram.

static remove_redundant_spaces(spaces: set[frozenset[Element]], keep_all_spaces: bool = False) set[frozenset[Element]][source]
update(new_entries: Sequence[Entry] | set[Entry], verbose: bool = False, *, return_info: Literal[False] = False, on_new_el_ref: Literal['raise', 'ignore', 'recalculate'] = 'raise') Self[source]
update(new_entries: Sequence[Entry] | set[Entry], verbose: bool = False, *, return_info: Literal[True] = False, on_new_el_ref: Literal['raise', 'ignore', 'recalculate'] = 'raise') tuple[Self, dict[str, Any]]

Return a new PatchedPhaseDiagram incorporating new_entries, rebuilding only the affected patches. For each affected patch the rebuild uses the current stable entries in that space plus the new entries, avoiding redundant recalculation of the full convex hull.

Entry objects are shared between the old and new instances so memory usage stays flat until the caller drops the old reference.

Intended usage pattern:

ppd, info = ppd.update(new_entries, return_info=True)
Parameters:
  • new_entries – new PDEntry-like objects to incorporate.

  • verbose – whether to show a progress bar during patch rebuilds.

  • return_info – if True return a (ppd, info_dict) tuple instead of just the new PatchedPhaseDiagram.

  • on_new_el_ref

    what to do when a new entry would displace an existing elemental reference (lower energy for an element). - "raise" (default): raise a ValueError. - "ignore": silently keep the old elemental reference and

    skip the new entry for el_ref purposes.

    • "recalculate": accept the new reference and rebuild all affected spaces using the full qhull_entries.

Returns:

PatchedPhaseDiagram (or tuple of PatchedPhaseDiagram and info dict when return_info is True). The info dict contains:

  • ”updated_spaces”: list of frozenset[Element] spaces that were rebuilt

  • ”new_spaces”: list of frozenset[Element] spaces that were newly created

  • ”new_stable_entries”: set of entries that are stable after the update

    but were not stable before

  • ”removed_stable_entries”: set of entries that were stable before

    the update but are no longer stable

class PhaseDiagram(entries: Collection[Entry], elements: Collection[Element] | None = None, *, computed_data: dict[str, Any] | None = None)[source]

Bases: MSONable

Simple phase diagram class taking in elements and entries as inputs. The algorithm is based on the work in the following papers:

      1. Ong, L. Wang, B. Kang, and G. Ceder, Li-Fe-P-O2 Phase Diagram from

    First Principles Calculations. Chem. Mater., 2008, 20(5), 1798-1807. doi:10.1021/cm702327g

      1. Ong, A. Jain, G. Hautier, B. Kang, G. Ceder, Thermal stabilities

    of delithiated olivine MPO4 (M=Fe, Mn) cathodes investigated using first principles calculations. Electrochem. Comm., 2010, 12(3), 427-430. doi:10.1016/j.elecom.2010.01.010

dim[source]

The dimensionality of the phase diagram.

Type:

int

elements[source]

Elements in the phase diagram.

el_refs[source]

List of elemental references for the phase diagrams. These are entries corresponding to the lowest energy element entries for simple compositional phase diagrams.

all_entries[source]

All entries provided for Phase Diagram construction. Note that this does not mean that all these entries are actually used in the phase diagram. For example, this includes the positive formation energy entries that are filtered out before Phase Diagram construction.

qhull_entries[source]

Actual entries used in convex hull. Excludes all positive formation energy entries.

qhull_data[source]

Data used in the convex hull operation. This is essentially a matrix of composition data and energy per atom values created from qhull_entries.

facets[source]

Facets of the phase diagram in the form of [[1,2,3],[4,5,6]…]. For a ternary, it is the indices (references to qhull_entries and qhull_data) for the vertices of the phase triangles. Similarly extended to higher D simplices for higher dimensions.

simplices[source]

The simplices of the phase diagram as a list of np.ndarray, i.e., the list of stable compositional coordinates in the phase diagram.

Parameters:
  • entries (list[PDEntry]) – A list of PDEntry-like objects having an energy, energy_per_atom and composition.

  • elements (list[Element]) – Optional list of elements in the phase diagram. If set to None, the elements are determined from the entries themselves and are sorted alphabetically. If specified, element ordering (e.g. for pd coordinates) is preserved.

  • computed_data (dict) – A dict containing pre-computed data. This allows PhaseDiagram object to be reconstituted without performing the expensive convex hull computation. The dict is the output from the PhaseDiagram._compute() method and is stored in PhaseDiagram.computed_data when generated for the first time.

property all_entries_hulldata: ndarray[source]

The ndarray used to construct the convex hull.

as_dict() dict[str, Any][source]

Get MSONable dict representation of PhaseDiagram.

property dim: int[source]

The dimensionality of the phase diagram.

formation_energy_tol: ClassVar[float] = 1e-11[source]
classmethod from_dict(dct: dict[str, Any]) Self[source]
Parameters:

dct (dict) – dictionary representation of PhaseDiagram.

Returns:

PhaseDiagram

get_all_chempots(comp: Composition) dict[str, dict[Element, float]][source]

Get chemical potentials at a given composition.

Parameters:

comp (Composition) – Composition

Returns:

Chemical potentials.

get_chempot_range_map(elements: Sequence[Element], referenced: bool = True, joggle: bool = True) dict[Element, list[Simplex]][source]

Get a chemical potential range map for each stable entry.

Parameters:
  • elements – Sequence of elements to be considered as independent variables. e.g. if you want to show the stability ranges of all Li-Co-O phases with respect to mu_Li and mu_O, you will supply [Element(“Li”), Element(“O”)]

  • referenced – If True, gives the results with a reference being the energy of the elemental phase. If False, gives absolute values.

  • joggle (bool) – Whether to joggle the input to avoid precision errors.

Returns:

[simplices]}. The list of simplices are the sides of the N-1 dim polytope bounding the allowable chemical potential range of each entry.

Return type:

Returns a dict of the form {entry

get_chempot_range_stability_phase(target_comp: Composition, open_elt: Element) dict[Element, tuple[float, float]][source]

Get a set of chemical potentials corresponding to the max and min chemical potential of the open element for a given composition. It is quite common to have for instance a ternary oxide (e.g., ABO3) for which you want to know what are the A and B chemical potential leading to the highest and lowest oxygen chemical potential (reducing and oxidizing conditions). This is useful for defect computations.

Parameters:
  • target_comp – A Composition object

  • open_elt – Element that you want to constrain to be max or min

Returns:

A dictionary of the form {Element: (min_mu, max_mu)} where min_mu and max_mu are the minimum and maximum chemical potentials for the given element (as “absolute” values, i.e. not referenced to 0).

Return type:

dict[Element, (float, float)]

get_composition_chempots(comp: Composition) dict[Element, float][source]

Get the chemical potentials for all elements at a given composition.

Parameters:

comp (Composition) – Composition

Returns:

Dictionary of chemical potentials.

get_critical_compositions(comp1: Composition, comp2: Composition) list[Composition][source]

Get the critical compositions along the tieline between two compositions. I.e. where the decomposition products change. The endpoints are also returned.

Parameters:
  • comp1 (Composition) – First composition to define the tieline

  • comp2 (Composition) – Second composition to define the tieline

Returns:

list of critical compositions. All are of

the form x * comp1 + (1-x) * comp2

Return type:

[(Composition)]

get_decomp_and_e_above_hull(entry: PDEntry, allow_negative: bool = False, check_stable: bool = True, on_error: Literal['raise', 'warn', 'ignore'] = 'raise') tuple[dict[PDEntry, float], float] | tuple[None, None][source]

Provides the decomposition and energy above convex hull for an entry. Due to caching, can be much faster if entries with the same composition are processed together.

Parameters:
  • entry (PDEntry) – A PDEntry like object

  • allow_negative (bool) – Whether to allow negative e_above_hulls. Used to calculate equilibrium reaction energies. Defaults to False.

  • check_stable (bool) – Whether to first check whether an entry is stable. In normal circumstances, this is the faster option since checking for stable entries is relatively fast. However, if you have a huge proportion of unstable entries, then this check can slow things down. You should then set this to False.

  • on_error ('raise' | 'warn' | 'ignore') – What to do if no valid decomposition was found. ‘raise’ will throw ValueError. ‘warn’ will print return (None, None). ‘ignore’ just returns (None, None). Defaults to ‘raise’.

Raises:

ValueError – If on_error is ‘raise’ and no valid decomposition exists in this phase diagram for given entry.

Returns:

The decomposition is provided

as a dict of {PDEntry: amount} where amount is the amount of the fractional composition. Stable entries should have energy above convex hull of 0. The energy is given per atom.

Return type:

tuple[decomp, energy_above_hull]

get_decomp_and_hull_energy_per_atom(comp: Composition) tuple[dict[PDEntry, float], float][source]
Parameters:

comp (Composition) – Input composition.

Returns:

Energy of lowest energy equilibrium at desired composition per atom

get_decomp_and_phase_separation_energy(entry: PDEntry, space_limit: int = 200, stable_only: bool = False, tols: Sequence[float] = (1e-08,), maxiter: int = 1000, **kwargs: Any) tuple[dict[PDEntry, float], float] | tuple[None, None][source]

Provides the combination of entries in the PhaseDiagram that gives the lowest formation enthalpy with the same composition as the given entry excluding entries with the same composition and the energy difference per atom between the given entry and the energy of the combination found.

For unstable entries that are not polymorphs of stable entries (or completely novel entries) this is simply the energy above (or below) the convex hull.

For entries with the same composition as one of the stable entries in the phase diagram setting stable_only to False (Default) allows for entries not previously on the convex hull to be considered in the combination. In this case the energy returned is what is referred to as the decomposition enthalpy in:

  1. Bartel, C., Trewartha, A., Wang, Q., Dunn, A., Jain, A., Ceder, G.,

    A critical examination of compound stability predictions from machine-learned formation energies, npj Computational Materials 6, 97 (2020)

For stable entries setting stable_only to True returns the same energy as get_equilibrium_reaction_energy. This function is based on a constrained optimization rather than recalculation of the convex hull making it algorithmically cheaper. However, if tol is too loose there is potential for this algorithm to converge to a different solution.

Parameters:
  • entry (PDEntry) – A PDEntry like object.

  • space_limit (int) – The maximum number of competing entries to consider before calculating a second convex hull to reducing the complexity of the optimization.

  • stable_only (bool) – Only use stable materials as competing entries.

  • tols (list[float]) – Tolerances for convergence of the SLSQP optimization when finding the equilibrium reaction. Tighter tolerances tested first.

  • maxiter (int) – The maximum number of iterations of the SLSQP optimizer when finding the equilibrium reaction.

  • **kwargs – Passed to get_decomp_and_e_above_hull.

Returns:

The decomposition is given as a dict of {PDEntry, amount}

for all entries in the decomp reaction where amount is the amount of the fractional composition. The phase separation energy is given per atom.

Return type:

tuple[decomp, energy]

get_decomposition(comp: Composition) dict[PDEntry, float][source]

Provides the decomposition at a particular composition.

Parameters:

comp (Composition) – A composition

Returns:

amount} where amount is the amount of the fractional composition.

Return type:

Decomposition as a dict of {PDEntry

get_e_above_hull(entry: PDEntry, **kwargs: Any) float | None[source]

Provides the energy above convex hull for an entry.

Parameters:
  • entry (PDEntry) – A PDEntry like object.

  • **kwargs – Passed to get_decomp_and_e_above_hull().

Returns:

Energy above convex hull of entry. Stable entries should have

energy above hull of 0. The energy is given per atom.

Return type:

float | None

get_element_profile(element: Element, comp: Composition, comp_tol: float = 1e-05) list[dict[str, Any]][source]

Provides the element evolution data for a composition. For example, can be used to analyze Li conversion voltages by varying mu_Li and looking at the phases formed. Also can be used to analyze O2 evolution by varying mu_O2.

Parameters:
  • element – An element. Must be in the phase diagram.

  • comp – A Composition

  • comp_tol – The tolerance to use when calculating decompositions. Phases with amounts less than this tolerance are excluded. Defaults to 1e-5.

Returns:

[ {‘chempot’: -10.487582, ‘evolution’: -2.0, ‘reaction’: Reaction Object], …]

Return type:

Evolution data as a list of dictionaries of the following format

get_equilibrium_reaction_energy(entry: PDEntry) float | None[source]

Provides the reaction energy of a stable entry from the neighboring equilibrium stable entries (also known as the inverse distance to hull).

Parameters:

entry (PDEntry) – A PDEntry like object

Returns:

Equilibrium reaction energy of entry. Stable entries should have

equilibrium reaction energy <= 0. The energy is given per atom.

Return type:

float | None

get_form_energy(entry: PDEntry) float[source]

Get the formation energy for an entry (NOT normalized) from the elemental references.

Parameters:

entry (PDEntry) – A PDEntry-like object.

Returns:

Formation energy from the elemental references.

Return type:

float

get_form_energy_per_atom(entry: PDEntry) float[source]

Get the formation energy per atom for an entry from the elemental references.

Parameters:

entry (PDEntry) – An PDEntry-like object

Returns:

Formation energy per atom from the elemental references.

get_hull_energy(comp: Composition) float[source]
Parameters:

comp (Composition) – Input composition.

Returns:

Energy of lowest energy equilibrium at desired composition. Not

normalized by atoms, i.e. E(Li4O2) = 2 * E(Li2O)

get_hull_energy_per_atom(comp: Composition, **kwargs) float[source]
Parameters:

comp (Composition) – Input composition.

Returns:

Energy of lowest energy equilibrium at desired composition.

get_phase_separation_energy(entry: PDEntry, **kwargs)[source]

Provides the energy to the convex hull for the given entry. For stable entries already in the phase diagram the algorithm provides the phase separation energy which is referred to as the decomposition enthalpy in:

  1. Bartel, C., Trewartha, A., Wang, Q., Dunn, A., Jain, A., Ceder, G.,

    A critical examination of compound stability predictions from machine-learned formation energies, npj Computational Materials 6, 97 (2020)

Parameters:
  • entry (PDEntry) – A PDEntry like object

  • **kwargs

    Keyword args passed to get_decomp_and_phase_separation_energy space_limit (int): The maximum number of competing entries to consider. stable_only (bool): Only use stable materials as competing entries tol (float): The tolerance for convergence of the SLSQP optimization

    when finding the equilibrium reaction.

    maxiter (int): The maximum number of iterations of the SLSQP optimizer

    when finding the equilibrium reaction.

Returns:

phase separation energy per atom of entry. Stable entries should have energies <= 0, Stable elemental entries should have energies = 0 and unstable entries should have energies > 0. Entries that have the same composition as a stable energy may have positive or negative phase separation energies depending on their own energy.

get_plot(show_unstable: float = 0.2, backend: Literal['plotly', 'matplotlib'] = 'plotly', ternary_style: Literal['2d', '3d'] = '2d', label_stable: bool = True, label_unstable: bool = True, ordering: Sequence[Literal['Up', 'Left', 'Right']] | None = None, energy_colormap: str | Colormap | None = None, process_attributes: bool = False, ax: plt.Axes | None = None, label_uncertainties: bool = False, fill: bool = True, **kwargs) go.Figure | plt.Axes[source]

Convenient wrapper for PDPlotter. Initializes a PDPlotter object and calls get_plot() with provided combined arguments.

Plotting is only supported for phase diagrams with <=4 elements (unary, binary, ternary, or quaternary systems).

Parameters:
  • show_unstable (float) – Whether unstable (above the hull) phases will be plotted. If a number > 0 is entered, all phases with e_hull < show_unstable (eV/atom) will be shown.

  • backend ("plotly" | "matplotlib") – Python package to use for plotting. Defaults to “plotly”.

  • ternary_style ("2d" | "3d") – Ternary phase diagrams are typically plotted in two-dimensions (2d), but can be plotted in three dimensions (3d) to visualize the depth of the hull. This argument only applies when backend=”plotly”. Defaults to “2d”.

  • label_stable – Whether to label stable compounds.

  • label_unstable – Whether to label unstable compounds.

  • ordering – Ordering of vertices (matplotlib backend only).

  • energy_colormap – Colormap for coloring energy (matplotlib backend only).

  • process_attributes – Whether to process the attributes (matplotlib backend only).

  • ax – Existing Axes object if plotting multiple phase diagrams (matplotlib backend only).

  • label_uncertainties – Whether to add error bars to the hull (plotly backend only). For binaries, this also shades the hull with the uncertainty window.

  • fill – Whether to shade the hull. For ternary_2d and quaternary plots, this colors facets arbitrarily for visual clarity. For ternary_3d plots, this shades the hull by formation energy (plotly backend only).

  • **kwargs (dict) – Keyword args passed to PDPlotter.get_plot(). Can be used to customize markers etc. If not set, the default is { “markerfacecolor”: “#4daf4a”, “markersize”: 10, “linewidth”: 3 }

get_reference_energy(comp: Composition) float[source]

Sum of elemental reference energies over all elements in a composition.

Parameters:

comp (Composition) – Input composition.

Returns:

Reference energy

Return type:

float

get_reference_energy_per_atom(comp: Composition) float[source]

Sum of elemental reference energies over all elements in a composition.

Parameters:

comp (Composition) – Input composition.

Returns:

Reference energy per atom

Return type:

float

get_transition_chempots(element: Element) tuple[float, ...][source]

Get the critical chemical potentials for an element in the Phase Diagram.

Parameters:

element – An element. Has to be in the PD in the first place.

Returns:

A sorted sequence of critical chemical potentials, from less negative to more negative.

getmu_vertices_stability_phase(target_comp: Composition, dep_elt: Element, tol_en: float = 0.01) list[dict[Element, float]] | None[source]

Get a set of chemical potentials corresponding to the vertices of the simplex in the chemical potential phase diagram. The simplex is built using all elements in the target_composition except dep_elt. The chemical potential of dep_elt is computed from the target composition energy. This method is useful to get the limiting conditions for defects computations for instance.

Parameters:
  • target_comp – A Composition object

  • dep_elt – the element for which the chemical potential is computed from the energy of the stable phase at the target composition

  • tol_en – a tolerance on the energy to set

Returns:

mu}]: An array of conditions on simplex vertices for which each element has a chemical potential set to a given value. “absolute” values (i.e., not referenced to element energies)

Return type:

[{Element

numerical_tol: ClassVar[float] = 1e-08[source]
pd_coords(comp: Composition) ndarray[source]

The phase diagram is generated in a reduced dimensional space (n_elements - 1). This function returns the coordinates in that space. These coordinates are compatible with the stored simplex objects.

Parameters:

comp (Composition) – A composition

Returns:

The coordinates for a given composition in the PhaseDiagram’s basis

property stable_entries: set[Entry][source]

Returns: set[Entry]: of stable entries in the phase diagram.

property unstable_entries: set[Entry][source]

Returns: set[Entry]: unstable entries in the phase diagram. Includes positive formation energy entries.

exception PhaseDiagramError[source]

Bases: Exception

An exception class for Phase Diagram generation.

class ReactionDiagram(entry1: ComputedEntry, entry2: ComputedEntry, all_entries: list[ComputedEntry], tol: float = 0.0001, float_fmt: str = '%.4f')[source]

Bases: object

Analyzes the possible reactions between a pair of compounds, e.g. an electrolyte and an electrode.

Parameters:
  • entry1 (ComputedEntry) – Entry for 1st component. Note that corrections, if any, must already be pre-applied. This is to give flexibility for different kinds of corrections, e.g. if a particular entry is fitted to an experimental data (such as EC molecule).

  • entry2 (ComputedEntry) – Entry for 2nd component. Note that corrections must already be pre-applied. This is to give flexibility for different kinds of corrections, e.g. if a particular entry is fitted to an experimental data (such as EC molecule).

  • all_entries ([ComputedEntry]) – All other entries to be considered in the analysis. Note that corrections, if any, must already be pre-applied.

  • tol (float) – Tolerance to be used to determine validity of reaction. Defaults to 1e-4.

  • float_fmt (str) – Formatting string to be applied to all floats. Determines number of decimal places in reaction string. Defaults to “%.4f”.

get_compound_pd() CompoundPhaseDiagram[source]

Get the CompoundPhaseDiagram object, which can then be used for plotting.

Returns:

CompoundPhaseDiagram

class TransformedPDEntry(entry, sp_mapping, name=None)[source]

Bases: PDEntry

This class represents a TransformedPDEntry, which allows for a PDEntry to be transformed to a different composition coordinate space. It is used in the construction of phase diagrams that do not have elements as the terminal compositions.

Parameters:
  • entry (PDEntry) – Original entry to be transformed.

  • ({Composition (sp_mapping) – DummySpecies}): dictionary mapping Terminal Compositions to Dummy Species.

  • name (str | None) – Optional name for the entry. Defaults to the name of the original entry.

amount_tol: ClassVar[float] = 1e-05[source]
as_dict()[source]

Get MSONable dict representation of TransformedPDEntry.

property composition: Composition[source]

The composition in the dummy species space.

Returns:

Composition

classmethod from_dict(dct: dict) Self[source]
Parameters:

dct (dict) – dictionary representation of TransformedPDEntry.

Returns:

TransformedPDEntry

exception TransformedPDEntryError[source]

Bases: Exception

An exception class for TransformedPDEntry.

get_facets(qhull_data: ArrayLike, joggle: bool = False) ConvexHull[source]

Get the simplex facets for the Convex hull.

Parameters:
  • qhull_data (np.ndarray) – The data from which to construct the convex hull as a Nxd array (N being number of data points and d being the dimension)

  • joggle (bool) – Whether to joggle the input to avoid precision errors.

Returns:

with list of simplices of the convex hull.

Return type:

scipy.spatial.ConvexHull

order_phase_diagram(lines: list, stable_entries: dict[Any, PDEntry], unstable_entries: dict[PDEntry, Any], ordering: Sequence[Literal['Up', 'Left', 'Right']]) tuple[list, dict[Any, PDEntry], dict[PDEntry, Any]][source]

Orders the entries (their coordinates) in a phase diagram plot according to the user specified ordering. Ordering should be given as [‘Up’, ‘Left’, ‘Right’], where Up, Left and Right are the names of the entries in the upper, left and right corners of the triangle respectively.

Parameters:
  • lines – list of list of coordinates for lines in the PD.

  • stable_entries – {coordinate : entry} for each stable node in the phase diagram. (Each coordinate can only have one stable phase)

  • unstable_entries – {entry: coordinates} for all unstable nodes in the phase diagram.

  • ordering – Ordering of the phase diagram, given as a list [‘Up’, ‘Left’,’Right’]

Returns:

  • a list of list of coordinates for lines in the PD.

  • a {coordinate: entry} for each stable node

in the phase diagram. (Each coordinate can only have one stable phase) - a {entry: coordinates} for all unstable nodes in the phase diagram.

Return type:

tuple[list, dict, dict]

tet_coord(coord: ArrayLike) np.ndarray[source]

Convert a 3D coordinate into a tetrahedron based coordinate system for a prettier phase diagram.

Parameters:

coord – coordinate used in the convex hull computation.

Returns:

coordinates in a tetrahedron-based coordinate system.

triangular_coord(coord: ArrayLike) np.ndarray[source]

Convert a 2D coordinate into a triangle-based coordinate system for a prettier phase diagram.

Parameters:

coord – coordinate used in the convex hull computation.

Returns:

coordinates in a triangular-based coordinate system.

uniquelines(q: list[NDArray[int]]) set[tuple[int, int]][source]

Given all the facets, convert it into a set of unique lines. Specifically used for converting convex hull facets into line pairs of coordinates.

Parameters:

q – A 2-dim sequence, where each row represents a facet. e.g. [[1, 2, 3], [3, 6, 7], …]

Returns:

A set of tuple of lines. e.g. ((1, 2), (1, 3), …)

Return type:

setoflines

pymatgen.analysis.reaction_calculator module

This module provides classes that define a chemical reaction.

class BalancedReaction(reactants_coeffs: Mapping[CompositionLike, float], products_coeffs: Mapping[CompositionLike, float])[source]

Bases: MSONable

Represent a complete chemical reaction.

Reactants and products to be specified as dict of {Composition: coeff}.

Parameters:
  • reactants_coeffs (dict[Composition, float]) – Reactants as dict of {Composition: amt}.

  • products_coeffs (dict[Composition, float]) – Products as dict of {Composition: amt}.

TOLERANCE: float = 1e-06[source]
property all_comp: list[Composition][source]

List of all compositions in the reaction.

as_dict() dict[source]
Returns:

A dictionary representation of BalancedReaction.

as_entry(energies) ComputedEntry[source]

Get a ComputedEntry representation of the reaction.

calculate_energy(energies: dict[Composition, ufloat]) AffineScalarFunc[source]
calculate_energy(energies: dict[Composition, float]) float

Calculates the energy of the reaction.

Parameters:

({Composition (energies) – float}): Energy for each composition. E.g ., {comp1: energy1, comp2: energy2}.

Returns:

reaction energy as a float.

property coeffs: list[float][source]

Final coefficients of the calculated reaction.

property elements: list[Element | Species][source]

List of elements in the reaction.

classmethod from_dict(dct: dict) Self[source]
Parameters:

dct (dict) – from as_dict().

Returns:

BalancedReaction

classmethod from_str(rxn_str: str) Self[source]

Generate a balanced reaction from a string. The reaction must already be balanced.

Parameters:

rxn_string (str) – The reaction string. For example, “4 Li + O2 -> 2Li2O”

Returns:

BalancedReaction

get_coeff(comp: Composition) float[source]

Get coefficient for a particular composition.

get_el_amount(element: Element | Species) float[source]

Get the amount of the element in the reaction.

Parameters:

element (SpeciesLike) – Element in the reaction

Returns:

Amount of that element in the reaction.

normalize_to(comp: Composition, factor: float = 1) None[source]

Normalizes the reaction to one of the compositions. By default, normalizes such that the composition given has a coefficient of 1. Another factor can be specified.

Parameters:
  • comp (Composition) – Composition to normalize to

  • factor (float) – Factor to normalize to. Defaults to 1.

normalize_to_element(element: Species | Element, factor: float = 1) None[source]

Normalizes the reaction to one of the elements. By default, normalizes such that the amount of the element is 1. Another factor can be specified.

Parameters:
  • element (SpeciesLike) – Element to normalize to.

  • factor (float) – Factor to normalize to. Defaults to 1.

property normalized_repr: str[source]

A normalized representation of the reaction. All factors are converted to lowest common factors.

normalized_repr_and_factor() tuple[str, float][source]

Normalized representation for a reaction For example, 4 Li + 2 O -> 2Li2O becomes 2 Li + O -> Li2O.

property products: list[Composition][source]

List of products.

property reactants: list[Composition][source]

List of reactants.

class ComputedReaction(reactant_entries: list[ComputedEntry], product_entries: list[ComputedEntry])[source]

Bases: Reaction

Convenience class to generate a reaction from ComputedEntry objects, with some additional attributes, such as a reaction energy based on computed energies.

Parameters:
property all_entries[source]

Equivalent of all_comp but returns entries, in the same order as the coefficients.

as_dict() dict[source]
Returns:

A dictionary representation of ComputedReaction.

property calculated_reaction_energy: float[source]

Returns: float: The calculated reaction energy.

property calculated_reaction_energy_uncertainty: float[source]

Calculates the uncertainty in the reaction energy based on the uncertainty in the energies of the products and reactants.

classmethod from_dict(dct: dict) Self[source]
Parameters:

dct (dict) – from as_dict().

Returns:

A ComputedReaction object.

class Reaction(reactants: list[Composition], products: list[Composition])[source]

Bases: BalancedReaction

A more flexible class representing a Reaction. The reaction amounts will be automatically balanced. Reactants and products can swap sides so that all coefficients are positive, however this class will find the solution with the minimum number of swaps and coefficients of 0. Normalizes so that the FIRST product (or products, if underdetermined) has a coefficient of one.

Reactants and products to be specified as list of pymatgen.core.structure.Composition. e.g. [comp1, comp2].

Parameters:
as_dict() dict[source]
Returns:

A dictionary representation of Reaction.

copy() Self[source]

Get a copy of the Reaction object.

classmethod from_dict(dct: dict) Self[source]
Parameters:

dct (dict) – from as_dict().

Returns:

Reaction

exception ReactionError(msg: str)[source]

Bases: Exception

Exception class for Reactions. Allows more information in exception messages to cover situations not covered by standard exception classes.

Create a ReactionError.

Parameters:

msg (str) – More information about the ReactionError.