rxn_network.reactions#

rxn_network.reactions.base#

Basic interface for a (chemical) Reaction.

class rxn_network.reactions.base.Reaction[source]#

Bases: MSONable

Base definition for a reaction class.

abstract property reactants: list[Composition]#

List of reactants for this reaction.

abstract property products: list[Composition]#

List of products for this reaction.

abstract property coefficients: ndarray#

Coefficients of the reaction.

abstract property energy: float#

The energy of this reaction in total eV.

abstract property compositions: list[Composition]#

List of all compositions in the reaction.

property elements: list[Element]#

List of elements in the reaction.

rxn_network.reactions.basic#

This module for defining chemical reaction objects was originally sourced from pymatgen and streamlined for the reaction-network code.

class rxn_network.reactions.basic.BasicReaction(compositions, coefficients, balanced=None, data=None, lowest_num_errors=0)[source]#

Bases: Reaction

An object representing a basic chemical reaction: compositions and their coefficients.

A BasicReaction object is defined by a list of compositions and their corresponding coefficients, where a negative coefficient refers to a reactant, and a positive coefficient refers to a product.

Parameters:
  • compositions (Iterable[Composition]) – List of composition objects (pymatgen).

  • coefficients (Iterable[float] | np.ndarray) – List of coefficients, where negative coeff distinguishes a reactant.

  • balanced (bool | None) – Whether the reaction is stoichiometricaly balanced or not (see construction via balance() method).

  • data (dict | None) – Optional corresponding data in dictionary format; often used to store various calculated parameters.

  • lowest_num_errors (float) – the minimum number of errors reported by the reaction balancing algorithm (see the balance() method). A number of errors >= 1 means that the reaction may be different than intended (some phases may be shuffled or removed entirely).

classmethod balance(reactants, products, data=None)[source]#

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

Parameters:
  • reactants (list[Composition]) – List of reactants.

  • products (list[Composition]) – List of products.

  • data (dict | None) – Optional dictionary containing extra data about the reaction.

Return type:

BasicReaction

normalize_to(comp, factor=1)[source]#

Normalizes the reaction to one of the compositions via the provided factor.

By default, normalizes such that the composition given has a coefficient of 1.

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

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

Return type:

BasicReaction

normalize_to_element(element, factor=1)[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 (Element/Species) – Element to normalize to.

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

Return type:

BasicReaction

get_el_amount(element)[source]#

Returns the amount of the element in the reaction.

Parameters:

element (Element/Species) – Element in the reaction

Returns:

Amount of that element in the reaction.

Return type:

float

get_coeff(comp)[source]#

Returns coefficient for a particular composition.

Parameters:

comp (Composition) –

normalized_repr_and_factor()[source]#

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

copy()[source]#

Returns a copy of the BasicReaction object.

Return type:

BasicReaction

reverse()[source]#

Returns a copy of the original BasicReaction object where original reactants are new products, and vice versa.

Return type:

BasicReaction

is_separable(target)[source]#

Checks if the reaction forms byproducts which are separable from the target composition.

Separable byproducts are those that are common gases (e.g., CO2), or other phases that do not contain any of the elements in the target phase.

Parameters:

target (str | Composition) – Composition of target; elements in this phase will be used to determine whether byproducts only contain added elements.

Returns:

True if reaction is separable from target, False otherwise.

Return type:

bool

property reactant_atomic_fractions: dict#

Returns the atomic mixing ratio of reactants in the reaction.

property product_atomic_fractions: dict#

Returns the atomic mixing ratio of reactants in the reaction.

property reactant_molar_fractions: dict#

Returns the molar mixing ratio of reactants in the reaction.

property product_molar_fractions: dict#

Returns the molar mixing ratio of products in the reaction.

classmethod from_string(rxn_string)[source]#

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

Parameters:

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

Returns:

BalancedReaction

Return type:

BasicReaction

classmethod from_formulas(reactants, products)[source]#

Initialize a reaction from a list of 1) reactant formulas and 2) product formulas.

Parameters:
  • reactants (list[str]) – List of reactant formulas

  • products (list[str]) – List of product formulas

Returns:

A BasicReaction object

Return type:

BasicReaction

property reactants: list[Composition]#

List of reactants for this reaction.

property products: list[Composition]#

List of products for this reaction.

property compositions: list[Composition]#

List of composition objects for this reaction.

property coefficients: ndarray#

Array of reaction coefficients.

property num_atoms: float#

Total number of atoms in this reaction.

property energy: float#

The energy of this reaction.

property energy_per_atom: float#

The energy per atom of this reaction.

property is_identity: bool#

Returns True if the reaction has identical reactants and products.

property chemical_system: str#

Returns the chemical system as string in the form of A-B-C-…

property normalized_repr: str#

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

rxn_network.reactions.computed#

A reaction class that builds reactions based on ComputedEntry objects and provides information about reaction thermodynamics.

class rxn_network.reactions.computed.ComputedReaction(entries, coefficients, data=None, lowest_num_errors=0)[source]#

Bases: BasicReaction

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

Parameters:
  • entries (list[ComputedEntry]) – List of ComputedEntry objects.

  • coefficients (np.ndarray | list[float]) – List or array of reaction coefficients.

  • data (dict | None) – Optional dict of data

  • lowest_num_errors (int) – number of “errors” encountered during reaction balancing.

classmethod balance(reactant_entries, product_entries, data=None)[source]#

Balances and returns a new ComputedReaction.

Reactants and products to be specified as a collection (list, set, etc.) of ComputedEntry objects.

Parameters:
  • reactant_entries (list[ComputedEntry]) – List of reactant entries

  • product_entries (list[ComputedEntry]) – List of product entries

  • data (dict | None) – Optional dict of data

Return type:

ComputedReaction

get_new_temperature(new_temperature)[source]#

Returns a new reaction with the temperature changed.

Parameters:

new_temperature (float) – New temperature in Kelvin

Return type:

ComputedReaction

property energy: float#

Returns (float): The calculated reaction energy.

property energy_per_atom: float#

Returns (float): The calculated reaction energy in eV, divided by the total number of atoms in the reaction. Cached for speedup.

property energy_uncertainty: float#

Calculates the uncertainty in the reaction energy based on the uncertainty in the energies of the reactants/products. Cached for speedup.

property energy_uncertainty_per_atom: float#

Returns the energy_uncertainty divided by the total number of atoms in the reaction.

property entries: list[ComputedEntry]#

Returns a copy of the entries.

copy()[source]#

Returns a copy of the Reaction object.

Return type:

ComputedReaction

reverse()[source]#

Returns a reversed reaction (i.e. sides flipped).

Return type:

ComputedReaction

normalize_to(comp, factor=1)[source]#

Normalizes the reaction to one of the compositions via the provided factor.

By default, normalizes such that the composition given has a coefficient of 1.

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

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

Return type:

ComputedReaction

normalize_to_element(element, factor=1)[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 (Element/Species) – Element to normalize to.

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

Return type:

ComputedReaction

get_entry_idx_vector(n)[source]#

Maps coefficients to a vector of length n on corresponding entry indices.

Parameters:

n (int) – Total number of entries (determines length of vector)

Returns:

Vector containing reaction coefficients on the corresponding entry indices.

Return type:

ndarray

rxn_network.reactions.hull#

Code for analyzing sets of reactions between two phases.

class rxn_network.reactions.hull.InterfaceReactionHull(c1, c2, reactions)[source]#

Bases: MSONable

A class for storing and analyzing a set of reactions at an interface between two reactants. This class is more generalized than the InterfacialReactivity class and can encompass any set of reactions between two reactants, regardless of whether the reaction products are “stable” (i.e. together on the convex hull).

Parameters:
  • c1 (Composition) – Composition of reactant 1

  • c2 (Composition) – Composition of reactant 2

  • reactions (list[ComputedReaction]) – List of reactions containing all enumerated reactions between the two reactants. Note that this list should not include identity reactions of the precursors.

plot(y_max=0.2)[source]#

Plot the reaction hull.

Parameters:

y_max (float) –

Return type:

Figure

get_energy_above_hull(reaction)[source]#

Get the energy of a reaction above the reaction hull.

Parameters:

reaction (ComputedReaction) –

Return type:

float

get_coordinate(reaction)[source]#

Get coordinate of reaction in reaction hull. This is expressed as the atomic mixing ratio of component 2 in the reaction.

Parameters:

reaction (ComputedReaction) –

Return type:

float

get_hull_energy(coordinate)[source]#

Get the energy of the reaction at a given coordinate.

Parameters:

coordinate (float) – Coordinate of reaction in reaction hull.

Returns:

Energy of reaction at given coordinate.

Return type:

float

get_reactions_by_coordinate(coordinate)[source]#

Get the reaction(s) at a given coordinate.

Parameters:

coordinate (float) –

Return type:

dict[ComputedReaction, float]

get_primary_competition(reaction)[source]#

Calculates the primary competition, C_1, for a reaction (in eV/atom).

If you use this selectivity metric in your work, please cite the following work:

McDermott, M. J.; McBride, B. C.; Regier, C.; Tran, G. T.; Chen, Y.; Corrao, A. A.; Gallant, M. C.; Kamm, G. E.; Bartel, C. J.; Chapman, K. W.; Khalifah, P. G.; Ceder, G.; Neilson, J. R.; Persson, K. A. Assessing Thermodynamic Selectivity of Solid-State Reactions for the Predictive Synthesis of Inorganic Materials. arXiv August 22, 2023. https://doi.org/10.48550/arXiv.2308.11816.

Parameters:

reaction (ComputedReaction) – A computed reaction.

Returns:

The primary competition (C1 score) in eV/atom.

Return type:

float

get_secondary_competition(reaction, normalize=True, include_e_hull=False, recursive=False)[source]#

Calculates the secondary competition, C_2, for a reaction (in eV/atom).

If you use this selectivity metric in your work, please cite the following work:

McDermott, M. J.; McBride, B. C.; Regier, C.; Tran, G. T.; Chen, Y.; Corrao, A. A.; Gallant, M. C.; Kamm, G. E.; Bartel, C. J.; Chapman, K. W.; Khalifah, P. G.; Ceder, G.; Neilson, J. R.; Persson, K. A. Assessing Thermodynamic Selectivity of Solid-State Reactions for the Predictive Synthesis of Inorganic Materials. arXiv August 22, 2023. https://doi.org/10.48550/arXiv.2308.11816.

Parameters:
  • reaction (ComputedReaction) – A computed reaction.

  • normalize (bool) – Whether or not to normalize the sum of secondary reaction sequence energies by the total number of sequnces. Defaults to True according to original definition.

  • include_e_hull (bool) – Whether or not to include the energy above hull of the target reaction in the definition of C_2. According to the original paper, this defaults to False.

  • recursive (bool) – Whether or not to perform the secondary reaction analysis via a recursive approach. This should return the same answer, but much slower. This argument exists for debugging / validation and defaults to False.

Returns:

The secondary competition (C2 score) in eV/atom.

Return type:

float

get_secondary_competition_max_energy(reaction)[source]#

Calculates the score for a given reaction.

Parameters:

reaction (ComputedReaction) – Reaction to calculate the competition score for.

Returns:

The competition score for the reaction

Return type:

float

get_secondary_competition_area(reaction)[source]#

Calculates the score for a given reaction. This formula is based on a methodology presented in the following paper: (TBD).

Parameters:

reaction (ComputedReaction) – Reaction to calculate the competition score for.

Returns:

The competition score for the reaction

Return type:

float

get_decomposition_energy(x1, x2)[source]#

Calculates the energy of the reaction decomposition between two points.

Parameters:
  • x1 (float) – Coordinate of first point.

  • x2 (float) – Coordinate of second point.

Returns:

The energy of the reaction decomposition between the two points.

Return type:

float

get_max_decomposition_energy(x1, x2)[source]#

Similar to get_decomposition_energy, but returns only the decomposition energy that is maximum (rather than the sum of all possible decompositions).

Parameters:
  • x1 (float) – Coordinate of first point.

  • x2 (float) – Coordinate of second point.

Returns:

The maximum energy of the reaction decomposition between the two points.

Return type:

float

get_decomposition_area(x1, x2)[source]#

Similar to get_decomposition_energy, but returns the area enclosed instead of an energy.

WARNING: This may be numerically unstable.

Parameters:
  • x1 (float) – Coordinate of first point.

  • x2 (float) – Coordinate of second point.

Returns:

The area of reaction decomposition between the two points.

Return type:

float

get_coords_in_range(x1, x2)[source]#

Get the coordinates in the range [x1, x2].

Parameters:
  • x1 (float) – Start of range.

  • x2 (float) – End of range.

Returns:

Array of coordinates in the range.

count(num)[source]#

Reurns the number of decomposition pathways for the interface reaction hull based on the number of product vertices (i.e., total # of vertices considered - 2 reactant vertices).

Precomputed for hulls up to size 15. Otherwise, calls recursive implementation of counting function.

Parameters:

num (int) – Number of product vertices.

Return type:

int

get_decomposition_energy_and_num_paths_recursive(x1, x2, use_x_min_ref=True, use_x_max_ref=True)[source]#

This is a recursive implementation of the get_decomposition_energy function. It significantly slower than the non-recursive implementation but is more straightforward to understand. Both should return the same answer, however the refcursive implementation also includes “free” computation of the total number of paths. The function has been cached for speed.

Parameters:
  • x1 (float) – Coordinate of first point.

  • x2 (float) – Coordinate of second point.

  • use_x_min_ref (bool) – Useful for recursive calls. If true, uses the reactant at x=0 as the reference (sometimes there is a decomposition reaction of the reactant that is lower in energy than the reactant).

  • use_x_max_ref (bool) – Useful for recursive calls. If true, uses the reactant at x=1.0 as the reference (sometimes there is a decomposition reaction of the reactant that is lower in energy than the reactant).

Returns:

Tuple of decomposition energy and the number of decomposition pathways.

Return type:

tuple[float, int]

property hull_vertices: ndarray#

Returns numpy array of indices of the vertices that are on the hull.

property stable_reactions: list[ComputedReaction]#

Returns the reactions that are stable (on the convex hull) of the interface reaction hull.

property unstable_reactions#

Returns the reactions that are unstable (NOT on the convex hull) of the interface reaction hull.

rxn_network.reactions.open#

A reaction class that builds reactions based on ComputedEntry objects under the presence of an open entry (e.g. O2), and provides information about reaction thermodynamics computed as changes in grand potential.

class rxn_network.reactions.open.OpenComputedReaction(entries, coefficients, chempots, data=None, lowest_num_errors=0)[source]#

Bases: ComputedReaction

Extends the ComputedReaction class to add support for “open” reactions, where the reaction energy is calculated as a change in grand potential.

Parameters:
  • entries (list[ComputedEntry]) – List of ComputedEntry objects.

  • coefficients (np.ndarray | list[float]) – List of reaction coefficients.

  • chempots (dict[Element, float]) – Dict of chemical potentials corresponding to open elements.

  • data (dict | None) – Optional dict of data.

  • lowest_num_errors (int) – number of “errors” encountered during reaction balancing.

classmethod balance(reactant_entries, product_entries, chempots, data=None)[source]#

Balances and returns a new ComputedReaction.

Reactants and products to be specified as a collection (list, set, etc.) of ComputedEntry objects.

A dictionary of open elements and their corresponding chemical potentials must be supplied.

Parameters:
  • reactant_entries (list[ComputedEntry]) – List of reactant entries

  • product_entries (list[ComputedEntry]) – List of product entries

  • chempots (dict[Element, float]) – Dict of chemical potentials corresponding to open element(s)

  • data (dict | None) – Optional dict of data

Return type:

OpenComputedReaction

get_new_temperature(new_temperature)[source]#

Returns a new reaction with the temperature changed.

Parameters:

new_temperature (float) – New temperature in Kelvin

Return type:

OpenComputedReaction

property energy: float#

Returns (float): The calculated reaction energy.

property elements: list[Element]#

List of elements in the reaction.

property total_chemical_system: str#

Chemical system string, including open elements.

copy()[source]#

Returns a copy of the OpenComputedReaction object.

Return type:

OpenComputedReaction

reverse()[source]#

Returns a copy of reaction with reactants/products swapped.

property reactant_atomic_fractions: dict#

Returns the atomic mixing ratio of reactants in the reaction.

property product_atomic_fractions: dict#

Returns the atomic mixing ratio of reactants in the reaction.

classmethod from_computed_rxn(reaction, chempots)[source]#

Generate an OpenComputedReaction from a ComputedReaction object and chemical potential dict.

Parameters:
  • reaction (ComputedReaction) – ComputedReaction object

  • chempots (dict[Element, float]) – Dict of chemical potentials corresponding to open element(s)

Returns:

OpenComputedReaction object

Return type:

OpenComputedReaction

as_dict()[source]#

Returns a dictionary representation of the reaction.

Return type:

dict

classmethod from_dict(d)[source]#

Returns an OpenComputedReaction object from a dictionary representation.

Return type:

OpenComputedReaction

rxn_network.reactions.plotting#

Utility functions for plotting reaction data & performing analysis.

rxn_network.reactions.plotting.plot_reaction_scatter(df, x='secondary_competition', y='energy', z=None, color=None, plot_pareto=True)[source]#

Plot a Plotly scatter plot (2D or 3D) of reactions on various thermodynamic metric axes. This also constructs the Pareto front on the provided dimensions.

Parameters:
  • df (DataFrame) – DataFrame with columns: rxn, energy, (primary_competition), (secondary_competition), (chempot_distance), (added_elems), (dE)

  • x (str) – Column name to plot on x-axis

  • y (str) – Column name to plot on y-axis

  • z (str | None) – Column name to plot on z-axis

  • color (str | None) – Column name to color points by. Defaults to None.

  • plot_pareto (bool) – Whether to plot the Pareto front. Defaults to True.

Returns:

Plotly scatter plot

Return type:

px.scatter

rxn_network.reactions.plotting.pretty_df_layout(df)[source]#

Improve visibility for a pandas DataFrame with wide column names.

Parameters:

df (DataFrame) –

rxn_network.reactions.plotting.filter_df_by_precursors(df, precursors)[source]#

Filter a reaction DataFrame by available precursors.

Parameters:
  • df (DataFrame) –

  • precursors (list[str]) –

rxn_network.reactions.reaction_set#

Implements a class for conveniently and efficiently storing sets of ComputedReaction objects which share entries.

class rxn_network.reactions.reaction_set.ReactionSet(entries, indices, coeffs, open_elem=None, chempot=0.0, all_data=None)[source]#

Bases: MSONable

A lightweight class for storing large sets of ComputedReaction objects. Automatically represents a set of reactions as an array of coefficients with a second array linking to a corresponding list of shared entries. This is useful for dumping large amounts of reaction data to a database.

Note: this is not a true “set”; there is the option for filtering duplicates but it

is not explicitly required.

Parameters:
  • entries (list[ComputedEntry]) – List of ComputedEntry objects shared by reactions

  • indices (dict[int, np.ndarray]) – Array indexing the entry list; gets entries used by each reaction object

  • coeffs (dict[int, np.ndarray]) – Array of all reaction coefficients

  • open_elem (str | Element | None) – Open element, e.g., “O”

  • chempot (float) – Chemical potential (mu) of open element in equation: Phi = G - mu*N

  • all_data (dict[int, np.ndarray] | None) – Optional list of data for each reaction.

get_rxns()[source]#

Generator for all ComputedReaction objects or OpenComputedReaction objects (when open element and chempot are specified) for the reaction set.

Return type:

Iterable[ComputedReaction | OpenComputedReaction]

classmethod from_rxns(rxns, entries=None, open_elem=None, chempot=0.0, filter_duplicates=False)[source]#

Initiate a ReactionSet object from a list of reactions. Including a list of unique entries saves some computation time.

Parameters:
  • rxns (Collection[ComputedReaction | OpenComputedReaction]) – List of ComputedReaction-like objects.

  • entries (Collection[ComputedEntry] | None) – Optional list of ComputedEntry objects

  • open_elem (str | Element | None) – Open element, e.g. “O2”

  • chempot (float) – Chemical potential (mu) of open element in equation: Phi = G - mu*N

  • filter_duplicates (bool) – Whether to filter duplicate reactions. Defaults to False.

Return type:

ReactionSet

to_dataframe(cost_function, target=None, calculate_uncertainties=False, calculate_separable=False)[source]#

Make a dataframe of reactions from a ReactionSet object.

Parameters:
  • cost_function (CostFunction) – Cost function to use for evaluating reaction costs

  • target (Composition | None) – Optional target composition (used to determine added elements)

  • calculate_uncertainties (bool) – Whether to calculate uncertainties (dE column)

  • calculate_separable (bool) – Whether to calculate if the reaction products are separable (see ComputedReaction.is_separable)

Returns:

rxn: Reaction object energy: reaction energy in eV/atom dE (optional): uncertainty in reaction energy in eV/atom added_elems (optional): List of added elements separable (optional): whether reaction products are separable cost: Cost of reaction other: any other data associated with reaction

Return type:

Pandas DataFrame with columns

calculate_costs(cf)[source]#

Evaluate a cost function on an acquired set of reactions.

Parameters:

cf (CostFunction) – CostFunction object, e.g. Softplus()

Return type:

list[float]

add_rxns(rxns)[source]#

Return a new ReactionSet with the reactions added.

Warning: all new reactions must only have entires contained in the entries of the current reaction set.

Parameters:

rxns (Collection[ComputedReaction | OpenComputedReaction]) –

add_rxn_set(rxn_set)[source]#

Adds a new reaction set to current reaction set.

Warning: new reaction set must have the same entries as the current reaction set.

Parameters:

rxn_set (ReactionSet) –

Return type:

ReactionSet

get_rxns_by_reactants(reactants, return_set=False)[source]#

Return a list of reactions with the given reactants.

Parameters:
Return type:

Iterable[ComputedReaction | OpenComputedReaction]

get_rxns_by_product(product, return_set=False)[source]#

Return a list of reactions which contain the given product formula.

Parameters:
  • product (str) – The product’s formula

  • return_set (bool) – Whether to return the identified reactions in the form of a ReactionSet object. Defaults to False.

filter_duplicates(ensure_rxns=None, parallelize=True)[source]#

Returns a new ReactionSet object with duplicate reactions removed.

NOTE: Duplicate reactions include those that are multiples of each other. For example, if a reaction set contains both A + B -> C and 2A + 2B -> 2C, the second reaction will be removed.

Parameters:
  • ensure_rxns (list[ComputedReaction | OpenComputedReaction] | None) – An optional list of reactions to ensure are contained within the filtered set that is returned. This is important for some cases (e.g., pathfinding), where you expect a certain reaction object to be in the set.

  • parallelize (bool) – Whether to parallelize duplicate checking with Ray. This can be a slow procedure otherwise. Defaults to True.

Return type:

ReactionSet

set_chempot(open_el, chempot)[source]#

Returns a new ReactionSet containing the same reactions as this ReactionSet but with a grand potential change recalculated under the constraint defined by the provided open element and its chemical potential.

Parameters:
  • open_el (str | Element | None) – The element to be considered open.

  • chempot (float | None) – The open element’s chemical potential (for use in energy change calculation)

Returns:

A new ReactionSet containing reactions with the recalculated

energies.

Return type:

ReactionSet

set_new_temperature(new_temp)[source]#

Returns a new ReactionSet containing the same reactions as this ReactionSet but with a recalculated Gibb’s/Grand potential change reflecting formation energies calculated at the provided temperature.

Parameters:

new_temp (float) – The temperature for which new reaction energies should be calculated.

Returns:

The new ReactionSet containing the recalculated reactions.

Return type:

ReactionSet