pymatgen.analysis.pourbaix_diagram module

class IonEntry(ion, energy, name=None)[source]

Bases: pymatgen.analysis.phase_diagram.PDEntry

Object similar to PDEntry, but contains an Ion object instead of a Composition object.

  • comp – Ion object

  • energy – Energy for composition.

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


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.


Creates a dict of composition, energy, and ion name

classmethod from_dict(d)[source]

Returns an IonEntry object from a dict.

MU_H2O = -2.4583
class MultiEntry(entry_list, weights=None)[source]

Bases: pymatgen.analysis.pourbaix_diagram.PourbaixEntry

PourbaixEntry-like object for constructing multi-elemental Pourbaix diagrams.

Initializes a MultiEntry.

  • entry_list ([PourbaixEntry]) – List of component PourbaixEntries

  • weights ([float]) – Weights associated with each entry. Default is None


Returns dict which contains Pourbaix Entry data. Note that the pH, voltage, H2O factors are always calculated when constructing a PourbaixEntry object.

classmethod from_dict(d)[source]


property name

Multientry name, i. e. the name of each entry joined by ‘ + ‘

PREFAC = 0.0591
class PourbaixDiagram(entries, comp_dict=None, conc_dict=None, filter_solids=False, nproc=None)[source]

Bases: monty.json.MSONable

Class to create a Pourbaix diagram from entries

  • entries ([PourbaixEntry] or [MultiEntry]) – Entries list containing Solids and Ions or a list of MultiEntries

  • ({str (conc_dict) – float}): Dictionary of compositions, defaults to equal parts of each elements

  • ({str – float}): Dictionary of ion concentrations, defaults to 1e-6 for each element

  • filter_solids (bool) – applying this filter to a pourbaix diagram ensures all included phases are filtered by stability on the compositional phase diagram. This breaks some of the functionality of the analysis, though, so use with caution.

  • nproc (int) – number of processes to generate multientries with in parallel. Defaults to None (serial processing)

property all_entries

Return all entries used to generate the pourbaix diagram


A JSON serializable dict representation of an object.

find_stable_entry(pH, V)[source]

Finds stable entry at a pH,V condition :param pH: pH to find stable entry :type pH: float :param V: V to find stable entry :type V: float


classmethod from_dict(d)[source]
get_decomposition_energy(entry, pH, V)[source]

Finds decomposition to most stable entry

  • entry (PourbaixEntry) – PourbaixEntry corresponding to compound to find the decomposition for

  • pH (float) – pH at which to find the decomposition

  • V (float) – voltage at which to find the decomposition


reaction corresponding to the decomposition

get_hull_energy(pH, V)[source]
static get_pourbaix_domains(pourbaix_entries, limits=None)[source]

Returns a set of pourbaix stable domains (i. e. polygons) in pH-V space from a list of pourbaix_entries

This function works by using scipy’s HalfspaceIntersection function to construct all of the 2-D polygons that form the boundaries of the planes corresponding to individual entry gibbs free energies as a function of pH and V. Hyperplanes of the form a*pH + b*V + 1 - g(0, 0) are constructed and supplied to HalfspaceIntersection, which then finds the boundaries of each pourbaix region using the intersection points.

  • pourbaix_entries ([PourbaixEntry]) – Pourbaix entries with which to construct stable pourbaix domains

  • limits ([[float]]) – limits in which to do the pourbaix analysis


[boundary_points]}. The list of boundary points are the sides of the N-1 dim polytope bounding the allowable ph-V range of each entry.

Return type

Returns a dict of the form {entry

static process_multientry(entry_list, prod_comp, coeff_threshold=0.0001)[source]

Static method for finding a multientry based on a list of entries and a product composition. Essentially checks to see if a valid aqueous reaction exists between the entries and the product composition and returns a MultiEntry with weights according to the coefficients if so.

  • entry_list ([Entry]) – list of entries from which to create a MultiEntry

  • prod_comp (Composition) – composition constraint for setting weights of MultiEntry

  • coeff_threshold (float) – threshold of stoichiometric coefficients to filter, if weights are lower than this value, the entry is not returned

property stable_entries

Returns the stable entries in the Pourbaix diagram.

property unprocessed_entries

Return unprocessed entries

property unstable_entries

Returns all unstable entries in the Pourbaix diagram

class PourbaixEntry(entry, entry_id=None, concentration=1e-06)[source]

Bases: monty.json.MSONable

An object encompassing all data relevant to a solid or ion in a pourbaix diagram. Each bulk solid/ion has an energy g of the form: e = e0 + 0.0591 log10(conc) - nO mu_H2O + (nH - 2nO) pH + phi (-nH + 2nO + q)

Note that the energies corresponding to the input entries should be formation energies with respect to hydrogen and oxygen gas in order for the pourbaix diagram formalism to work. This may be changed to be more flexible in the future.


entry (ComputedEntry/ComputedStructureEntry/PDEntry/IonEntry) – An entry object


Returns dict which contains Pourbaix Entry data. Note that the pH, voltage, H2O factors are always calculated when constructing a PourbaixEntry object.

property composition

Returns composition

property conc_term

Returns the concentration contribution to the free energy, and should only be present when there are ions in the entry

property energy

returns energy

Returns (float): total energy of the pourbaix

entry (at pH, V = 0 vs. SHE)

energy_at_conditions(pH, V)[source]

Get free energy for a given pH and V

  • pH (float) – pH at which to evaluate free energy

  • V (float) – voltage at which to evaluate free energy


free energy at conditions

property energy_per_atom

energy per atom of the pourbaix entry

Returns (float): energy per atom

classmethod from_dict(d)[source]


property nH2O
property nPhi
property name
property normalization_factor

Sum of number of atoms minus the number of H and O in composition

property normalized_energy

energy normalized by number of non H or O atoms, e. g. for Zn2O6, energy / 2 or for AgTe3(OH)3, energy / 4

normalized_energy_at_conditions(pH, V)[source]

Energy at an electrochemical condition, compatible with numpy arrays for pH/V input

  • pH (float) – pH at condition

  • V (float) – applied potential at condition


energy normalized by number of non-O/H atoms at condition

property npH
property num_atoms

Return number of atoms in current formula. Useful for normalization

class PourbaixPlotter(pourbaix_diagram)[source]

Bases: object

A plotter class for phase diagrams.

  • phasediagram – A PhaseDiagram object.

  • show_unstable – Whether unstable phases will be plotted as well as red crosses. Defaults to False.


Returns the vertices of the Pourbaix domain.


entry – Entry for which domain vertices are desired


list of vertices

get_pourbaix_plot(limits=None, title='', label_domains=True, plt=None)[source]

Plot Pourbaix diagram.

  • limits – 2D list containing limits of the Pourbaix diagram of the form [[xlo, xhi], [ylo, yhi]]

  • title (str) – Title to display on plot

  • label_domains (bool) – whether to label pourbaix domains

  • plt (pyplot) – Pyplot instance for plotting


plt (pyplot) - matplotlib plot object with pourbaix diagram

plot_entry_stability(entry, pH_range=None, pH_resolution=100, V_range=None, V_resolution=100, e_hull_max=1, cmap='RdYlBu_r', **kwargs)[source]
show(*args, **kwargs)[source]

Shows the pourbaix plot

  • *args – args to get_pourbaix_plot

  • **kwargs – kwargs to get_pourbaix_plot



elements_HO = {Element H, Element O}

Generates a label for the pourbaix plotter


entry (PourbaixEntry or MultiEntry) – entry to get a label for


Returns either an ion object or composition object given a formula.


formula – String formula. Eg. of ion: NaOH(aq), Na[+]; Eg. of solid: Fe2O3(s), Fe(s), Na2O


Composition/Ion object

logger = <Logger pymatgen.analysis.pourbaix_diagram (WARNING)>
class tqdm(iterable=None, desc=None, total=None, leave=True, file=None, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000, write_bytes=None, gui=False, **kwargs)[source]

Bases: tqdm._utils.Comparable

Decorate an iterable object, returning an iterator which acts exactly like the original iterable, but prints a dynamically updating progressbar every time a value is requested.

  • iterable (iterable, optional) – Iterable to decorate with a progressbar. Leave blank to manually manage the updates.

  • desc (str, optional) – Prefix for the progressbar.

  • total (int, optional) – The number of expected iterations. If unspecified, len(iterable) is used if possible. If float(“inf”) or as a last resort, only basic progress statistics are displayed (no ETA, no progressbar). If gui is True and this parameter needs subsequent updating, specify an initial arbitrary large positive integer, e.g. int(9e9).

  • leave (bool, optional) – If [default: True], keeps all traces of the progressbar upon termination of iteration.

  • file (io.TextIOWrapper or io.StringIO, optional) – Specifies where to output the progress messages (default: sys.stderr). Uses file.write(str) and file.flush() methods. For encoding, see write_bytes.

  • ncols (int, optional) – The width of the entire output message. If specified, dynamically resizes the progressbar to stay within this bound. If unspecified, attempts to use environment width. The fallback is a meter width of 10 and no limit for the counter and statistics. If 0, will not print any meter (only stats).

  • mininterval (float, optional) – Minimum progress display update interval [default: 0.1] seconds.

  • maxinterval (float, optional) – Maximum progress display update interval [default: 10] seconds. Automatically adjusts miniters to correspond to mininterval after long display update lag. Only works if dynamic_miniters or monitor thread is enabled.

  • miniters (int, optional) – Minimum progress display update interval, in iterations. If 0 and dynamic_miniters, will automatically adjust to equal mininterval (more CPU efficient, good for tight loops). If > 0, will skip display of specified number of iterations. Tweak this and mininterval to get very efficient loops. If your progress is erratic with both fast and slow iterations (network, skipping items, etc) you should set miniters=1.

  • ascii (bool or str, optional) – If unspecified or False, use unicode (smooth blocks) to fill the meter. The fallback is to use ASCII characters ” 123456789#”.

  • disable (bool, optional) – Whether to disable the entire progressbar wrapper [default: False]. If set to None, disable on non-TTY.

  • unit (str, optional) – String that will be used to define the unit of each iteration [default: it].

  • unit_scale (bool or int or float, optional) – If 1 or True, the number of iterations will be reduced/scaled automatically and a metric prefix following the International System of Units standard will be added (kilo, mega, etc.) [default: False]. If any other non-zero number, will scale total and n.

  • dynamic_ncols (bool, optional) – If set, constantly alters ncols to the environment (allowing for window resizes) [default: False].

  • smoothing (float, optional) – Exponential moving average smoothing factor for speed estimates (ignored in GUI mode). Ranges from 0 (average speed) to 1 (current/instantaneous speed) [default: 0.3].

  • bar_format (str, optional) –

    Specify a custom bar string formatting. May impact performance. [default: ‘{l_bar}{bar}{r_bar}’], where l_bar=’{desc}: {percentage:3.0f}%|’ and r_bar=’| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ‘


    Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,

    percentage, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, elapsed, elapsed_s, remaining, remaining_s, desc, postfix, unit.

    Note that a trailing “: ” is automatically removed after {desc} if the latter is empty.

  • initial (int, optional) – The initial counter value. Useful when restarting a progress bar [default: 0].

  • position (int, optional) – Specify the line offset to print this bar (starting from 0) Automatic if unspecified. Useful to manage multiple bars at once (eg, from threads).

  • postfix (dict or *, optional) – Specify additional stats to display at the end of the bar. Calls set_postfix(**postfix) if possible (dict).

  • unit_divisor (float, optional) – [default: 1000], ignored unless unit_scale is True.

  • write_bytes (bool, optional) – If (default: None) and file is unspecified, bytes will be written in Python 2. If True will also write bytes. In all other cases will default to unicode.

  • gui (bool, optional) – WARNING: internal parameter - do not use. Use tqdm_gui(…) instead. If set, will attempt to use matplotlib animations for a graphical output [default: False].



Return type

decorated iterator.


Clear current bar display.


Cleanup and (if leave=False) close the progressbar.

display(msg=None, pos=None)[source]

Use self.sp to display msg in the specified pos.

Consider overloading this function when inheriting to use e.g.: self.some_frontend(**self.format_dict) instead of self.sp.

  • msg (str, optional. What to display (default: repr(self)).) –

  • pos (int, optional. Position to moveto) – (default: abs(self.pos)).

static ema(x, mu=None, alpha=0.3)[source]

Exponential moving average: smoothing to give progressively lower weights to older values.

  • x (float) – New value to include in EMA.

  • mu (float, optional) – Previous EMA value.

  • alpha (float, optional) – Smoothing factor in range [0, 1], [default: 0.3]. Increase to give more weight to recent values. Ranges from 0 (yields mu) to 1 (yields x).

classmethod external_write_mode(file=None, nolock=False)[source]

Disable tqdm within context and refresh tqdm when exits. Useful when writing to standard output stream

property format_dict

Public API for read-only member access.

static format_interval(t)[source]

Formats a number of seconds as a clock time, [H:]MM:SS


t (int) – Number of seconds.


out – [H:]MM:SS

Return type


static format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000, **extra_kwargs)[source]

Return a string-based progress bar given some parameters

  • n (int) – Number of finished iterations.

  • total (int) – The expected total number of iterations. If meaningless (), only basic progress statistics are displayed (no ETA).

  • elapsed (float) – Number of seconds passed since start.

  • ncols (int, optional) – The width of the entire output message. If specified, dynamically resizes the progress meter to stay within this bound [default: None]. The fallback meter width is 10 for the progress bar + no limit for the iterations counter and statistics. If 0, will not print any meter (only stats).

  • prefix (str, optional) – Prefix message (included in total width) [default: ‘’]. Use as {desc} in bar_format string.

  • ascii (bool, optional or str, optional) – If not set, use unicode (smooth blocks) to fill the meter [default: False]. The fallback is to use ASCII characters ” 123456789#”.

  • unit (str, optional) – The iteration unit [default: ‘it’].

  • unit_scale (bool or int or float, optional) – If 1 or True, the number of iterations will be printed with an appropriate SI metric prefix (k = 10^3, M = 10^6, etc.) [default: False]. If any other non-zero number, will scale total and n.

  • rate (float, optional) – Manual override for iteration rate. If [default: None], uses n/elapsed.

  • bar_format (str, optional) –

    Specify a custom bar string formatting. May impact performance. [default: ‘{l_bar}{bar}{r_bar}’], where l_bar=’{desc}: {percentage:3.0f}%|’ and r_bar=’| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ‘


    Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,

    percentage, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, elapsed, elapsed_s, remaining, remaining_s, desc, postfix, unit.

    Note that a trailing “: ” is automatically removed after {desc} if the latter is empty.

  • postfix (*, optional) – Similar to prefix, but placed at the end (e.g. for additional stats). Note: postfix is usually a string (not a dict) for this method, and will if possible be set to postfix = ‘, ‘ + postfix. However other types are supported (#382).

  • unit_divisor (float, optional) – [default: 1000], ignored unless unit_scale is True.



Return type

Formatted meter and stats, ready to display.

static format_num(n)[source]

Intelligent scientific notation (.3g).


n (int or float or Numeric) – A Number.


out – Formatted number.

Return type


static format_sizeof(num, suffix='', divisor=1000)[source]

Formats a number (greater than unity) with SI Order of Magnitude prefixes.

  • num (float) – Number ( >= 1) to format.

  • suffix (str, optional) – Post-postfix [default: ‘’].

  • divisor (float, optionl) – Divisor between prefixes [default: 1000].


out – Number with Order of Magnitude SI unit postfix.

Return type


classmethod get_lock()[source]

Get the global lock. Construct it if it does not exist.

monitor = None
monitor_interval = 10
classmethod pandas(*targs, **tkwargs)[source]
Registers the given tqdm class with

pandas.core. ( frame.DataFrame | series.Series | groupby.DataFrameGroupBy | groupby.SeriesGroupBy ).progress_apply

A new instance will be create every time progress_apply is called, and each instance will automatically close() upon completion.


tkwargs (targs,) –


>>> import pandas as pd
>>> import numpy as np
>>> from tqdm import tqdm, tqdm_gui
>>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
>>> tqdm.pandas(ncols=50)  # can use tqdm_gui, optional kwargs, etc
>>> # Now you can use `progress_apply` instead of `apply`
>>> df.groupby(0).progress_apply(lambda x: x**2)

References progress-indicator-during-pandas-operations-python


Force refresh the display of this bar.


Resets to 0 iterations for repeated use.

Consider combining with leave=True.


total (int, optional. Total to use for the new bar.) –

set_description(desc=None, refresh=True)[source]

Set/modify description of the progress bar.

  • desc (str, optional) –

  • refresh (bool, optional) – Forces refresh [default: True].

set_description_str(desc=None, refresh=True)[source]

Set/modify description without ‘: ‘ appended.

classmethod set_lock(lock)[source]

Set the global lock.

set_postfix(ordered_dict=None, refresh=True, **kwargs)[source]

Set/modify postfix (additional stats) with automatic formatting based on datatype.

  • ordered_dict (dict or OrderedDict, optional) –

  • refresh (bool, optional) – Forces refresh [default: True].

  • kwargs (dict, optional) –

set_postfix_str(s='', refresh=True)[source]

Postfix without dictionary expansion, similar to prefix handling.

static status_printer(file)[source]

Manage the printing and in-place updating of a line of characters. Note that if the string is longer than a line, then in-place updating may not work (it will print a new line at each refresh).


Restart tqdm timer from last print time.


Manually update the progress bar, useful for streams such as reading files. E.g.: >>> t = tqdm(total=filesize) # Initialise >>> for current_buffer in stream: … … … t.update(len(current_buffer)) >>> t.close() The last line is highly recommended, but possibly not necessary if t.update() will be called in such a way that filesize will be exactly reached and printed.


n (int, optional) – Increment to add to the internal counter of iterations [default: 1].

classmethod write(s, file=None, end='\n', nolock=False)[source]

Print a message via tqdm (without overlap with bars).