pymatgen.analysis.phase_diagram module¶
This module defines tools to generate and analyze phase diagrams.

class
BasePhaseDiagram
(facets, simplexes, all_entries, qhull_data, dim, el_refs, elements, qhull_entries)[source]¶ Bases:
monty.json.MSONable
BasePhaseDiagram is not intended to be used directly, and PhaseDiagram should be preferred.
When constructing a PhaseDiagram, a lot of heavy processing is performed to calculate the phase diagram information such as facets, simplexes, etc. The BasePhaseDiagram offers a way to store this information so that a phase diagram can be reconstructed without doing this heavy processing. It is primarily intended for database applications.
This class uses casting to bypass the init, so this constructor should only be called by as_dict and from_dict functions. Prefer the PhaseDiagram class for typical use cases.

property
all_entries_hulldata
[source]¶ The actual ndarray used to construct the convex hull.
 Type
return

classmethod
from_entries
(entries, elements=None)[source]¶ Construct the PhaseDiagram object and recast it as a BasePhaseDiagram
 Parameters
entries ([PDEntry]) – A list of PDEntrylike objects having an energy, energy_per_atom and composition.
elements ([Element]) – Optional list of elements in the phase diagram. If set to None, the elements are determined from the the entries themselves and are sorted alphabetically. If specified, element ordering (e.g. for pd coordinates) is preserved.

get_all_chempots
(comp)[source]¶ Get chemical potentials at a given compositon.
 Parameters
comp – Composition
 Returns
Chemical potentials.

get_chempot_range_map
(elements, referenced=True, joggle=True)[source]¶ Returns 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 LiCoO phases wrt 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.
joggle (boolean) – Whether to joggle the input to avoid precision errors.
 Returns
[simplices]}. The list of simplices are the sides of the N1 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, open_elt)[source]¶ returns 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
(mu_min,mu_max)}: Chemical potentials are given in “absolute” values (i.e., not referenced to 0)
 Return type
{Element

get_composition_chempots
(comp)[source]¶ Get the chemical potentials for all elements at a given composition.
 Parameters
comp – Composition
 Returns
Dict of chemical potentials.

get_critical_compositions
(comp1, comp2)[source]¶ Get the critical compositions along the tieline between two compositions. I.e. where the decomposition products change. The endpoints are also returned. :param comp1, comp2: compositions that define the tieline :type comp1, comp2: Composition
 Returns
 list of critical compositions. All are of
the form x * comp1 + (1x) * comp2
 Return type
[(Composition)]

get_decomp_and_e_above_hull
(entry, allow_negative=False)[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.
 Returns
 (decomp, energy_above_hull). 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.

get_decomp_and_phase_separation_energy
(entry, space_limit=200, stable_only=False, tol=1e10, maxiter=1000)[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:
 Bartel, C., Trewartha, A., Wang, Q., Dunn, A., Jain, A., Ceder, G.,
A critical examination of compound stability predictions from machinelearned 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 optimisation 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.
tol (float) – The tolerence 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
(decomp, energy). The decompostion 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.

get_decomposition
(comp)[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, **kwargs)[source]¶ Provides the energy above convex hull for an entry
 Parameters
entry (PDEntry) – A PDEntry like object
 Returns
Energy above convex hull of entry. Stable entries should have energy above hull of 0. The energy is given per atom.

get_element_profile
(element, comp, comp_tol=1e05)[source]¶ Provides the element evolution data for a composition. For example, can be used to analyze Li conversion voltages by varying uLi and looking at the phases formed. Also can be used to analyze O2 evolution by varying uO2.
 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 1e5.
 Returns
[ {‘chempot’: 10.487582010000001, ‘evolution’: 2.0, ‘reaction’: Reaction Object], …]
 Return type
Evolution data as a list of dictionaries of the following format

get_equilibrium_reaction_energy
(entry)[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.

get_form_energy
(entry)[source]¶ Returns the formation energy for an entry (NOT normalized) from the elemental references.
 Parameters
entry (PDEntry) – A PDEntrylike object.
 Returns
Formation energy from the elemental references.

get_form_energy_per_atom
(entry)[source]¶ Returns the formation energy per atom for an entry from the elemental references.
 Parameters
entry (PDEntry) – An PDEntrylike object
 Returns
Formation energy per atom from the elemental references.

get_hull_energy
(comp)[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_phase_separation_energy
(entry, **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 refered to as the decomposition enthalpy in:
 Bartel, C., Trewartha, A., Wang, Q., Dunn, A., Jain, A., Ceder, G.,
A critical examination of compound stability predictions from machinelearned formation energies, npj Computational Materials 6, 97 (2020)
 Parameters
entry (PDEntry) – A PDEntry like object
**kwargs –
Keyword args passed to get_decomp_and_decomp_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 tolerence 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 postive or negative phase separation energies depending on their own energy.

get_transition_chempots
(element)[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, dep_elt, tol_en=0.01)[source]¶ returns 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

pd_coords
(comp)[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

class
CompoundPhaseDiagram
(entries, terminal_compositions, normalize_terminal_compositions=True)[source]¶ Bases:
pymatgen.analysis.phase_diagram.PhaseDiagram
Generates phase diagrams from compounds as terminations instead of elements.
Initializes a CompoundPhaseDiagram.
 Parameters
entries ([PDEntry]) – Sequence of input entries. For example, if you want a Li2OP2O5 phase diagram, you might have all LiPO entries as an input.
terminal_compositions ([Composition]) – Terminal compositions of phase space. In the Li2OP2O5 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. Nonnormalized terminals are more intuitive in terms of compositional breakdowns.

transform_entries
(entries, terminal_compositions)[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.
 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, chempots, name=None)[source]¶ Bases:
pymatgen.analysis.phase_diagram.PDEntry
A grand potential pd entry object encompassing all relevant data for phase diagrams. Chemical potentials are given as a elementchemical potential dict.
 Parameters
entry – A PDEntrylike 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.

class
GrandPotentialPhaseDiagram
(entries, chempots, elements=None)[source]¶ Bases:
pymatgen.analysis.phase_diagram.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:
S. P. Ong, L. Wang, B. Kang, and G. Ceder, LiFePO2 Phase Diagram from First Principles Calculations. Chem. Mater., 2008, 20(5), 17981807. doi:10.1021/cm702327g
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), 427430. doi:10.1016/j.elecom.2010.01.010
Standard constructor for grand potential phase diagram.
 Parameters
entries ([PDEntry]) – A list of PDEntrylike objects having an energy, energy_per_atom and composition.
({Element (chempots) – float}): Specify the chemical potentials of the open elements.
elements ([Element]) – Optional list of elements in the phase diagram. If set to None, the elements are determined from the the entries themselves.

class
PDEntry
(composition: pymatgen.core.composition.Composition, energy: float, name: str = None, attribute: object = None)[source]¶ Bases:
pymatgen.entries.Entry
An object encompassing all relevant data for phase diagrams.

name
: str[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.

attribute
: MSONable[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.
 Parameters
composition (Composition) – 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.


class
PDPlotter
(phasediagram: pymatgen.analysis.phase_diagram.PhaseDiagram, show_unstable: float = 0.2, backend: str = 'plotly', **plotkwargs)[source]¶ Bases:
object
A plotter class for compositional phase diagrams.
 Parameters
phasediagram (PhaseDiagram) – PhaseDiagram object.
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 (str) – Python package used for plotting (“matplotlib” or “plotly”). Defaults to “plotly”.
**plotkwargs (dict) –
Keyword args passed to matplotlib.pyplot.plot. Can be used to customize markers etc. If not set, the default is {
”markerfacecolor”: (0.2157, 0.4941, 0.7216), “markersize”: 10, “linewidth”: 3
}

get_chempot_range_map_plot
(elements, referenced=True)[source]¶ Returns a plot of the chemical potential range _map. Currently works only for 3component PDs.
 Parameters
elements – Sequence of elements to be considered as independent variables. E.g., if you want to show the stability ranges of all LiCoO phases wrt 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
A matplotlib plot object.

get_contour_pd_plot
()[source]¶ Plot a contour phase diagram plot, where phase triangles are colored according to degree of instability by interpolation. Currently only works for 3component phase diagrams.
 Returns
A matplotlib plot object.

get_plot
(label_stable=True, label_unstable=True, ordering=None, energy_colormap=None, process_attributes=False, plt=None, label_uncertainties=False)[source]¶  Parameters
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).
plt – Existing plt 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.
 Returns
go.Figure (plotly) or matplotlib.pyplot (matplotlib)

property
pd_plot_data
[source]¶ Plotting data for phase diagram. Cached for repetitive calls. 2comp  Full hull with energies 3/4comp  Projection into 2D or 3D Gibbs triangle.
 Returns
lines is a list of list of coordinates for lines in the PD.
 stable_entries is a dict of {coordinatesentry} for each stable node
in the phase diagram. (Each coordinate can only have one stable phase)
 unstable_entries is a dict of {entry: coordinates} for all unstable
nodes in the phase diagram.
 Return type
(lines, stable_entries, unstable_entries)

plot_chempot_range_map
(elements, referenced=True)[source]¶ Plot the chemical potential range _map. Currently works only for 3component PDs.
 Parameters
elements – Sequence of elements to be considered as independent variables. E.g., if you want to show the stability ranges of all LiCoO phases wrt 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, comp, show_label_index=None, xlim=5)[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)[source]¶ Draw the phase diagram using Plotly (or Matplotlib) and show it.
 Parameters
*args – Passed to get_plot.
**kwargs – Passed to get_plot.

write_image
(stream, image_format='svg', **kwargs)[source]¶ Writes the phase diagram to an image in a stream.
 Parameters
stream – stream to write to. Can be a file stream or a StringIO stream.
image_format – format for image. Can be any of matplotlib supported formats. Defaults to svg for best results for vector graphics.
**kwargs – Pass through to get_plot functino.

class
PhaseDiagram
(entries, elements=None)[source]¶ Bases:
pymatgen.analysis.phase_diagram.BasePhaseDiagram
Simple phase diagram class taking in elements and entries as inputs. The algorithm is based on the work in the following papers:
S. P. Ong, L. Wang, B. Kang, and G. Ceder, LiFePO2 Phase Diagram from First Principles Calculations. Chem. Mater., 2008, 20(5), 17981807. doi:10.1021/cm702327g
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), 427430. doi:10.1016/j.elecom.2010.01.010
..attribute: all_entries
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.
Standard constructor for phase diagram.
 Parameters
entries ([PDEntry]) – A list of PDEntrylike objects having an energy, energy_per_atom and composition.
elements ([Element]) – Optional list of elements in the phase diagram. If set to None, the elements are determined from the the entries themselves and are sorted alphabetically. If specified, element ordering (e.g. for pd coordinates) is preserved.

exception
PhaseDiagramError
[source]¶ Bases:
Exception
An exception class for Phase Diagram generation.

class
ReactionDiagram
(entry1, entry2, all_entries, tol=0.0001, float_fmt='%.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 preapplied. 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 preapplied. 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 preapplied.
tol (float) – Tolerance to be used to determine validity of reaction.
float_fmt (str) – Formatting string to be applied to all floats. Determines number of decimal places in reaction string.

class
TransformedPDEntry
(entry, sp_mapping, name=None)[source]¶ Bases:
pymatgen.analysis.phase_diagram.PDEntry
This class repesents 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

exception
TransformedPDEntryError
[source]¶ Bases:
Exception
An exception class for TransformedPDEntry.

get_facets
(qhull_data, joggle=False)[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 (boolean) – Whether to joggle the input to avoid precision errors.
 Returns
List of simplices of the Convex Hull.

order_phase_diagram
(lines, stable_entries, unstable_entries, ordering)[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
newlines is a list of list of coordinates for lines in the PD.
newstable_entries is a {coordinate : entry} for each stable node
in the phase diagram. (Each coordinate can only have one stable phase)  newunstable_entries is a {entry: coordinates} for all unstable nodes in the phase diagram.
 Return type
(newlines, newstable_entries, newunstable_entries)

tet_coord
(coord)[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 tetrahedronbased coordinate system.

triangular_coord
(coord)[source]¶ Convert a 2D coordinate into a trianglebased coordinate system for a prettier phase diagram.
 Parameters
coord – coordinate used in the convex hull computation.
 Returns
coordinates in a triangularbased coordinate system.

uniquelines
(q)[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 2dim 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), (2,3), ….)
 Return type
setoflines