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 compositions: list[Composition]#
List of all compositions 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:
- 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:
- 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:
- 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:
- 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
becomes2 Li + O -> Li2O
.
- reverse()[source]#
Returns a copy of the original BasicReaction object where original reactants are new products, and vice versa.
- Return type:
- 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:
- 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.
- 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:
- classmethod from_formulas(reactants, products)[source]#
Initialize a reaction from a list of 1) reactant formulas and 2) product formulas.
- Parameters:
- Returns:
A BasicReaction object
- Return type:
- 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.
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:
- 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:
- Return type:
- get_new_temperature(new_temperature)[source]#
Returns a new reaction with the temperature changed.
- Parameters:
new_temperature (float) – New temperature in Kelvin
- Return type:
- 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.
- 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:
- 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:
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.
- get_energy_above_hull(reaction)[source]#
Get the energy of a reaction above the reaction hull.
- Parameters:
reaction (ComputedReaction) –
- Return type:
- 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:
- get_reactions_by_coordinate(coordinate)[source]#
Get the reaction(s) at a given coordinate.
- Parameters:
coordinate (float) –
- Return type:
- 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:
- 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:
- 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:
- 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:
- get_decomposition_energy(x1, x2)[source]#
Calculates the energy of the reaction decomposition between two points.
- 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).
- 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.
- 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.
- 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:
- 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:
- Return type:
- get_new_temperature(new_temperature)[source]#
Returns a new reaction with the temperature changed.
- Parameters:
new_temperature (float) – New temperature in Kelvin
- Return type:
- 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:
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.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:
- 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:
- 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:
- 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.
- 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:
- 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:
- Returns:
- A new ReactionSet containing reactions with the recalculated
energies.
- Return type:
- 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: