pymatgen.core package

This package contains core modules and classes for representing structures and operations on them.

Submodules

pymatgen.core.bonds module

This module implements definitions for various kinds of bonds. Typically used in Molecule analysis.

class CovalentBond(site1: Site, site2: Site)[source]

Bases: object

A covalent bond between two sites.

Initialize a covalent bond between two sites.

Parameters:
  • site1 (Site) – First site.

  • site2 (Site) – Second site.

get_bond_order(tol: float = 0.2, default_bl: float | None = None) float[source]

The bond order according the distance between the two sites.

Parameters:
  • tol (float) – Relative tolerance to test. (1 + tol) * the longest bond distance is considered to be the threshold length for a bond to exist. (1 - tol) * the shortest bond distance is considered to be the shortest possible bond length Defaults to 0.2.

  • default_bl – If a particular type of bond does not exist, use this bond length as a default value (bond order = 1). If None, a ValueError will be thrown.

Returns:

value of bond order. E.g. 1.7 for C-C bond in benzene.

Return type:

float

static is_bonded(site1: Site, site2: Site, tol: float = 0.2, bond_order: float | None = None, default_bl: float | None = None) bool[source]

Check if two sites are bonded, up to a certain limit.

Parameters:
  • site1 (Site) – First site

  • site2 (Site) – Second site

  • tol (float) – Relative tolerance to test. Basically, the code checks if the distance between the sites is less than (1 + tol) * typical bond distances. Defaults to 0.2, i.e., 20% longer.

  • bond_order – Bond order to test. If None, the code simply checks against all possible bond data. Defaults to None.

  • default_bl – If a particular type of bond does not exist, use this bond length. If None, a ValueError will be thrown.

Returns:

True if two sites are bonded.

Return type:

bool

property length: float[source]

Length of the bond.

get_bond_length(sp1: SpeciesLike, sp2: SpeciesLike, bond_order: float = 1) float[source]

Get the bond length between two species.

Parameters:
  • sp1 (Species) – First specie.

  • sp2 (Species) – Second specie.

  • bond_order – For species with different possible bond orders, this allows one to obtain the bond length for a particular bond order. For example, to get the C=C bond length instead of the C-C bond length, this should be set to 2. Defaults to 1.

Returns:

Bond length in Angstrom. If no data is available,

the sum of the atomic radius is used.

Return type:

float

get_bond_order(sp1: SpeciesLike, sp2: SpeciesLike, dist: float, tol: float = 0.2, default_bl: float | None = None) float[source]

Calculate the bond order given the distance of 2 species.

Parameters:
  • sp1 (Species) – First specie.

  • sp2 (Species) – Second specie.

  • dist (float) – Distance in angstrom

  • tol (float) – Relative tolerance to test. Basically, the code checks if the distance between the sites is larger than (1 + tol) * the longest bond distance or smaller than (1 - tol) * the shortest bond distance to determine if they are bonded or the distance is too short. Defaults to 0.2.

  • default_bl – If a particular type of bond does not exist, use this bond length (bond order = 1). If None, a ValueError will be thrown.

Returns:

Bond order. For example, 1.7 for C-C bond in benzene.

Return type:

float

obtain_all_bond_lengths(sp1: SpeciesLike, sp2: SpeciesLike, default_bl: float | None = None) dict[float, float][source]

Obtain bond lengths for all bond orders from bond length database.

Parameters:
  • sp1 (Species) – First specie.

  • sp2 (Species) – Second specie.

  • default_bl – If a particular type of bond does not exist, use this bond length as a default value (bond order = 1). If None, a ValueError will be thrown.

Returns:

A dict mapping bond order to bond length in angstrom

pymatgen.core.composition module

This module implements a Composition class to represent compositions, and a ChemicalPotential class to represent potentials.

class ChemicalPotential(*args, **kwargs)[source]

Bases: dict, MSONable

Represent set of chemical potentials. Can be: multiplied/divided by a Number multiplied by a Composition (returns an energy) added/subtracted with other ChemicalPotentials.

Parameters:
  • *args – any valid dict init arguments

  • **kwargs – any valid dict init arguments.

get_energy(composition: Composition, strict: bool = True) float[source]

Calculate the energy of a composition.

Parameters:
  • composition (Composition) – input composition

  • strict (bool) – Whether all potentials must be specified

class Composition(*args, strict: bool = False, **kwargs)[source]

Bases: Hashable, Mapping, MSONable, Stringify

Represents a Composition, a mapping of {element/species: amount} with enhanced functionality tailored for handling chemical compositions. The class is immutable, hashable, and designed for robust usage in material science and chemistry computations.

Key Features:
  • Supports both Element and Species as keys, with differentiation

between oxidation states (e.g., Fe2+ and Fe3+ are distinct keys). - Behaves like a dictionary but returns 0 for missing keys, making it similar to a defaultdict while remaining immutable. - Provides numerous utility methods for chemical computations, such as calculating fractions, weights, and formula representations.

Highlights:
  • Input Flexibility: Accepts formulas as strings, dictionaries, or

keyword arguments for construction. - Convenience Methods: Includes get_fraction, reduced_formula, and weight-related utilities. - Enhanced Formula Representation: Supports reduced, normalized, and IUPAC-sorted formulas.

Examples

>>> comp = Composition("LiFePO4")
>>> comp.get_atomic_fraction(Element("Li"))
0.14285714285714285
>>> comp.num_atoms
7.0
>>> comp.reduced_formula
'LiFePO4'
>>> comp.formula
'Li1 Fe1 P1 O4'
>>> comp.get_wt_fraction(Element("Li"))
0.04399794666951898
>>> comp.num_atoms
7.0
- `amount_tolerance`

Tolerance for distinguishing composition

Type:

float

amounts. Default is 1e-8 to minimize floating-point errors.
- `charge_balanced_tolerance`

Tolerance for verifying charge balance.

Type:

float

- `special_formulas`

Custom formula mappings for specific compounds

Type:

dict

(e.g., `"LiO"` `"Li2O2"`).
- `oxi_prob`

Prior probabilities of oxidation states, used

Type:

dict or None

for oxidation state guessing.
Functionality:
  • Arithmetic Operations: Add, subtract, multiply, or divide compositions.

For example:
>>> comp1 = Composition("Fe2O3")
>>> comp2 = Composition("FeO")
>>> result = comp1 + comp2  # Produces "Fe3O4"
  • Representation:
    • formula: Full formula string with elements sorted by electronegativity.

    • reduced_formula: Simplified formula with minimal ratios.

    • hill_formula: Hill notation (C and H prioritized, others alphabetically sorted).

  • Utilities:
    • get_atomic_fraction: Returns the atomic fraction of a given element/species.

    • get_wt_fraction: Returns the weight fraction of a given element/species.

    • is_element: Checks if the composition is a pure element.

    • reduced_composition: Normalizes the composition by the greatest common denominator.

    • fractional_composition: Returns the normalized composition where sums equal 1.

  • Oxidation State Handling:
    • oxi_state_guesses: Suggests charge-balanced oxidation states.

    • charge_balanced: Checks if the composition is charge balanced.

    • add_charges_from_oxi_state_guesses: Assigns oxidation states based on guesses.

  • Validation:
    • valid: Ensures all elements/species are valid.

Notes

  • When constructing from strings, both Element and Species types are

handled. For example:
  • Composition(“Fe2+”) differentiates Fe2+ from Fe3+.

  • Composition(“Fe2O3”) auto-parses standard formulas.

Very flexible Composition construction, similar to the built-in Python dict(). Also extended to allow simple string init.

Takes any inputs supported by the Python built-in dict function.

  1. A dict of either {Element/Species: amount},

    {string symbol:amount}, or {atomic number:amount} or any mixture of these. e.g. {Element(“Li”): 2, Element(“O”): 1}, {“Li”:2, “O”:1}, {3: 2, 8: 1} all result in a Li2O composition.

  2. Keyword arg initialization, similar to a dict, e.g.

    Composition(Li = 2, O = 1)

In addition, the Composition constructor also allows a single string as an input formula. e.g. Composition(“Li2O”).

Parameters:
  • *args – Any number of 2-tuples as key-value pairs.

  • strict (bool) – Only allow valid Elements and Species in the Composition. Defaults to False.

  • allow_negative (bool) – Whether to allow negative compositions. Defaults to False.

  • **kwargs – Additional kwargs supported by the dict() constructor.

add_charges_from_oxi_state_guesses(oxi_states_override: dict | None = None, target_charge: float = 0, all_oxi_states: bool = False, max_sites: int | None = None) Self[source]

Assign oxidation states based on guessed oxidation states.

See oxi_state_guesses for an explanation of how oxidation states are guessed. This operation uses the set of oxidation states for each site that were determined to be most likely from the oxidation state guessing routine.

Parameters:
  • oxi_states_override (dict[str, list[float]]) – Override an element’s common oxidation states, e.g. {“V”: [2, 3, 4, 5]}

  • target_charge (float) – the desired total charge on the structure. Default is 0 signifying charge balance.

  • all_oxi_states (bool) – if True, all oxidation states of an element, even rare ones, are used in the search for guesses. However, the full oxidation state list is very inclusive and can produce nonsensical results. If False, the icsd_oxidation_states list is used when present, or the common_oxidation_states is used when icsd_oxidation_states is not present. These oxidation states lists comprise more commonly occurring oxidation states and results in more reliable guesses, albeit at the cost of missing some uncommon situations. The default is False.

  • max_sites (int) – If possible, will reduce Compositions to at most this many sites to speed up oxidation state guesses. If the composition cannot be reduced to this many sites a ValueError will be raised. Set to -1 to just reduce fully. If set to a number less than -1, the formula will be fully reduced but a ValueError will be thrown if the number of atoms in the reduced formula is greater than abs(max_sites).

Returns:

Composition, where the elements are assigned oxidation states based on the results form guessing oxidation states. If no oxidation state is possible, returns a Composition where all oxidation states are 0.

almost_equals(other: Composition, rtol: float = 0.1, atol: float = 1e-08) bool[source]

Get true if compositions are equal within a tolerance.

Parameters:
  • other (Composition) – Other composition to check

  • rtol (float) – Relative tolerance

  • atol (float) – Absolute tolerance

property alphabetical_formula: str[source]

A formula string, with elements sorted by alphabetically e.g. Fe4 Li4 O16 P4.

amount_tolerance = 1e-08[source]
property anonymized_formula: str[source]

An anonymized formula. Unique species are arranged in ordering of increasing amounts and assigned ascending alphabets. Useful for prototyping formulas. For example, all stoichiometric perovskites have anonymized_formula ABC3.

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

Subtly different from get_el_amt_dict in that they keys here are str(Element) instead of Element.symbol.

Returns:

element symbol and (unreduced) amount. E.g.

{“Fe”: 4.0, “O”: 6.0} or {“Fe3+”: 4.0, “O2-”: 6.0}

Return type:

dict[str, float]

property average_electroneg: float[source]

Average electronegativity of the composition.

property charge: float | None[source]

Total charge based on oxidation states. If any oxidation states are None or they’re all 0, returns None. Use add_charges_from_oxi_state_guesses to assign oxidation states to elements based on charge balancing.

property charge_balanced: bool | None[source]

True if composition is charge balanced, False otherwise. If any oxidation states are None, returns None. Use add_charges_from_oxi_state_guesses to assign oxidation states to elements.

charge_balanced_tolerance = 1e-08[source]
property chemical_system: str[source]

The chemical system of a Composition, for example “O-Si” for SiO2. Chemical system is a string of a list of elements sorted alphabetically and joined by dashes, by convention for use in database keys.

property chemical_system_set: set[str][source]

The set of elements in the Composition. E.g. {“O”, “Si”} for SiO2.

contains_element_type(category: str) bool[source]

Check if Composition contains any elements matching a given category.

Parameters:

category (str) – one of “noble_gas”, “transition_metal”, “post_transition_metal”, “rare_earth_metal”, “metal”, “metalloid”, “alkali”, “alkaline”, “halogen”, “chalcogen”, “lanthanoid”, “actinoid”, “radioactive”, “quadrupolar”, “s-block”, “p-block”, “d-block”, “f-block”.

Returns:

True if any elements in Composition match category.

Return type:

bool

copy() Self[source]

A copy of the composition.

property element_composition: Self[source]

The composition replacing any species by the corresponding element.

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

List of elements in Composition.

property formula: str[source]

A formula string, with elements sorted by electronegativity, e.g. Li4 Fe4 P4 O16.

property fractional_composition: Self[source]

The normalized composition in which the amounts of each species sum to 1. E.g. “Fe2 O3”.fractional_composition = “Fe0.4 O0.6”.

classmethod from_dict(dct: dict) Self[source]

Create a composition from a dict generated by as_dict(). Strictly not necessary given that the standard constructor already takes in such an input, but this method preserves the standard pymatgen API of having from_dict methods to reconstitute objects generated by as_dict(). Allows for easier introspection.

Parameters:

dct (dict) – {symbol: amount} dict.

classmethod from_weight_dict(weight_dict: dict[SpeciesLike, float], strict: bool = True, **kwargs) Self[source]

Create a Composition based on a dict of atomic fractions calculated from a dict of weight fractions. Allows for quick creation of the class from weight-based notations commonly used in the industry, such as Ti6V4Al and Ni60Ti40.

Parameters:
  • weight_dict (dict) – {symbol: weight_fraction} dict.

  • strict (bool) – Only allow valid Elements and Species in the Composition. Defaults to True.

  • **kwargs – Additional kwargs supported by the dict() constructor.

Returns:

Composition in molar fractions.

Examples

>>> Composition.from_weights({"Fe": 0.5, "Ni": 0.5})
Composition('Fe0.512434 Ni0.487566')
>>> Composition.from_weights({"Ti": 60, "Ni": 40})
Composition('Ti0.647796 Ni0.352204')
classmethod from_weights(*args, strict: bool = True, **kwargs) Self[source]

Create a Composition from a weight-based formula.

Parameters:
  • *args – Any number of 2-tuples as key-value pairs.

  • strict (bool) – Only allow valid Elements and Species in the Composition. Defaults to False.

  • allow_negative (bool) – Whether to allow negative compositions. Defaults to False.

  • **kwargs – Additional kwargs supported by the dict() constructor.

Returns:

Composition in molar fractions.

Examples

>>> Composition.from_weights("Fe50Ti50")
Composition('Fe0.461538 Ti0.538462')
>>> Composition.from_weights({"Fe": 0.5, "Ni": 0.5})
Composition('Fe0.512434 Ni0.487566')
get_atomic_fraction(el: SpeciesLike) float[source]

Calculate atomic fraction of an Element or Species.

Parameters:

el (SpeciesLike) – Element or Species to get fraction for.

Returns:

Atomic fraction for element el in Composition

get_el_amt_dict() dict[str, float][source]
Returns:

element symbol and (unreduced) amount. E.g.

{“Fe”: 4.0, “O”: 6.0}.

Return type:

dict[str, float]

get_integer_formula_and_factor(max_denominator: int = 10000, iupac_ordering: bool = False) tuple[str, float][source]

Calculate an integer formula and factor.

Parameters:
  • max_denominator (int) – all amounts in the el:amt dict are first converted to a Fraction with this maximum denominator

  • iupac_ordering (bool, optional) – Whether to order the formula by the iupac “electronegativity” series, defined in Table VI of “Nomenclature of Inorganic Chemistry (IUPAC Recommendations 2005)”. This ordering effectively follows the groups and rows of the periodic table, except the Lanthanides, Actinides and hydrogen. Note that polyanions will still be determined based on the true electronegativity of the elements.

Returns:

A pretty normalized formula and a multiplicative factor, i.e., Li0.5O0.25 returns (Li2O, 0.25). O0.25 returns (O2, 0.125)

get_reduced_composition_and_factor() tuple[Self, float][source]

Calculate a reduced composition and factor.

Returns:

A normalized composition and a multiplicative factor, i.e., Li4Fe4P4O16 returns (Composition(“LiFePO4”), 4).

get_reduced_formula_and_factor(iupac_ordering: bool = False) tuple[str, float][source]

Calculate a reduced formula and factor.

Parameters:

iupac_ordering (bool, optional) – Whether to order the formula by the iupac “electronegativity” series, defined in Table VI of “Nomenclature of Inorganic Chemistry (IUPAC Recommendations 2005)”. This ordering effectively follows the groups and rows of the periodic table, except the Lanthanides, Actinides and hydrogen. Note that polyanions will still be determined based on the true electronegativity of the elements.

Returns:

A pretty normalized formula and a multiplicative factor, i.e., Li4Fe4P4O16 returns (LiFePO4, 4).

get_wt_fraction(el: SpeciesLike) float[source]

Calculate weight fraction of an Element or Species.

Parameters:

el (Element | Species) – Element or Species to get fraction for.

Returns:

Weight fraction for element el in Composition.

Return type:

float

property hill_formula: str[source]

The Hill system (or Hill notation) is a system of writing empirical chemical formulas, molecular chemical formulas and components of a condensed formula such that the number of carbon atoms in a molecule is indicated first, the number of hydrogen atoms next, and then the number of all other chemical elements subsequently, in alphabetical order of the chemical symbols. When the formula contains no carbon, all the elements, including hydrogen, are listed alphabetically.

property is_element: bool[source]

True if composition is an element.

property iupac_formula: str[source]

A formula string, with elements sorted by the IUPAC electronegativity ordering defined in Table VI of “Nomenclature of Inorganic Chemistry (IUPAC Recommendations 2005)”. This ordering effectively follows the groups and rows of the periodic table, except the Lanthanides, Actinides and hydrogen. Polyanions are still determined based on the true electronegativity of the elements. e.g. CH2(SO4)2.

property num_atoms: float[source]

Total number of atoms in Composition. For negative amounts, sum of absolute values.

oxi_prob = None[source]
oxi_state_guesses(oxi_states_override: dict | None = None, target_charge: float = 0, all_oxi_states: bool = False, max_sites: int | None = None) tuple[dict[str, float]][source]

Check if the composition is charge-balanced and returns back all charge-balanced oxidation state combinations. Composition must have integer values. Note that more num_atoms in the composition gives more degrees of freedom. e.g. if possible oxidation states of element X are [2,4] and Y are [-3], then XY is not charge balanced but X2Y2 is. Results are returned from most to least probable based on ICSD statistics. Use max_sites to improve performance if needed.

Parameters:
  • oxi_states_override (dict) – dict of str->list to override an element’s common oxidation states, e.g. {“V”: [2,3,4,5]}

  • target_charge (int) – the desired total charge on the structure. Default is 0 signifying charge balance.

  • all_oxi_states (bool) – if True, all oxidation states of an element, even rare ones, are used in the search for guesses. However, the full oxidation state list is very inclusive and can produce nonsensical results. If False, the icsd_oxidation_states list is used when present, or the common_oxidation_states is used when icsd_oxidation_states is not present. These oxidation states lists comprise more commonly occurring oxidation states and results in more reliable guesses, albeit at the cost of missing some uncommon situations. The default is False.

  • max_sites (int) – if possible, will reduce Compositions to at most this many sites to speed up oxidation state guesses. If the composition cannot be reduced to this many sites a ValueError will be raised. Set to -1 to just reduce fully. If set to a number less than -1, the formula will be fully reduced but a ValueError will be thrown if the number of atoms in the reduced formula is greater than abs(max_sites).

Returns:

each dict reports an element symbol and average

oxidation state across all sites in that composition. If the composition is not charge balanced, an empty list is returned.

Return type:

list[dict]

static ranked_compositions_from_indeterminate_formula(fuzzy_formula: str, lock_if_strict: bool = True) list[Composition][source]

Takes in a formula where capitalization might not be correctly entered, and suggests a ranked list of potential Composition matches. Author: Anubhav Jain.

Parameters:
  • fuzzy_formula (str) – A formula string, such as “co2o3” or “MN”, that may or may not have multiple interpretations

  • lock_if_strict (bool) – If true, a properly entered formula will only return the one correct interpretation. For example, “Co1” will only return “Co1” if true, but will return both “Co1” and “C1 O1” if false.

Returns:

A ranked list of potential Composition matches

property reduced_composition: Self[source]

The reduced composition, i.e. amounts normalized by greatest common denominator. E.g. “Fe4 P4 O16”.reduced_composition = “Fe P O4”.

property reduced_formula: str[source]

A pretty normalized formula, i.e., LiFePO4 instead of Li4Fe4P4O16.

remove_charges() Self[source]

Get a new Composition with charges from each Species removed.

Returns:

Composition object without charge decoration, for example {“Fe3+”: 2.0, “O2-“:3.0} becomes {“Fe”: 2.0, “O”:3.0}

replace(elem_map: dict[str, str | dict[str, float]]) Self[source]

Replace elements in a composition. Returns a new Composition, leaving the old one unchanged.

Parameters:

elem_map (dict[str, str | dict[str, float]]) – dict of elements or species to swap. E.g. {“Li”: “Na”} performs a Li for Na substitution. The target can be a {species: factor} dict. For example, in Fe2O3 you could map {“Fe”: {“Mg”: 0.5, “Cu”:0.5}} to obtain MgCuO3.

Returns:

New object with elements remapped according to elem_map.

Return type:

Composition

special_formulas: ClassVar[dict[str, str]] = {'Cl': 'Cl2', 'CsO': 'Cs2O2', 'F': 'F2', 'H': 'H2', 'HO': 'H2O2', 'KO': 'K2O2', 'LiO': 'Li2O2', 'N': 'N2', 'NaO': 'Na2O2', 'O': 'O2', 'RbO': 'Rb2O2'}[source]
property to_data_dict: dict[Literal['reduced_cell_composition', 'unit_cell_composition', 'reduced_cell_formula', 'elements', 'nelements'], Any][source]

Returns: dict with the following keys:

  • reduced_cell_composition

  • unit_cell_composition

  • reduced_cell_formula

  • elements

  • nelements.

to_pretty_string() str[source]
Returns:

Same output as __str__() but without spaces.

Return type:

str

property to_reduced_dict: dict[str, float][source]

Returns: dict[str, float]: element symbols mapped to reduced amount e.g. {“Fe”: 2.0, “O”:3.0}.

property to_weight_dict: dict[str, float][source]

Returns: dict[str, float]: weight fractions of each component, e.g. {“Ti”: 0.90, “V”: 0.06, “Al”: 0.04}.

property total_electrons: float[source]

Total number of electrons in composition.

property valid: bool[source]

True if Composition contains valid elements or species and False if the Composition contains any dummy species.

property weight: float[source]

Total molecular weight of Composition.

exception CompositionError[source]

Bases: Exception

Exception class for composition errors.

reduce_formula(sym_amt: dict[str, float] | dict[str, int], iupac_ordering: bool = False) tuple[str, float][source]

Helper function to reduce a sym_amt dict to a reduced formula and factor.

Parameters:
  • sym_amt (dict) – {symbol: amount}.

  • iupac_ordering (bool, optional) – Whether to order the formula by the iupac “electronegativity” series, defined in Table VI of “Nomenclature of Inorganic Chemistry (IUPAC Recommendations 2005)”. This ordering effectively follows the groups and rows of the periodic table, except the Lanthanides, Actinides and hydrogen. Note that polyanions will still be determined based on the true electronegativity of the elements.

Returns:

reduced formula and factor.

Return type:

tuple[str, float]

pymatgen.core.interface module

This module provides classes to store, generate, and manipulate interfaces, including grain boundaries.

class GrainBoundary(lattice: np.ndarray | Lattice, species: Sequence[CompositionLike], coords: Sequence[ArrayLike], rotation_axis: Tuple3Ints | Tuple4Ints, rotation_angle: float, gb_plane: Tuple3Ints, join_plane: Tuple3Ints, init_cell: Structure, vacuum_thickness: float, ab_shift: tuple[float, float], site_properties: dict[str, Any], oriented_unit_cell: Structure, validate_proximity: bool = False, coords_are_cartesian: bool = False, properties: dict | None = None)[source]

Bases: Structure

Representation of grain boundary (GB). Implements additional attributes pertaining to GBs, but the init method does not actually implement any algorithm that creates a GB. This is a DUMMY class who’s init method only holds information about the GB. Also has additional methods that returns other information about a GB such as sigma value.

Note that all GBs have their surface normal oriented in the c-direction. This means the lattice vectors a and b are in the GB surface plane (at least for one grain) and the c vector is out of the surface plane (though not necessarily perpendicular to the surface).

A Structure with additional information and methods pertaining to GBs.

Parameters:
  • lattice (Lattice | np.ndarray) – The lattice, either as an instance or a 3x3 array. Each row should correspond to a lattice vector.

  • species ([Species]) –

    Sequence of species on each site. Can take in flexible input, including:

    1. A sequence of element / species specified either as string symbols, e.g. [“Li”, “Fe2+”, “P”, …] or atomic numbers, e.g. (3, 56, …) or actual Element or Species objects.

    2. List of dict of elements/species and occupancies, e.g. [{“Fe” : 0.5, “Mn”:0.5}, …]. This allows the setup of disordered structures.

  • coords (Nx3 array) – list of fractional/cartesian coordinates for each species.

  • rotation_axis (list[int]) – Rotation axis of GB in the form of a list of integers, e.g. [1, 1, 0].

  • rotation_angle (float, in unit of degree) – rotation angle of GB.

  • gb_plane (list) – Grain boundary plane in the form of a list of integers e.g.: [1, 2, 3].

  • join_plane (list) – Joining plane of the second grain in the form of a list of integers. e.g.: [1, 2, 3].

  • init_cell (Structure) – initial bulk structure to form the GB.

  • site_properties (dict) – Properties associated with the sites as a dict of sequences, The sequences have to be the same length as the atomic species and fractional_coords. For GB, you should have the ‘grain_label’ properties to classify the sites as ‘top’, ‘bottom’, ‘top_incident’, or ‘bottom_incident’.

  • vacuum_thickness (float in angstrom) – The thickness of vacuum inserted between two grains of the GB.

  • ab_shift (list of float, in unit of crystal vector a, b) – The relative shift along a, b vectors.

  • oriented_unit_cell (Structure) – oriented unit cell of the bulk init_cell. Helps to accurately calculate the bulk properties that are consistent with GB calculations.

  • validate_proximity (bool) – Whether to check if there are sites that are less than 0.01 Ang apart. Defaults to False.

  • coords_are_cartesian (bool) – Set to True if you are providing coordinates in Cartesian coordinates. Defaults to False.

  • properties (dict) – dictionary containing properties associated with the whole GrainBoundary.

as_dict() dict[source]
Returns:

Dictionary representation of GrainBoundary object.

property bottom_grain: Structure[source]

The bottom grain (Structure) of the GB.

property coincidents: list[Site][source]

A list of coincident sites.

copy() Self[source]

Make a copy of the GrainBoundary.

classmethod from_dict(dct: dict) Self[source]

Generate GrainBoundary from a dict created by as_dict().

Parameters:

dct – dict

Returns:

GrainBoundary object

get_sorted_structure(key: Callable | None = None, reverse: bool = False) Self[source]

Get a sorted copy of the Structure. The parameters have the same meaning as in list.sort. By default, sites are sorted by the electronegativity of the species. Note that Slab has to override this because of the different __init__ args.

Parameters:
  • key – Specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

  • reverse (bool) – If set to True, then the list elements are sorted as if each comparison were reversed.

property sigma: int[source]

The sigma value of the GB. If using ‘quick_gen’ to generate GB, this value is not valid.

property sigma_from_site_prop: int[source]

The sigma value of the GB from site properties. If the GB structure merge some atoms due to the atoms too close with each other, this property will not work.

property top_grain: Structure[source]

The top grain (Structure) of the GB.

class GrainBoundaryGenerator(initial_structure: Structure, symprec: float = 0.1, angle_tolerance: float = 1.0)[source]

Bases: object

Generate grain boundaries (GBs) from bulk conventional cell (FCC, BCC can from the primitive cell), and works for Cubic, Tetragonal, Orthorhombic, Rhombohedral, and Hexagonal systems. It generate GBs from given parameters, which includes GB plane, rotation axis, rotation angle.

This class works for any general GB, including twist, tilt and mixed GBs. The three parameters, rotation axis, GB plane and rotation angle, are sufficient to identify one unique GB. While sometimes, users may not be able to tell what exactly rotation angle is but prefer to use sigma as an parameter, this class also provides the function that is able to return all possible rotation angles for a specific sigma value. The same sigma value (with rotation axis fixed) can correspond to multiple rotation angles.

Users can use structure matcher in pymatgen to get rid of the redundant structures.

Parameters:
  • initial_structure (Structure) – Initial input structure. It can be conventional or primitive cell (primitive cell works for bcc and fcc). For fcc and bcc, using conventional cell can lead to a non-primitive grain boundary structure. This code supplies Cubic, Tetragonal, Orthorhombic, Rhombohedral, and Hexagonal systems.

  • symprec (float) – Tolerance for symmetry finding. Defaults to 0.1 (the value used in Materials Project), which is for structures with slight deviations from their proper atomic positions (e.g., structures relaxed with electronic structure codes). A smaller value of 0.01 is often used for properly refined structures with atoms in the proper symmetry coordinates. User should make sure the symmetry is what you want.

  • angle_tolerance (float) – Angle tolerance for symmetry finding.

static enum_possible_plane_cubic(plane_cutoff: int, r_axis: tuple[int, int, int], r_angle: float) dict[Literal['Twist', 'Symmetric tilt', 'Normal tilt', 'Mixed'], list[list]][source]

Find all possible plane combinations for GBs given a rotation axis and angle for cubic system, and classify them to different categories, including “Twist”, “Symmetric tilt”, “Normal tilt”, “Mixed” GBs.

Parameters:
  • plane_cutoff (int) – the cutoff of plane miller index.

  • r_axis ((u, v, w])) – the rotation axis of the grain boundary.

  • r_angle (float) – rotation angle of the GBs.

Returns:

all combinations with keys as GB type, e.g. “Twist”, “Symmetric tilt”, etc.

and values as the combination of the two plane miller index (GB plane and joining plane).

Return type:

dict

static enum_sigma_cubic(cutoff: int, r_axis: tuple[int, int, int]) dict[int, list[float]][source]

Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in cubic system. The algorithm for this code is from reference, Acta Cryst, A40,108(1984).

Parameters:
  • cutoff (int) – the cutoff of sigma values.

  • r_axis ((u, v, w)) – the rotation axis of the grain boundary.

Returns:

sigmas dictionary with keys as the possible integer sigma values

and values as list of the possible rotation angles to the corresponding sigma values. e.g. the format as {sigma1: [angle11,angle12,…], sigma2: [angle21, angle22,…],…} Note: the angles are the rotation angles of one grain respect to the other grain. When generating the microstructures of the grain boundary using these angles, you need to analyze the symmetry of the structure. Different angles may result in equivalent microstructures.

Return type:

dict

static enum_sigma_hex(cutoff: int, r_axis: tuple[int, int, int] | tuple[int, int, int, int], c2_a2_ratio: tuple[int, int]) dict[int, list[float]][source]

Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in hexagonal system. The algorithm for this code is from reference, Acta Cryst, A38,550(1982).

Parameters:
  • cutoff (int) – the cutoff of sigma values.

  • r_axis ((u, v, w) or (u, v, t, w)) – the rotation axis of the grain boundary.

  • c2_a2_ratio ((mu, mv)) – mu/mv is the square of the hexagonal axial ratio, which is rational number. If irrational, set c2_a2_ratio = None

Returns:

sigmas dictionary with keys as the possible integer sigma values

and values as list of the possible rotation angles to the corresponding sigma values. e.g. the format as {sigma1: [angle11, angle12, …], sigma2: [angle21, angle22, …], …} Note: the angles are the rotation angles of one grain respect to the other grain. When generating the microstructures of the grain boundary using these angles, you need to analyze the symmetry of the structure. Different angles may result in equivalent microstructures.

Return type:

dict

static enum_sigma_ort(cutoff: int, r_axis: Tuple3Ints, c2_b2_a2_ratio: Tuple3Floats) dict[int, list[float]][source]

Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in orthorhombic system.

Reference: Scipta Metallurgica 27, 291(1992).

Parameters:
  • cutoff (int) – the cutoff of sigma values.

  • r_axis ((u, v, w)) – the rotation axis of the grain boundary.

  • c2_b2_a2_ratio ((mu, lambda, mv)) – mu:lam:mv is the square of the orthorhombic axial ratio with rational numbers. If irrational for one axis, set it to None. e.g. mu:lam:mv = c2,None,a2, means b2 is irrational.

Returns:

sigmas dictionary with keys as the possible integer sigma values

and values as list of the possible rotation angles to the corresponding sigma values. e.g. the format as {sigma1: [angle11,angle12,…], sigma2: [angle21, angle22,…],…} Note: the angles are the rotation angle of one grain respect to the other grain. When generating the microstructure of the grain boundary using these angles, you need to analyze the symmetry of the structure. Different angles may result in equivalent microstructures.

Return type:

dict

static enum_sigma_rho(cutoff: int, r_axis: tuple[int, int, int] | tuple[int, int, int, int], ratio_alpha: tuple[int, int]) dict[int, list[float]][source]

Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in rhombohedral system. The algorithm for this code is from reference, Acta Cryst, A45,505(1989).

Parameters:
  • cutoff (int) – the cutoff of sigma values.

  • r_axis ((u, v, w) or (u, v, t, w)) – the rotation axis of the grain boundary.

  • ratio_alpha (tuple of two integers, e.g. mu, mv) – mu/mv is the ratio of (1+2*cos(alpha))/cos(alpha) with rational number. If irrational, set ratio_alpha = None.

Returns:

keys are possible integer sigma values

and values are lists of possible rotation angles to the {sigma1: [angle11, angle12,…], sigma2: [angle21, angle22,…],…} Note: the angles are the rotation angle of one grain respect to the other grain. When generating the microstructure of the grain boundary using these angles, you need to analyze the symmetry of the structure. Different angles may result in equivalent microstructures.

Return type:

dict[int, list[float]]

static enum_sigma_tet(cutoff: int, r_axis: tuple[int, int, int], c2_a2_ratio: tuple[int, int]) dict[int, list[float]][source]

Find all possible sigma values and corresponding rotation angles within a sigma value cutoff with known rotation axis in tetragonal system. The algorithm for this code is from reference, Acta Cryst, B46,117(1990).

Parameters:
  • cutoff (int) – the cutoff of sigma values.

  • r_axis ((u, v, w)) – the rotation axis of the grain boundary.

  • c2_a2_ratio ((mu, mv)) – mu/mv is the square of the tetragonal axial ratio with rational number. If irrational, set c2_a2_ratio = None.

Returns:

sigmas dictionary with keys as the possible integer sigma values

and values as list of the possible rotation angles to the corresponding sigma values. e.g. the format as {sigma1: [angle11, angle12, …], sigma2: [angle21, angle22, …], …} Note: the angles are the rotation angle of one grain respect to the other grain. When generating the microstructure of the grain boundary using these angles, you need to analyze the symmetry of the structure. Different angles may result in equivalent microstructures.

Return type:

dict

gb_from_parameters(rotation_axis: tuple[int, int, int], rotation_angle: float, expand_times: int = 4, vacuum_thickness: float = 0.0, ab_shift: tuple[float, float] = (0, 0), normal: bool = False, ratio: list[int] | None = None, plane: tuple[int, int, int] | None = None, max_search: int = 20, tol_coi: float = 1e-08, rm_ratio: float = 0.7, quick_gen: bool = False) GrainBoundary[source]
Parameters:
  • rotation_axis (tuple of 3) – Rotation axis of GB e.g.: (1, 1, 0).

  • rotation_angle (float, in unit of degree) – rotation angle used to generate GB. Make sure the angle is accurate enough. You can use the enum* functions in this class to extract the accurate angle. e.g.: The rotation angle of sigma 3 twist GB with the rotation axis (1, 1, 1) and GB plane (1, 1, 1) can be 60 degree. If you do not know the rotation angle, but know the sigma value, we have provide the function get_rotation_angle_from_sigma which is able to return all the rotation angles of sigma value you provided.

  • expand_times (int) – The multiple times used to expand one unit grain to larger grain. This is used to tune the grain length of GB to warrant that the two GBs in one cell do not interact with each other. Default set to 4.

  • vacuum_thickness (float, in angstrom) – The thickness of vacuum that you want to insert between two grains of the GB. Default to 0.

  • ab_shift (list of float, in unit of a, b vectors of Gb) – in plane shift of two grains

  • normal (bool) – determine if need to require the c axis of top grain (first transformation matrix) perpendicular to the surface or not. default to false.

  • ratio (list[int]) – lattice axial ratio. For cubic system, ratio is not needed. For tetragonal system, ratio = [mu, mv], list of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none. For orthorhombic system, ratio = [mu, lam, mv], list of 3 integers, that is, mu:lam:mv = c2:b2:a2. If irrational for one axis, set it to None. e.g. mu:lam:mv = c2,None,a2, means b2 is irrational. For rhombohedral system, ratio = [mu, mv], list of two integers, that is, mu/mv is the ratio of (1+2*cos(alpha))/cos(alpha). If irrational, set it to None. For hexagonal system, ratio = [mu, mv], list of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none. This code also supplies a class method to generate the ratio from the structure (get_ratio). User can also make their own approximation and input the ratio directly.

  • plane (tuple of 3) – Grain boundary plane. If none, we set it as twist GB. The plane will be perpendicular to the rotation axis.

  • max_search (int) – max search for the GB lattice vectors that give the smallest GB lattice. If normal is true, also max search the GB c vector that perpendicular to the plane. For complex GB, if you want to speed up, you can reduce this value. But too small of this value may lead to error.

  • tol_coi (float) – tolerance to find the coincidence sites. When making approximations to the ratio needed to generate the GB, you probably need to increase this tolerance to obtain the correct number of coincidence sites. To check the number of coincidence sites are correct or not, you can compare the generated Gb object’s sigma_from_site_prop with enum* sigma values (what user expected by input).

  • rm_ratio (float) – the criteria to remove the atoms which are too close with each other. rm_ratio*bond_length of bulk system is the criteria of bond length, below which the atom will be removed. Default to 0.7.

  • quick_gen (bool) – whether to quickly generate a supercell, if set to true, no need to find the smallest cell.

Returns:

GrainBoundary object

get_ratio(max_denominator: int = 5, index_none: int | None = None) list[int] | None[source]

Find the axial ratio needed for GB generator input.

Parameters:
  • max_denominator (int) – the maximum denominator for the computed ratio, default to be 5.

  • index_none (int) – specify the irrational axis. 0-a, 1-b, 2-c. Only may be needed for orthorhombic system.

Returns:

axial ratio needed for GB generator (list of integers).

static get_rotation_angle_from_sigma(sigma: int, r_axis: tuple[int, int, int] | tuple[int, int, int, int], lat_type: str = 'c', ratio: tuple[int, int] | tuple[int, int, int] | None = None) list[float][source]

Find all possible rotation angles for the given sigma value.

Parameters:
  • sigma (int) – sigma value provided

  • r_axis ((u, v, w) or (u, v, t, w) for hex/rho systems) – the rotation axis of the grain boundary.

  • lat_type (str) – one character to specify the lattice type. Defaults to ‘c’ for cubic. ‘c’ or ‘C’: cubic system ‘t’ or ‘T’: tetragonal system ‘o’ or ‘O’: orthorhombic system ‘h’ or ‘H’: hexagonal system ‘r’ or ‘R’: rhombohedral system

  • ratio (tuple[int, ...]) – lattice axial ratio. For cubic system, ratio is not needed. For tetragonal system, ratio = (mu, mv), tuple of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none. For orthorhombic system, ratio = (mu, lam, mv), tuple of 3 integers, that is, mu:lam:mv = c2:b2:a2. If irrational for one axis, set it to None. e.g. mu:lam:mv = c2,None,a2, means b2 is irrational. For rhombohedral system, ratio = (mu, mv), tuple of two integers, that is, mu/mv is the ratio of (1+2*cos(alpha)/cos(alpha). If irrational, set it to None. For hexagonal system, ratio = (mu, mv), tuple of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none.

Returns:

rotation_angles corresponding to the provided sigma value. If the sigma value is not correct, return the rotation angle corresponding to the correct possible sigma value right smaller than the wrong sigma value provided.

static get_trans_mat(r_axis: Tuple3Ints | Tuple4Ints, angle: float, normal: bool = False, trans_cry: NDArray | None = None, lat_type: str = 'c', ratio: list[int] | None = None, surface: Tuple3Ints | Tuple4Ints | None = None, max_search: int = 20, quick_gen: bool = False)[source]

Find the two transformation matrix for each grain from given rotation axis, GB plane, rotation angle and corresponding ratio (see explanation for ratio below). The structure of each grain can be obtained by applying the corresponding transformation matrix to the conventional cell. The algorithm for this code is from reference, Acta Cryst, A32,783(1976).

Parameters:
  • r_axis ((u, v, w) or (u, v, t, w) for hex/rho systems) – the rotation axis of the grain boundary.

  • angle (float, in unit of degree) – the rotation angle of the grain boundary

  • normal (bool) – determine if need to require the c axis of one grain associated with the first transformation matrix perpendicular to the surface or not. default to false.

  • trans_cry (np.array) – shape 3x3. If the structure given are primitive cell in cubic system, e.g. bcc or fcc system, trans_cry is the transformation matrix from its conventional cell to the primitive cell.

  • lat_type (str) – one character to specify the lattice type. Defaults to ‘c’ for cubic. ‘c’ or ‘C’: cubic system ‘t’ or ‘T’: tetragonal system ‘o’ or ‘O’: orthorhombic system ‘h’ or ‘H’: hexagonal system ‘r’ or ‘R’: rhombohedral system

  • ratio (list[int]) – lattice axial ratio. For cubic system, ratio is not needed. For tetragonal system, ratio = [mu, mv], list of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none. For orthorhombic system, ratio = [mu, lam, mv], list of 3 integers, that is, mu:lam:mv = c2:b2:a2. If irrational for one axis, set it to None. e.g. mu:lam:mv = c2,None,a2, means b2 is irrational. For rhombohedral system, ratio = [mu, mv], list of two integers, that is, mu/mv is the ratio of (1+2*cos(alpha)/cos(alpha). If irrational, set it to None. For hexagonal system, ratio = [mu, mv], list of two integers, that is, mu/mv = c2/a2. If it is irrational, set it to none.

  • surface ((h, k, l) or (h, k, i, l) for hex/rho systems) – The miller index of grain boundary plane, with the format of (h, k, l) if surface is not given, the default is perpendicular to r_axis, which is a twist grain boundary.

  • max_search (int) – max search for the GB lattice vectors that give the smallest GB lattice. If normal is true, also max search the GB c vector that perpendicular to the plane.

  • quick_gen (bool) – whether to quickly generate a supercell, if set to true, no need to find the smallest cell.

Returns:

The transformation array for one grain. t2 (3 by 3 integer array): The transformation array for the other grain

Return type:

t1 (3 by 3 integer array)

static reduce_mat(mat: NDArray, mag: int, r_matrix: NDArray) NDArray[source]

Reduce integer array mat’s determinant mag times by linear combination of its row vectors, so that the new array after rotation (r_matrix) is still an integer array.

Parameters:
  • mat (3 by 3 array) – input matrix

  • mag (int) – reduce times for the determinant

  • r_matrix (3 by 3 array) – rotation matrix

Returns:

the reduced integer array

static slab_from_csl(csl: NDArray, surface: Tuple3Ints, normal: bool, trans_cry: NDArray, max_search: int = 20, quick_gen: bool = False) Matrix3D[source]

By linear operation of csl lattice vectors to get the best corresponding slab lattice. That is the area of a,b vectors (within the surface plane) is the smallest, the c vector first, has shortest length perpendicular to surface [h,k,l], second, has shortest length itself.

Parameters:
  • csl (3 by 3 integer array) – input csl lattice.

  • surface ((h, k, l)) – the miller index of the surface. determine if the c vector needs to perpendicular to surface.

  • normal (bool) – search the GB c vector that is perpendicular to the plane.

  • trans_cry (3 by 3 array) – transform matrix from crystal system to orthogonal system.

  • max_search (int) – max search for the GB lattice vectors that give the smallest GB lattice. If normal is True, also max search the GB c vector that is perpendicular to the plane.

  • quick_gen (bool) – whether to quickly generate a supercell, no need to find the smallest cell if set to true.

Returns:

a slab lattice (3 by 3 integer array)

Return type:

t_matrix

static vec_to_surface(vec: Vector3D) MillerIndex[source]

Transform a float vector to a surface miller index with integers.

Parameters:

vec (Vector3D) – input float vector

Returns:

the surface miller index of the input vector.

class Interface(lattice: Lattice | NDArray, species: list[Any], coords: NDArray, site_properties: dict[str, Any], validate_proximity: bool = False, to_unit_cell: bool = False, coords_are_cartesian: bool = False, in_plane_offset: tuple[float, float] = (0, 0), gap: float = 0, vacuum_over_film: float = 0, interface_properties: dict | None = None)[source]

Bases: Structure

Store data for defining an interface between two Structures.

Make an Interface, a Structure with additional information and methods pertaining to interfaces.

Parameters:
  • lattice (Lattice | np.ndarray) – The lattice, either as a pymatgen.core.Lattice or a 3x3 array. Each row should correspond to a lattice vector. e.g. [[10,0,0], [20,10,0], [0,0,30]] specifies a lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30].

  • species ([Species]) –

    Sequence of species on each site. Can take in flexible input, including:

    1. A sequence of element / species specified either as string symbols, e.g. [“Li”, “Fe2+”, “P”, …] or atomic numbers, e.g. (3, 56, …) or actual Element or Species objects.

    2. List of dict of elements/species and occupancies, e.g. [{“Fe” : 0.5, “Mn”:0.5}, …]. This allows the setup of disordered structures.

  • coords (Nx3 array) – list of fractional/cartesian coordinates of each species.

  • validate_proximity (bool) – Whether to check if there are sites that are less than 0.01 Ang apart. Defaults to False.

  • to_unit_cell (bool) – Whether to translate sites into the unit cell. Defaults to False.

  • coords_are_cartesian (bool) – Set to True if you are providing coordinates in Cartesian coordinates. Defaults to False.

  • site_properties (dict) – Properties associated with the sites as a dict of sequences, e.g. {“magmom”:[5,5,5,5]}. The sequences have to be the same length as the atomic species and fractional_coords. Defaults to None for no properties.

  • in_plane_offset – fractional shift in plane for the film with respect to the substrate

  • gap – gap between substrate and film in Angstroms; zero corresponds to the original distance between substrate and film sites

  • vacuum_over_film – vacuum space above the film in Angstroms. Defaults to 0.

  • interface_properties – properties associated with the Interface. Defaults to None.

as_dict() dict[source]

MSONable dict.

copy() Self[source]

Make a copy of the Interface.

property film: Structure[source]

A Structure for just the film.

property film_indices: list[int][source]

Site indices of the film sites.

property film_layers: int[source]

Number of layers of the minimum element in the film composition.

property film_sites: list[Site][source]

The film sites of the interface.

property film_termination: str[source]

Label for the film termination chemistry.

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

dct – dict.

Returns:

Creates slab from dict.

classmethod from_slabs(substrate_slab: Slab, film_slab: Slab, in_plane_offset: tuple[float, float] = (0, 0), gap: float = 1.6, vacuum_over_film: float = 0, interface_properties: dict | None = None, center_slab: bool = True) Self[source]

Make an Interface by merging a substrate and film slabs The film a- and b-vectors will be forced to be the substrate slab’s a- and b-vectors.

For now, it’s suggested to use a factory method that will ensure the appropriate Interface is already met.

Parameters:
  • substrate_slab (Slab) – slab for the substrate.

  • film_slab (Slab) – slab for the film.

  • in_plane_offset (tuple) – fractional shift in plane for the film with respect to the substrate. For example, (0.5, 0.5) will shift the film by half the substrate’s a- and b-vectors. Defaults to (0, 0).

  • gap (float) – gap between substrate and film in Angstroms. Defaults to 1.6.

  • vacuum_over_film (float) – vacuum space above the film in Angstroms. Defaults to 0.

  • interface_properties (dict) – misc properties to assign to the Interface. Defaults to None.

  • center_slab (bool) – center the slab. Defaults to True.

property gap: float[source]

The gap in Cartesian units between the film and the substrate.

get_shifts_based_on_adsorbate_sites(tolerance: float = 0.1) list[tuple[float, float]][source]

Compute possible in-plane shifts based on an adsorbate site algorithm.

Parameters:

tolerance – tolerance for “uniqueness” for shifts in Cartesian unit This is usually Angstroms.

get_sorted_structure(key: Callable | None = None, reverse: bool = False) Structure[source]

Get a sorted structure for the Interface. The parameters have the same meaning as in list.sort. By default, sites are sorted by the electronegativity of the species.

Parameters:
  • key – Specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

  • reverse (bool) – If set to True, then the list elements are sorted as if each comparison were reversed.

property in_plane_offset: ndarray[source]

The shift between the film and substrate in fractional coordinates.

property substrate: Structure[source]

A Structure for just the substrate.

property substrate_indices: list[int][source]

Site indices for the substrate atoms.

property substrate_layers: int[source]

Number of layers of the minimum element in the substrate composition.

property substrate_sites: list[Site][source]

The site objects in the substrate.

property substrate_termination: str[source]

Label for the substrate termination chemistry.

property vacuum_over_film: float[source]

The vacuum space over the film in Cartesian units.

count_layers(struct: Structure, el: Element | None = None) int[source]

Count the number of layers along the c-axis.

fix_pbc(structure: Structure, matrix: NDArray = None) Structure[source]

Wrap all frac_coords of the input structure within [0, 1].

Parameters:
  • structure (pymatgen structure object) – input structure

  • matrix (lattice matrix, 3 by 3 array/matrix) – new structure’s lattice matrix, If None, use input structure’s matrix.

Returns:

new structure with fixed frac_coords and lattice matrix

label_termination(slab: Structure, ftol: float = 0.25, t_idx: int | None = None) str[source]

Label the slab surface termination.

Parameters:
  • slab (Slab) – film or substrate slab to label termination for

  • ftol (float) – tolerance for terminating position hierarchical clustering

  • t_idx (None | int) – if not None, adding an extra index to the termination label output

symm_group_cubic(mat: NDArray) list[source]

Obtain cubic symmetric equivalents of the list of vectors.

Parameters:

mat (np.ndarray) – n x 3 lattice matrix

Returns:

cubic symmetric equivalents of the list of vectors.

pymatgen.core.ion module

Module containing class to create an ion.

class Ion(composition: Composition, charge: float = 0.0, **kwargs)[source]

Bases: Composition, MSONable, Stringify

Just a Composition object with an additional variable to store charge.

The net charge can either be represented as Mn++, Mn+2, Mn[2+], Mn[++], or Mn[+2]. Note the order of the sign and magnitude in each representation.

Flexible Ion construction, similar to Composition. For more information, please see pymatgen.core.Composition.

property alphabetical_formula: str[source]

A formula string, with elements sorted by alphabetically and appended charge.

property anonymized_formula: str[source]

An anonymized formula. Appends charge to the end of anonymized composition.

as_dict() dict[str, float][source]
Returns:

dict with composition, as well as charge.

property charge: float[source]

Charge of the ion.

property composition: Composition[source]

Composition of ion.

property formula: str[source]

A formula string with appended charge. The charge is written with the sign preceding the magnitude, e.g. ‘Ca1 +2’. Uncharged species have “(aq)” appended, e.g. “O2 (aq)”.

classmethod from_dict(dct: dict) Self[source]

Generate an ion object from a dict created by as_dict().

Parameters:

dct – {symbol: amount} dict.

classmethod from_formula(formula: str) Self[source]

Create Ion from formula. The net charge can either be represented as Mn++, Mn+2, Mn[2+], Mn[++], or Mn[+2]. Note the order of the sign and magnitude in each representation.

Also note that (aq) can be included in the formula, e.g. “NaOH (aq)”.

Parameters:

formula (str) – The formula to create ion from.

Returns:

Ion

get_reduced_formula_and_factor(iupac_ordering: bool = False, hydrates: bool = False) tuple[str, float][source]

Calculate a reduced formula and factor.

Similar to Composition.get_reduced_formula_and_factor except that O-H formulas receive special handling to differentiate between hydrogen peroxide and OH-. Formulas containing HO are written with oxygen first (e.g. ‘Fe(OH)2’ rather than ‘Fe(HO)2’), and special formulas that apply to solids (e.g. Li2O2 instead of LiO) are not used.

Note that the formula returned by this method does not contain a charge. To include charge, use formula or reduced_formula instead.

Parameters:
  • iupac_ordering (bool, optional) – Whether to order the formula by the iupac “electronegativity” series, defined in Table VI of “Nomenclature of Inorganic Chemistry (IUPAC Recommendations 2005)”. This ordering effectively follows the groups and rows of the periodic table, except the Lanthanides, Actinides and hydrogen. Note that polyanions will still be determined based on the true electronegativity of the elements.

  • hydrates – If True (default), attempt to recognize hydrated metal complexes and separate out the H2O in the reduced formula. For example, Zr(OH)4 becomes ZrO2.2H2O. Applies only to Ions containing metals.

Returns:

A pretty normalized formula and a multiplicative factor, i.e.,

H4O4 returns (‘H2O2’, 2.0).

Return type:

tuple[str, float]

oxi_state_guesses(oxi_states_override: dict | None = None, all_oxi_states: bool = False, max_sites: int | None = None) list[dict[str, float]][source]

Check if the composition is charge-balanced and returns all charge-balanced oxidation state combinations. Composition must have integer values. Note that more num_atoms in the composition gives more degrees of freedom. e.g. if possible oxidation states of element X are [2,4] and Y are [-3], then XY is not charge balanced but X2Y2 is. Results are returned from most to least probable based on ICSD statistics. Use max_sites to improve performance if needed.

Parameters:
  • oxi_states_override (dict) – dict of str->list to override an element’s common oxidation states, e.g. {“V”: [2,3,4,5]}

  • all_oxi_states (bool) – if True, an element defaults to all oxidation states in pymatgen Element.icsd_oxidation_states. Otherwise, default is Element.common_oxidation_states. Note that the full oxidation state list is very inclusive and can produce nonsensical results.

  • max_sites (int) – if possible, will reduce Compositions to at most this many sites to speed up oxidation state guesses. If the composition cannot be reduced to this many sites a ValueError will be raised. Set to -1 to just reduce fully. If set to a number less than -1, the formula will be fully reduced but a ValueError will be thrown if the number of atoms in the reduced formula is greater than abs(max_sites).

Returns:

A list of dicts - each dict reports an element symbol and average

oxidation state across all sites in that composition. If the composition is not charge balanced, an empty list is returned.

property reduced_formula: str[source]

A reduced formula string with appended charge. The charge is placed in brackets with the sign preceding the magnitude, e.g. ‘Ca[+2]’. Uncharged species have “(aq)” appended, e.g. “O2(aq)”.

to_pretty_string() str[source]

Pretty string with proper superscripts.

property to_reduced_dict: dict[source]

Returns: dict with element symbol and reduced amount e.g.

{“Fe”: 2.0, “O”:3.0}.

pymatgen.core.lattice module

This module defines the Lattice class, the fundamental class for representing periodic crystals. It is essentially a matrix with some extra methods and attributes.

class Lattice(matrix: ArrayLike, pbc: PbcLike = (True, True, True))[source]

Bases: MSONable

Essentially a matrix with conversion matrices. In general, it is assumed that lengths are in Angstrom and angles are in degrees unless otherwise stated.

Properties lazily generated for efficiency.

Create a lattice from any sequence of 9 numbers. Note that the sequence is assumed to be read one row at a time. Each row represents one lattice vector.

Parameters:
  • matrix – Sequence of numbers in any form. Examples of acceptable input. i) An actual numpy array. ii) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] iii) [1, 0, 0 , 0, 1, 0, 0, 0, 1] iv) (1, 0, 0, 0, 1, 0, 0, 0, 1) Each row should correspond to a lattice vector. e.g. [[10, 0, 0], [20, 10, 0], [0, 0, 30]] specifies a lattice with lattice vectors [10, 0, 0], [20, 10, 0] and [0, 0, 30].

  • pbc – a tuple defining the periodic boundary conditions along the three axis of the lattice.

property a: float[source]

a lattice parameter.

property abc: Vector3D[source]

Lengths of the lattice vectors, i.e. (a, b, c).

property alpha: float[source]

Angle alpha of lattice in degrees.

property angles: Vector3D[source]

Lattice angles.

Returns:

The angles (alpha, beta, gamma) of the lattice.

as_dict(verbosity: int = 0) dict[source]

MSONable dict representation of the Lattice.

Parameters:

verbosity (int) – Default of 0 only includes the matrix representation. Set to 1 to include the lattice parameters.

property b: float[source]

b lattice parameter.

property beta: float[source]

Angle beta of lattice in degrees.

property c: float[source]

c lattice parameter.

copy() Self[source]

Make a copy of this lattice.

classmethod cubic(a: float, pbc: PbcLike = (True, True, True)) Self[source]

Convenience constructor for a cubic lattice.

Parameters:
  • a (float) – The a lattice parameter of the cubic cell.

  • pbc (tuple) – a tuple defining the periodic boundary conditions along the three axis of the lattice. If None periodic in all directions.

Returns:

Cubic lattice of dimensions (a x a x a).

d_hkl(miller_index: MillerIndex) float[source]

Get the distance between the hkl plane and the origin.

Parameters:

miller_index (MillerIndex) – Miller index of plane

Returns:

distance between hkl plane and origin

Return type:

float

dot(coords_a: ArrayLike, coords_b: ArrayLike, frac_coords: bool = False) np.ndarray[source]

Compute the scalar product of vector(s).

Parameters:
  • coords_a – Array-like coordinates.

  • coords_b – Array-like coordinates.

  • frac_coords (bool) – True if the vectors are fractional (as opposed to Cartesian) coordinates.

Returns:

one-dimensional numpy array.

find_all_mappings(other_lattice: Self, ltol: float = 1e-05, atol: float = 1, skip_rotation_matrix: bool = False) Iterator[tuple[Lattice, np.ndarray | None, np.ndarray]][source]

Find all mappings between current lattice and another lattice.

Parameters:
  • other_lattice (Lattice) – Another lattice that is equivalent to this one.

  • ltol (float) – Tolerance for matching lengths. Defaults to 1e-5.

  • atol (float) – Tolerance for matching angles. Defaults to 1.

  • skip_rotation_matrix (bool) – Whether to skip calculation of the rotation matrix

Yields:

(aligned_lattice, rotation_matrix, scale_matrix) if a mapping is found. aligned_lattice is a rotated version of other_lattice that has the same lattice parameters, but which is aligned in the coordinate system of this lattice so that translational points match up in 3D. rotation_matrix is the rotation that has to be applied to other_lattice to obtain aligned_lattice, i.e., aligned_matrix = np.inner(other_lattice, rotation_matrix) and op = SymmOp.from_rotation_and_translation(rotation_matrix) aligned_matrix = op.operate_multi(latt.matrix) Finally, scale_matrix is the integer matrix that expresses aligned_matrix as a linear combination of this lattice, i.e., aligned_matrix = np.dot(scale_matrix, self.matrix)

None is returned if no matches are found.

find_mapping(other_lattice: Self, ltol: float = 1e-05, atol: float = 1, skip_rotation_matrix: bool = False) tuple[Lattice, np.ndarray | None, np.ndarray] | None[source]

Find a mapping between current lattice and another lattice. There are an infinite number of choices of basis vectors for two entirely equivalent lattices. This method returns a mapping that maps other_lattice to this lattice.

Parameters:
  • other_lattice (Lattice) – Another lattice that is equivalent to this one.

  • ltol (float) – Tolerance for matching lengths. Defaults to 1e-5.

  • atol (float) – Tolerance for matching angles. Defaults to 1.

  • skip_rotation_matrix (bool) – Whether to skip calculation of the rotation matrix. Defaults to False.

Returns:

(aligned_lattice, rotation_matrix, scale_matrix) if a mapping is found. aligned_lattice is a rotated version of other_lattice that has the same lattice parameters, but which is aligned in the coordinate system of this lattice so that translational points match up in 3D. rotation_matrix is the rotation that has to be applied to other_lattice to obtain aligned_lattice, i.e., aligned_matrix = np.inner(other_lattice, rotation_matrix) and op = SymmOp.from_rotation_and_translation(rotation_matrix) aligned_matrix = op.operate_multi(latt.matrix) Finally, scale_matrix is the integer matrix that expresses aligned_matrix as a linear combination of this lattice, i.e., aligned_matrix = np.dot(scale_matrix, self.matrix)

None is returned if no matches are found.

Return type:

tuple[Lattice, np.ndarray, np.ndarray]

classmethod from_dict(dct: dict, fmt: str | None = None, **kwargs) Self[source]

Create a Lattice from a dictionary.

If fmt is None, the dict should contain the a, b, c, alpha, beta, and gamma parameters.

If fmt == “abivars”, the function build a Lattice object from a dictionary with the Abinit variables acell and rprim in Bohr. If acell is not given, the Abinit default is used i.e. [1,1,1] Bohr

Example

Lattice.from_dict(fmt=”abivars”, acell=3*[10], rprim=np.eye(3))

classmethod from_parameters(a: float, b: float, c: float, alpha: float, beta: float, gamma: float, *, vesta: bool = False, pbc: PbcLike = (True, True, True)) Self[source]

Create a Lattice using unit cell lengths (in Angstrom) and angles (in degrees).

Parameters:
  • a (float) – a lattice parameter.

  • b (float) – b lattice parameter.

  • c (float) – c lattice parameter.

  • alpha (float) – alpha angle in degrees.

  • beta (float) – beta angle in degrees.

  • gamma (float) – gamma angle in degrees.

  • vesta (bool) – True if you import Cartesian coordinates from VESTA.

  • pbc (tuple) – a tuple defining the periodic boundary conditions along the three axis of the lattice. If None periodic in all directions.

Returns:

Lattice with the specified lattice parameters.

property gamma: float[source]

Angle gamma of lattice in degrees.

get_all_distances(frac_coords1: ArrayLike, frac_coords2: ArrayLike) np.ndarray[source]

Get the distances between two lists of coordinates taking into account periodic boundary conditions and the lattice. Note that this computes an MxN array of distances (i.e. the distance between each point in frac_coords1 and every coordinate in frac_coords2). This is different functionality from pbc_diff.

Parameters:
  • frac_coords1 – First set of fractional coordinates. e.g. [0.5, 0.6, 0.7] or [[1.1, 1.2, 4.3], [0.5, 0.6, 0.7]]. It can be a single coord or any array of coords.

  • frac_coords2 – Second set of fractional coordinates.

Returns:

2d array of Cartesian distances. E.g the distance between frac_coords1[i] and frac_coords2[j] is distances[i,j]

get_brillouin_zone() list[list[ndarray]][source]

Get the Wigner-Seitz cell for the reciprocal lattice, aka the Brillouin Zone.

Returns:

A list of list of coordinates. Each element in the list is a “facet” of the boundary of the Brillouin Zone. For instance, a list of four coordinates will represent a square facet.

get_cartesian_coords(fractional_coords: ArrayLike) np.ndarray[source]

Get the Cartesian coordinates given fractional coordinates.

Parameters:

fractional_coords (3x1 array) – Fractional coords.

Returns:

Cartesian coordinates

get_distance_and_image(frac_coords1: ArrayLike, frac_coords2: ArrayLike, jimage: ArrayLike | None = None) tuple[float, np.ndarray][source]

Get distance between two frac_coords assuming periodic boundary conditions. If the index jimage is not specified it selects the j image nearest to the i atom and returns the distance and jimage indices in terms of lattice vector translations. If the index jimage is specified it returns the distance between the frac_coords1 and the specified jimage of frac_coords2, and the given jimage is also returned.

Parameters:
  • frac_coords1 (3x1 array) – Reference frac_coords to get distance from.

  • frac_coords2 (3x1 array) – frac_coords to get distance from.

  • jimage (3x1 array) – Specific periodic image in terms of lattice translations, e.g. [1,0,0] implies to take periodic image that is one a-lattice vector away. If jimage is None, the image that is nearest to the site is found.

Returns:

distance and periodic lattice translations (jimage)

of the other site for which the distance applies. This means that the distance between frac_coords1 and (jimage + frac_coords2) is equal to distance.

Return type:

tuple[float, np.ndarray]

get_frac_coords_from_lll(lll_frac_coords: ArrayLike) np.ndarray[source]

Given fractional coordinates in the lll basis, returns corresponding fractional coordinates in the lattice basis.

get_fractional_coords(cart_coords: ArrayLike) np.ndarray[source]

Get the fractional coordinates given Cartesian coordinates.

Parameters:

cart_coords (3x1 array) – Cartesian coords.

Returns:

Fractional coordinates.

get_lll_frac_coords(frac_coords: ArrayLike) np.ndarray[source]

Given fractional coordinates in the lattice basis, returns corresponding fractional coordinates in the lll basis.

get_lll_reduced_lattice(delta: float = 0.75) Self[source]

Lenstra-Lenstra-Lovasz lattice basis reduction.

Parameters:

delta – Delta parameter.

Returns:

LLL reduced

Return type:

Lattice

get_miller_index_from_coords(coords: ArrayLike, coords_are_cartesian: bool = True, round_dp: int = 4, verbose: bool = True) MillerIndex[source]

Get the Miller index of a plane from a list of site coordinates.

A minimum of 3 sets of coordinates are required. If more than 3 sets of coordinates are given, the best plane that minimises the distance to all points will be calculated.

Parameters:
  • coords (iterable) – A list or numpy array of coordinates. Can be Cartesian or fractional coordinates. If more than three sets of coordinates are provided, the best plane that minimises the distance to all sites will be calculated.

  • coords_are_cartesian (bool, optional) – Whether the coordinates are in Cartesian space. If using fractional coordinates set to False.

  • round_dp (int, optional) – The number of decimal places to round the miller index to.

  • verbose (bool, optional) – Whether to print warnings.

Returns:

The Miller index.

Return type:

tuple

get_niggli_reduced_lattice(tol: float = 1e-05) Self[source]

Get the Niggli reduced lattice using the numerically stable algo proposed by R. W. Grosse-Kunstleve, N. K. Sauter, & P. D. Adams, Acta Crystallographica Section A Foundations of Crystallography, 2003, 60(1), 1-6. doi:10.1107/S010876730302186X.

Parameters:

tol (float) – The numerical tolerance. The default of 1e-5 should result in stable behavior for most cases.

Returns:

Niggli-reduced lattice.

Return type:

Lattice

get_points_in_sphere(frac_points: ArrayLike, center: ArrayLike, r: float, zip_results: bool = True) list[tuple[np.ndarray, float, int, np.ndarray]] | tuple[np.ndarray, ...] | list[source]

Find all points within a sphere from the point taking into account periodic boundary conditions. This includes sites in other periodic images.

Algorithm:

  1. place sphere of radius r in crystal and determine minimum supercell (parallelepiped) which would contain a sphere of radius r. for this we need the projection of a_1 on a unit vector perpendicular to a_2 & a_3 (i.e. the unit vector in the direction b_1) to determine how many a_1’s it will take to contain the sphere.

    Nxmax = r * length_of_b_1 / (2 Pi)

  2. keep points falling within r.

Parameters:
  • frac_points – All points in the lattice in fractional coordinates.

  • center – Cartesian coordinates of center of sphere.

  • r – radius of sphere.

  • zip_results (bool) – Whether to zip the results together to group by point, or return the raw frac_coord, dist, index arrays

Returns:

[(frac_coord, dist, index, supercell_image) …] since most of the time, subsequent

processing requires the distance, index number of the atom, or index of the image

else:

frac_coords, dists, inds, image

Return type:

if zip_results

get_points_in_sphere_old(frac_points: ArrayLike, center: ArrayLike, r: float, zip_results=True) list[tuple[np.ndarray, float, int, np.ndarray]] | tuple[list[np.ndarray], list[float], list[int], list[np.ndarray]][source]

Find all points within a sphere from the point taking into account periodic boundary conditions. This includes sites in other periodic images. Does not support partial periodic boundary conditions.

Algorithm:

  1. place sphere of radius r in crystal and determine minimum supercell (parallelepiped) which would contain a sphere of radius r. for this we need the projection of a_1 on a unit vector perpendicular to a_2 & a_3 (i.e. the unit vector in the direction b_1) to determine how many a_1’s it will take to contain the sphere.

    Nxmax = r * length_of_b_1 / (2 Pi)

  2. keep points falling within r.

Parameters:
  • frac_points – All points in the lattice in fractional coordinates.

  • center – Cartesian coordinates of center of sphere.

  • r – radius of sphere.

  • zip_results (bool) – Whether to zip the results together to group by point, or return the raw frac_coord, dist, index arrays

Returns:

[(frac_coord, dist, index, supercell_image) …] since most of the time, subsequent

processing requires the distance, index number of the atom, or index of the image

else:

frac_coords, dists, inds, image

Return type:

if zip_results

get_points_in_sphere_py(frac_points: ArrayLike, center: ArrayLike, r: float, zip_results: bool = True) list[tuple[np.ndarray, float, int, np.ndarray]] | list[np.ndarray][source]

Find all points within a sphere from the point taking into account periodic boundary conditions. This includes sites in other periodic images.

Algorithm:

  1. place sphere of radius r in crystal and determine minimum supercell (parallelepiped) which would contain a sphere of radius r. for this we need the projection of a_1 on a unit vector perpendicular to a_2 & a_3 (i.e. the unit vector in the direction b_1) to determine how many a_1’s it will take to contain the sphere.

    Nxmax = r * length_of_b_1 / (2 Pi)

  2. keep points falling within r.

Parameters:
  • frac_points – All points in the lattice in fractional coordinates.

  • center – Cartesian coordinates of center of sphere.

  • r – radius of sphere.

  • zip_results (bool) – Whether to zip the results together to group by point, or return the raw frac_coord, dist, index arrays

Returns:

[(frac_coord, dist, index, supercell_image) …] since most of the time, subsequent

processing requires the distance, index number of the atom, or index of the image

else:

frac_coords, dists, inds, image

Return type:

if zip_results

get_recp_symmetry_operation(symprec: float = 0.01) list[SymmOp][source]

Find the symmetric operations of the reciprocal lattice, to be used for hkl transformations.

Parameters:

symprec – default is 0.001.

get_vector_along_lattice_directions(cart_coords: ArrayLike) np.ndarray[source]

Get the coordinates along lattice directions given Cartesian coordinates.

Note, this is different than a projection of the Cartesian vector along the lattice parameters. It is simply the fractional coordinates multiplied by the lattice vector magnitudes.

For example, this method is helpful when analyzing the dipole moment (in units of electron Angstroms) of a ferroelectric crystal. See the Polarization class in pymatgen.analysis.ferroelectricity.polarization.

Parameters:

cart_coords (3x1 array) – Cartesian coords.

Returns:

Lattice coordinates.

get_wigner_seitz_cell() list[list[ndarray]][source]

Get the Wigner-Seitz cell for the given lattice.

Returns:

A list of list of coordinates. Each element in the list is a “facet” of the boundary of the Wigner Seitz cell. For instance, a list of four coordinates will represent a square facet.

classmethod hexagonal(a: float, c: float, pbc: PbcLike = (True, True, True)) Self[source]

Convenience constructor for a hexagonal lattice.

Parameters:
  • a (float) – a lattice parameter of the hexagonal cell.

  • c (float) – c lattice parameter of the hexagonal cell.

  • pbc (tuple) – a tuple defining the periodic boundary conditions along the three axis of the lattice. If None periodic in all directions.

Returns:

Hexagonal lattice of dimensions (a x a x c).

property inv_matrix: ndarray[source]

Inverse of lattice matrix.

property is_3d_periodic: bool[source]

True if the Lattice is periodic in all directions.

is_hexagonal(hex_angle_tol: float = 5, hex_length_tol: float = 0.01) bool[source]
Parameters:
  • hex_angle_tol – Angle tolerance

  • hex_length_tol – Length tolerance.

Returns:

Whether lattice corresponds to hexagonal lattice.

property is_orthogonal: bool[source]

Whether all angles are 90 degrees.

property lengths: Vector3D[source]

Lattice lengths.

Returns:

The lengths (a, b, c) of the lattice.

property lll_inverse: ndarray[source]

Inverse of self.lll_mapping.

property lll_mapping: ndarray[source]

The mapping between the LLL reduced lattice and the original lattice.

property lll_matrix: ndarray[source]

The matrix for LLL reduction.

property matrix: ndarray[source]

Copy of matrix representing the Lattice.

property metric_tensor: ndarray[source]

The metric tensor of the lattice.

classmethod monoclinic(a: float, b: float, c: float, beta: float, pbc: PbcLike = (True, True, True)) Self[source]

Convenience constructor for a monoclinic lattice.

Parameters:
  • a (float) – a lattice parameter of the monoclinic cell.

  • b (float) – b lattice parameter of the monoclinic cell.

  • c (float) – c lattice parameter of the monoclinic cell.

  • beta (float) – beta angle between lattice vectors b and c in degrees.

  • pbc (tuple) – a tuple defining the periodic boundary conditions along the three axis of the lattice. If None periodic in all directions.

Returns:

Monoclinic lattice of dimensions (a x b x c) with non

right-angle beta between lattice vectors a and c.

norm(coords: ArrayLike, frac_coords: bool = True) np.ndarray[source]

Compute the norm of vector(s).

Parameters:
  • coords – Array-like object with the coordinates.

  • frac_coords – Boolean stating whether the vector corresponds to fractional or Cartesian coordinates.

Returns:

one-dimensional numpy array.

classmethod orthorhombic(a: float, b: float, c: float, pbc: PbcLike = (True, True, True)) Self[source]

Convenience constructor for an orthorhombic lattice.

Parameters:
  • a (float) – a lattice parameter of the orthorhombic cell.

  • b (float) – b lattice parameter of the orthorhombic cell.

  • c (float) – c lattice parameter of the orthorhombic cell.

  • pbc (tuple) – a tuple defining the periodic boundary conditions along the three axis of the lattice. If None periodic in all directions.

Returns:

Orthorhombic lattice of dimensions (a x b x c).

property parameters: tuple[float, float, float, float, float, float][source]

6-tuple of floats (a, b, c, alpha, beta, gamma).

property params_dict: dict[str, float][source]

Dictionary of lattice parameters.

property pbc: PbcLike[source]

Tuple defining the periodicity of the Lattice.

property reciprocal_lattice: Self[source]

The reciprocal lattice. Note that this is the standard reciprocal lattice used for solid state physics with a factor of 2 * pi. If you are looking for the crystallographic reciprocal lattice, use the reciprocal_lattice_crystallographic property. The property is lazily generated for efficiency.

property reciprocal_lattice_crystallographic: Self[source]

The crystallographic reciprocal lattice, i.e. no factor of 2 * pi.

classmethod rhombohedral(a: float, alpha: float, pbc: PbcLike = (True, True, True)) Self[source]

Convenience constructor for a rhombohedral lattice.

Parameters:
  • a (float) – a lattice parameter of the rhombohedral cell.

  • alpha (float) – Angle for the rhombohedral lattice in degrees.

  • pbc (tuple) – a tuple defining the periodic boundary conditions along the three axis of the lattice. If None periodic in all directions.

Returns:

Rhombohedral lattice of dimensions (a x a x a).

scale(new_volume: float) Self[source]

Return a new Lattice with volume new_volume by performing a scaling of the lattice vectors so that length proportions and angles are preserved.

Parameters:

new_volume – New volume to scale to.

Returns:

New lattice with desired volume.

selling_dist(other: Self) float[source]

Get the minimum Selling distance between two lattices.

property selling_vector: ndarray[source]

The (1,6) array of Selling Scalars.

classmethod tetragonal(a: float, c: float, pbc: PbcLike = (True, True, True)) Self[source]

Convenience constructor for a tetragonal lattice.

Parameters:
  • a (float) – a lattice parameter of the tetragonal cell.

  • c (float) – c lattice parameter of the tetragonal cell.

  • pbc (tuple) – The periodic boundary conditions along the three axis of the lattice. If None periodic in all directions.

Returns:

Tetragonal lattice of dimensions (a x a x c).

property volume: float[source]

Volume of the unit cell in Angstrom^3.

find_neighbors(label: ndarray, nx: int, ny: int, nz: int) list[ndarray][source]

Given a cube index, find the neighbor cube indices.

Parameters:
  • label – (array) (n,) or (n x 3) indice array

  • nx – (int) number of cells in y direction

  • ny – (int) number of cells in y direction

  • nz – (int) number of cells in z direction

Returns:

Neighbor cell indices.

get_integer_index(miller_index: MillerIndex, round_dp: int = 4, verbose: bool = True) MillerIndex[source]

Attempt to convert a vector of floats to whole numbers.

Parameters:
  • miller_index (MillerIndex) – Miller index.

  • round_dp (int, optional) – The number of decimal places to round the miller index to.

  • verbose (bool, optional) – Whether to print warnings.

Returns:

The Miller index.

Return type:

MillerIndex

get_points_in_spheres(all_coords: np.ndarray, center_coords: np.ndarray, r: float, pbc: bool | list[bool] | PbcLike = True, numerical_tol: float = 1e-08, lattice: Lattice | None = None, return_fcoords: bool = False) list[list[tuple[np.ndarray, float, int, np.ndarray]]][source]

For each point in center_coords, get all the neighboring points in all_coords that are within the cutoff radius r.

Parameters:
  • all_coords – (list of Cartesian coordinates) all available points

  • center_coords – (list of Cartesian coordinates) all centering points

  • r – (float) cutoff radius

  • pbc – (bool or a list of bool) whether to set periodic boundaries

  • numerical_tol – (float) numerical tolerance

  • lattice – (Lattice) lattice to consider when PBC is enabled

  • return_fcoords – (bool) whether to return fractional coords when pbc is set.

Returns:

List[List[Tuple[coords, distance, index, image]]]

pymatgen.core.libxcfunc module

Enumerator with the libxc identifiers. This is a low level object, client code should not interact with LibxcFunc directly but use the API provided by the Xcfunc object defined in core.xcfunc.py. Part of this module is automatically generated so be careful when refactoring stuff. Use the script ~pymatgen/dev_scripts/regen_libxcfunc.py to regenerate the enum values.

class LibxcFunc(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Enumerator with the identifiers. This object is used by Xcfunc declared in xcfunc.py to create an internal representation of the XC functional. This is a low level object, client code should not interact with LibxcFunc directly but use the API provided by Xcfunc.

Parameters:

_num – Number for the xc.

GGA_C_AM05 = 135[source]
GGA_C_APBE = 186[source]
GGA_C_BGCP = 39[source]
GGA_C_FT97 = 88[source]
GGA_C_GAM = 33[source]
GGA_C_HCTH_A = 97[source]
GGA_C_LM = 137[source]
GGA_C_LYP = 131[source]
GGA_C_N12 = 80[source]
GGA_C_N12_SX = 79[source]
GGA_C_OPTC = 200[source]
GGA_C_OP_B88 = 87[source]
GGA_C_OP_G96 = 85[source]
GGA_C_OP_PBE = 86[source]
GGA_C_OP_PW91 = 262[source]
GGA_C_OP_XALPHA = 84[source]
GGA_C_P86 = 132[source]
GGA_C_PBE = 130[source]
GGA_C_PBEFE = 258[source]
GGA_C_PBEINT = 62[source]
GGA_C_PBELOC = 246[source]
GGA_C_PBE_JRGX = 138[source]
GGA_C_PBE_SOL = 133[source]
GGA_C_PW91 = 134[source]
GGA_C_Q2D = 47[source]
GGA_C_REGTPSS = 83[source]
GGA_C_REVTCA = 99[source]
GGA_C_RGE2 = 143[source]
GGA_C_SOGGA11 = 152[source]
GGA_C_SOGGA11_X = 159[source]
GGA_C_SPBE = 89[source]
GGA_C_TCA = 100[source]
GGA_C_WI = 148[source]
GGA_C_WI0 = 153[source]
GGA_C_WL = 147[source]
GGA_C_XPBE = 136[source]
GGA_C_ZPBEINT = 61[source]
GGA_C_ZPBESOL = 63[source]
GGA_K_ABSP1 = 506[source]
GGA_K_ABSP2 = 507[source]
GGA_K_APBE = 185[source]
GGA_K_APBEINT = 54[source]
GGA_K_BALTIN = 504[source]
GGA_K_DK = 516[source]
GGA_K_ERNZERHOF = 520[source]
GGA_K_FR_B88 = 514[source]
GGA_K_FR_PW86 = 515[source]
GGA_K_GE2 = 501[source]
GGA_K_GOLDEN = 502[source]
GGA_K_GP85 = 510[source]
GGA_K_GR = 508[source]
GGA_K_LC94 = 521[source]
GGA_K_LIEB = 505[source]
GGA_K_LLP = 522[source]
GGA_K_LUDENA = 509[source]
GGA_K_MEYER = 57[source]
GGA_K_OL1 = 512[source]
GGA_K_OL2 = 513[source]
GGA_K_PEARSON = 511[source]
GGA_K_PERDEW = 517[source]
GGA_K_REVAPBE = 55[source]
GGA_K_REVAPBEINT = 53[source]
GGA_K_TFVW = 52[source]
GGA_K_THAKKAR = 523[source]
GGA_K_TW1 = 187[source]
GGA_K_TW2 = 188[source]
GGA_K_TW3 = 189[source]
GGA_K_TW4 = 190[source]
GGA_K_VJKS = 519[source]
GGA_K_VSK = 518[source]
GGA_K_VW = 500[source]
GGA_K_YT65 = 503[source]
GGA_XC_B97_D = 170[source]
GGA_XC_B97_GGA1 = 96[source]
GGA_XC_EDF1 = 165[source]
GGA_XC_HCTH_120 = 162[source]
GGA_XC_HCTH_147 = 163[source]
GGA_XC_HCTH_407 = 164[source]
GGA_XC_HCTH_407P = 93[source]
GGA_XC_HCTH_93 = 161[source]
GGA_XC_HCTH_P14 = 95[source]
GGA_XC_HCTH_P76 = 94[source]
GGA_XC_KT2 = 146[source]
GGA_XC_MOHLYP = 194[source]
GGA_XC_MOHLYP2 = 195[source]
GGA_XC_MPWLYP1W = 174[source]
GGA_XC_OBLYP_D = 67[source]
GGA_XC_OPBE_D = 65[source]
GGA_XC_OPWLYP_D = 66[source]
GGA_XC_PBE1W = 173[source]
GGA_XC_PBELYP1W = 175[source]
GGA_XC_TH1 = 154[source]
GGA_XC_TH2 = 155[source]
GGA_XC_TH3 = 156[source]
GGA_XC_TH4 = 157[source]
GGA_XC_TH_FC = 197[source]
GGA_XC_TH_FCFO = 198[source]
GGA_XC_TH_FCO = 199[source]
GGA_XC_TH_FL = 196[source]
GGA_XC_VV10 = 255[source]
GGA_XC_XLYP = 166[source]
GGA_X_2D_B86 = 128[source]
GGA_X_2D_B86_MGC = 124[source]
GGA_X_2D_B88 = 127[source]
GGA_X_2D_PBE = 129[source]
GGA_X_AIRY = 192[source]
GGA_X_AK13 = 56[source]
GGA_X_AM05 = 120[source]
GGA_X_APBE = 184[source]
GGA_X_B86 = 103[source]
GGA_X_B86_MGC = 105[source]
GGA_X_B86_R = 41[source]
GGA_X_B88 = 106[source]
GGA_X_BAYESIAN = 125[source]
GGA_X_BGCP = 38[source]
GGA_X_BPCCAC = 98[source]
GGA_X_C09X = 158[source]
GGA_X_CAP = 270[source]
GGA_X_DK87_R1 = 111[source]
GGA_X_DK87_R2 = 112[source]
GGA_X_EV93 = 35[source]
GGA_X_FT97_A = 114[source]
GGA_X_FT97_B = 115[source]
GGA_X_G96 = 107[source]
GGA_X_GAM = 32[source]
GGA_X_HCTH_A = 34[source]
GGA_X_HERMAN = 104[source]
GGA_X_HJS_B88 = 527[source]
GGA_X_HJS_B88_V2 = 46[source]
GGA_X_HJS_B97X = 528[source]
GGA_X_HJS_PBE = 525[source]
GGA_X_HJS_PBE_SOL = 526[source]
GGA_X_HTBS = 191[source]
GGA_X_ITYH = 529[source]
GGA_X_KT1 = 145[source]
GGA_X_LAG = 193[source]
GGA_X_LAMBDA_CH_N = 44[source]
GGA_X_LAMBDA_LO_N = 45[source]
GGA_X_LAMBDA_OC2_N = 40[source]
GGA_X_LB = 160[source]
GGA_X_LBM = 182[source]
GGA_X_LG93 = 113[source]
GGA_X_LV_RPW86 = 58[source]
GGA_X_MB88 = 149[source]
GGA_X_MPBE = 122[source]
GGA_X_MPW91 = 119[source]
GGA_X_N12 = 82[source]
GGA_X_OL2 = 183[source]
GGA_X_OPTB88_VDW = 139[source]
GGA_X_OPTPBE_VDW = 141[source]
GGA_X_OPTX = 110[source]
GGA_X_PBE = 101[source]
GGA_X_PBEA = 121[source]
GGA_X_PBEFE = 265[source]
GGA_X_PBEINT = 60[source]
GGA_X_PBEK1_VDW = 140[source]
GGA_X_PBE_JSJR = 126[source]
GGA_X_PBE_MOL = 49[source]
GGA_X_PBE_R = 102[source]
GGA_X_PBE_SOL = 116[source]
GGA_X_PBE_TCA = 59[source]
GGA_X_PW86 = 108[source]
GGA_X_PW91 = 109[source]
GGA_X_Q2D = 48[source]
GGA_X_RGE2 = 142[source]
GGA_X_RPBE = 117[source]
GGA_X_RPW86 = 144[source]
GGA_X_SFAT = 530[source]
GGA_X_SOGGA = 150[source]
GGA_X_SOGGA11 = 151[source]
GGA_X_SSB = 91[source]
GGA_X_SSB_D = 92[source]
GGA_X_SSB_SW = 90[source]
GGA_X_VMT84_GE = 68[source]
GGA_X_VMT84_PBE = 69[source]
GGA_X_VMT_GE = 70[source]
GGA_X_VMT_PBE = 71[source]
GGA_X_WC = 118[source]
GGA_X_WPBEH = 524[source]
GGA_X_XPBE = 123[source]
HYB_GGA_XC_B1LYP = 416[source]
HYB_GGA_XC_B1PW91 = 417[source]
HYB_GGA_XC_B1WC = 412[source]
HYB_GGA_XC_B3LYP = 402[source]
HYB_GGA_XC_B3LYP5 = 475[source]
HYB_GGA_XC_B3LYPs = 459[source]
HYB_GGA_XC_B3P86 = 403[source]
HYB_GGA_XC_B3PW91 = 401[source]
HYB_GGA_XC_B97 = 407[source]
HYB_GGA_XC_B97_1 = 408[source]
HYB_GGA_XC_B97_1p = 266[source]
HYB_GGA_XC_B97_2 = 410[source]
HYB_GGA_XC_B97_3 = 414[source]
HYB_GGA_XC_B97_K = 413[source]
HYB_GGA_XC_BHANDH = 435[source]
HYB_GGA_XC_BHANDHLYP = 436[source]
HYB_GGA_XC_CAMY_B3LYP = 470[source]
HYB_GGA_XC_CAMY_BLYP = 455[source]
HYB_GGA_XC_CAM_B3LYP = 433[source]
HYB_GGA_XC_CAP0 = 477[source]
HYB_GGA_XC_EDF2 = 476[source]
HYB_GGA_XC_HJS_B88 = 431[source]
HYB_GGA_XC_HJS_B97X = 432[source]
HYB_GGA_XC_HJS_PBE = 429[source]
HYB_GGA_XC_HJS_PBE_SOL = 430[source]
HYB_GGA_XC_HPBEINT = 472[source]
HYB_GGA_XC_HSE03 = 427[source]
HYB_GGA_XC_HSE06 = 428[source]
HYB_GGA_XC_LCY_BLYP = 468[source]
HYB_GGA_XC_LCY_PBE = 467[source]
HYB_GGA_XC_LC_VV10 = 469[source]
HYB_GGA_XC_LRC_WPBE = 473[source]
HYB_GGA_XC_LRC_WPBEH = 465[source]
HYB_GGA_XC_MB3LYP_RC04 = 437[source]
HYB_GGA_XC_MPW3LYP = 419[source]
HYB_GGA_XC_MPW3PW = 415[source]
HYB_GGA_XC_MPWLYP1M = 453[source]
HYB_GGA_XC_O3LYP = 404[source]
HYB_GGA_XC_PBE0_13 = 456[source]
HYB_GGA_XC_PBEH = 406[source]
HYB_GGA_XC_REVB3LYP = 454[source]
HYB_GGA_XC_SB98_1a = 420[source]
HYB_GGA_XC_SB98_1b = 421[source]
HYB_GGA_XC_SB98_1c = 422[source]
HYB_GGA_XC_SB98_2a = 423[source]
HYB_GGA_XC_SB98_2b = 424[source]
HYB_GGA_XC_SB98_2c = 425[source]
HYB_GGA_XC_TUNED_CAM_B3LYP = 434[source]
HYB_GGA_XC_WB97 = 463[source]
HYB_GGA_XC_WB97X = 464[source]
HYB_GGA_XC_WB97X_D = 471[source]
HYB_GGA_XC_WB97X_V = 466[source]
HYB_GGA_XC_X3LYP = 411[source]
HYB_GGA_XC_mPW1K = 405[source]
HYB_GGA_XC_mPW1PW = 418[source]
HYB_GGA_X_N12_SX = 81[source]
HYB_GGA_X_SOGGA11_X = 426[source]
HYB_MGGA_XC_B86B95 = 441[source]
HYB_MGGA_XC_B88B95 = 440[source]
HYB_MGGA_XC_BB1K = 443[source]
HYB_MGGA_XC_M05 = 438[source]
HYB_MGGA_XC_M05_2X = 439[source]
HYB_MGGA_XC_M06 = 449[source]
HYB_MGGA_XC_M06_2X = 450[source]
HYB_MGGA_XC_M06_HF = 444[source]
HYB_MGGA_XC_M08_HX = 460[source]
HYB_MGGA_XC_M08_SO = 461[source]
HYB_MGGA_XC_M11 = 462[source]
HYB_MGGA_XC_MPW1B95 = 445[source]
HYB_MGGA_XC_MPWB1K = 446[source]
HYB_MGGA_XC_PW6B95 = 451[source]
HYB_MGGA_XC_PW86B95 = 442[source]
HYB_MGGA_XC_PWB6K = 452[source]
HYB_MGGA_XC_REVTPSSH = 458[source]
HYB_MGGA_XC_TPSSH = 457[source]
HYB_MGGA_XC_WB97M_V = 531[source]
HYB_MGGA_XC_X1B95 = 447[source]
HYB_MGGA_XC_XB1K = 448[source]
HYB_MGGA_X_DLDF = 36[source]
HYB_MGGA_X_MN12_SX = 248[source]
HYB_MGGA_X_MN15 = 268[source]
HYB_MGGA_X_MS2H = 224[source]
HYB_MGGA_X_MVSH = 474[source]
HYB_MGGA_X_SCAN0 = 264[source]
LDA_C_1D_CSC = 18[source]
LDA_C_1D_LOOS = 26[source]
LDA_C_2D_AMGB = 15[source]
LDA_C_2D_PRM = 16[source]
LDA_C_GL = 5[source]
LDA_C_GOMBAS = 24[source]
LDA_C_HL = 4[source]
LDA_C_ML1 = 22[source]
LDA_C_ML2 = 23[source]
LDA_C_OB_PW = 14[source]
LDA_C_OB_PZ = 11[source]
LDA_C_PW = 12[source]
LDA_C_PW_MOD = 13[source]
LDA_C_PW_RPA = 25[source]
LDA_C_PZ = 9[source]
LDA_C_PZ_MOD = 10[source]
LDA_C_RC04 = 27[source]
LDA_C_RPA = 3[source]
LDA_C_VWN = 7[source]
LDA_C_VWN_1 = 28[source]
LDA_C_VWN_2 = 29[source]
LDA_C_VWN_3 = 30[source]
LDA_C_VWN_4 = 31[source]
LDA_C_VWN_RPA = 8[source]
LDA_C_WIGNER = 2[source]
LDA_C_XALPHA = 6[source]
LDA_C_vBH = 17[source]
LDA_K_LP = 51[source]
LDA_K_TF = 50[source]
LDA_X = 1[source]
LDA_XC_KSDT = 259[source]
LDA_XC_TETER93 = 20[source]
LDA_XC_ZLP = 43[source]
LDA_X_1D = 21[source]
LDA_X_2D = 19[source]
MGGA_C_BC95 = 240[source]
MGGA_C_CC06 = 229[source]
MGGA_C_CS = 72[source]
MGGA_C_DLDF = 37[source]
MGGA_C_M05 = 237[source]
MGGA_C_M05_2X = 238[source]
MGGA_C_M06 = 235[source]
MGGA_C_M06_2X = 236[source]
MGGA_C_M06_HF = 234[source]
MGGA_C_M06_L = 233[source]
MGGA_C_M08_HX = 78[source]
MGGA_C_M08_SO = 77[source]
MGGA_C_M11 = 76[source]
MGGA_C_M11_L = 75[source]
MGGA_C_MN12_L = 74[source]
MGGA_C_MN12_SX = 73[source]
MGGA_C_MN15 = 269[source]
MGGA_C_MN15_L = 261[source]
MGGA_C_PKZB = 239[source]
MGGA_C_REVTPSS = 241[source]
MGGA_C_SCAN = 267[source]
MGGA_C_TPSS = 231[source]
MGGA_C_TPSSLOC = 247[source]
MGGA_C_VSXC = 232[source]
MGGA_XC_B97M_V = 254[source]
MGGA_XC_OTPSS_D = 64[source]
MGGA_XC_TPSSLYP1W = 242[source]
MGGA_XC_ZLP = 42[source]
MGGA_X_2D_PRHG07 = 210[source]
MGGA_X_2D_PRHG07_PRP10 = 211[source]
MGGA_X_BJ06 = 207[source]
MGGA_X_BLOC = 244[source]
MGGA_X_BR89 = 206[source]
MGGA_X_GVT4 = 204[source]
MGGA_X_LTA = 201[source]
MGGA_X_M05 = 214[source]
MGGA_X_M05_2X = 215[source]
MGGA_X_M06 = 217[source]
MGGA_X_M06_2X = 218[source]
MGGA_X_M06_HF = 216[source]
MGGA_X_M06_L = 203[source]
MGGA_X_M08_HX = 219[source]
MGGA_X_M08_SO = 220[source]
MGGA_X_M11 = 225[source]
MGGA_X_M11_L = 226[source]
MGGA_X_MBEEF = 249[source]
MGGA_X_MBEEFVDW = 250[source]
MGGA_X_MK00 = 230[source]
MGGA_X_MK00B = 243[source]
MGGA_X_MN12_L = 227[source]
MGGA_X_MN15_L = 260[source]
MGGA_X_MODTPSS = 245[source]
MGGA_X_MS0 = 221[source]
MGGA_X_MS1 = 222[source]
MGGA_X_MS2 = 223[source]
MGGA_X_MVS = 257[source]
MGGA_X_PKZB = 213[source]
MGGA_X_REVTPSS = 212[source]
MGGA_X_RPP09 = 209[source]
MGGA_X_SCAN = 263[source]
MGGA_X_TAU_HCTH = 205[source]
MGGA_X_TB09 = 208[source]
MGGA_X_TPSS = 202[source]
static all_families()[source]

List of strings with the libxc families. Note that XC_FAMILY if removed from the string e.g. XC_FAMILY_LDA becomes LDA.

static all_kinds()[source]

List of strings with the libxc kinds. Also in this case, the string is obtained by remove the XC_ prefix. XC_CORRELATION –> CORRELATION.

as_dict() dict[source]

Serialize to MSONable dict representation, e.g. to write to disk as JSON.

classmethod from_dict(dct: dict) Self[source]

Deserialize from MSONable dict representation.

property info_dict[source]

Dictionary with metadata. see libxc_docs.json.

property is_c_kind: bool[source]

True if this is a correlation-only functional.

property is_gga_family: bool[source]

True if this functional belongs to the GGA family.

property is_hyb_gga_family: bool[source]

True if this functional belongs to the hybrid + GGA family.

property is_hyb_mgga_family: bool[source]

True if this functional belongs to the hybrid + meta-GGA family.

property is_k_kind: bool[source]

True if this is a kinetic functional.

property is_lda_family: bool[source]

True if this functional belongs to the LDA family.

property is_mgga_family: bool[source]

True if this functional belongs to the meta-GGA family.

property is_x_kind: bool[source]

True if this is an exchange-only functional.

property is_xc_kind: bool[source]

True if this is a exchange+correlation functional.

to_json() str[source]

Get a JSON string representation of the LibxcFunc.

pymatgen.core.molecular_orbitals module

This module implements a MolecularOrbital class to represent band character in solids. Useful for predicting PDOS character from structural information.

class MolecularOrbitals(formula: str)[source]

Bases: object

Represents the character of bands in a solid. The input is a chemical formula, since no structural characteristics are taken into account.

The band character of a crystal emerges from the atomic orbitals of the constituent ions, hybridization/covalent bonds, and the spin-orbit interaction (ex: Fe2O3). Right now the orbitals are only built from the uncharged atomic species. Functionality can be improved by: 1) calculate charged ion orbital energies 2) incorporate the coordination environment to account for covalent bonds

The atomic orbital energies are stored in pymatgen.core.periodic_table.JSON

MOs = MolecularOrbitals(‘SrTiO3’) MOs.band_edges # gives {‘HOMO’:[‘O’,’2p’,-0.338381], ‘LUMO’:[‘Ti’,’3d’,-0.17001], ‘metal’:False}

Parameters:

formula (str) – Chemical formula. Must have integer subscripts. Ex: ‘SrTiO3’.

composition[source]

the composition as a dictionary. Ex: {‘Sr’: 1, ‘Ti’: 1, ‘O’, 3}

elements[source]

the dictionary keys for the composition

elec_neg[source]

the maximum pairwise electronegativity difference

aos[source]

the constituent atomic orbitals for each element as a dictionary

band_edges[source]

dictionary containing the highest occupied molecular orbital (HOMO), lowest unoccupied molecular orbital (LUMO), and whether the material is predicted to be a metal

aos_as_list() list[tuple[str, str, float]][source]

The orbitals energies in eV are represented as [[‘O’, ‘1s’, -18.758245], [‘O’, ‘2s’, -0.871362], [‘O’, ‘2p’, -0.338381]] Data is obtained from https://www.nist.gov/pml/data/atomic-reference-data-electronic-structure-calculations.

Returns:

A list of atomic orbitals, sorted from lowest to highest energy.

max_electronegativity() float[source]
Returns:

The maximum pairwise electronegativity difference.

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

Fill up the atomic orbitals with available electrons.

Returns:

HOMO, LUMO, and whether it’s a metal.

pymatgen.core.operations module

This module provides classes that operate on points or vectors in 3D space.

class MagSymmOp(affine_transformation_matrix: ArrayLike, time_reversal: Literal[-1, 1], tol: float = 0.01)[source]

Bases: SymmOp

Thin wrapper around SymmOp to extend it to support magnetic symmetry by including a time reversal operator. Magnetic symmetry is similar to conventional crystal symmetry, except symmetry is reduced by the addition of a time reversal operator which acts on an atom’s magnetic moment.

Initialize the MagSymmOp from a 4x4 affine transformation matrix and time reversal operator. In general, this constructor should not be used unless you are transferring rotations. Use the static constructors instead to generate a SymmOp from proper rotations and translation.

Parameters:
  • affine_transformation_matrix (4x4 array) – Representing an affine transformation.

  • time_reversal (int) – 1 or -1

  • tol (float) – Tolerance for determining if matrices are equal.

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

MSONable dict.

as_xyzt_str() str[source]

Get a string of the form ‘x, y, z, +1’, ‘-x, -y, z, -1’, ‘-y+1/2, x+1/2, z+1/2, +1’, etc. Only works for integer rotation matrices.

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

dct – dict.

Returns:

MagneticSymmOp from dict representation.

static from_rotation_and_translation_and_time_reversal(rotation_matrix: ArrayLike = ((1, 0, 0), (0, 1, 0), (0, 0, 1)), translation_vec: ArrayLike = (0, 0, 0), time_reversal: Literal[-1, 1] = 1, tol: float = 0.1) MagSymmOp[source]

Create a symmetry operation from a rotation matrix, translation vector and time reversal operator.

Parameters:
  • rotation_matrix (3x3 array) – Rotation matrix.

  • translation_vec (3x1 array) – Translation vector.

  • time_reversal (int) – Time reversal operator, +1 or -1.

  • tol (float) – Tolerance to determine if rotation matrix is valid.

Returns:

MagSymmOp object

classmethod from_symmop(symmop: SymmOp, time_reversal: Literal[-1, 1]) Self[source]

Initialize a MagSymmOp from a SymmOp and time reversal operator.

Parameters:
  • symmop (SymmOp) – SymmOp

  • time_reversal (int) – Time reversal operator, +1 or -1.

Returns:

MagSymmOp object

classmethod from_xyzt_str(xyzt_str: str) Self[source]
Parameters:

xyzt_str (str) – of the form ‘x, y, z, +1’, ‘-x, -y, z, -1’, ‘-2y+1/2, 3x+1/2, z-y+1/2, +1’, etc.

Returns:

MagSymmOp object

operate_magmom(magmom: Magmom) Magmom[source]

Apply time reversal operator on the magnetic moment. Note that magnetic moments transform as axial vectors, not polar vectors.

See ‘Symmetry and magnetic structures’, Rodríguez-Carvajal and Bourée for a good discussion. DOI: 10.1051/epjconf/20122200010

Parameters:
  • magmom – Magnetic moment as electronic_structure.core.Magmom

  • array-like (class or as list or np)

Returns:

Magnetic moment after operator applied as Magmom class

class SymmOp(affine_transformation_matrix: ArrayLike, tol: float = 0.01)[source]

Bases: MSONable

A symmetry operation in Cartesian space. Consists of a rotation plus a translation. Implementation is as an affine transformation matrix of rank 4 for efficiency. Read: https://wikipedia.org/wiki/Affine_transformation.

affine_matrix[source]

A 4x4 array representing the symmetry operation.

Type:

np.ndarray

Initialize the SymmOp from a 4x4 affine transformation matrix. In general, this constructor should not be used unless you are transferring rotations. Use the static constructors instead to generate a SymmOp from proper rotations and translation.

Parameters:
  • affine_transformation_matrix (4x4 array) – Representing an affine transformation.

  • tol (float) – Tolerance for determining if matrices are equal. Defaults to 0.01.

Raises:

ValueError – if matrix is not 4x4.

apply_rotation_only(vector: ArrayLike) np.ndarray[source]

Vectors should only be operated by the rotation matrix and not the translation vector.

Parameters:

vector (3x1 array) – A vector.

Check if two points are symmetrically related.

Parameters:
  • point_a (3x1 array) – First point.

  • point_b (3x1 array) – Second point.

  • tol (float) – Absolute tolerance for checking distance. Defaults to 0.001.

Returns:

True if self.operate(point_a) == point_b or vice versa.

Return type:

bool

Check if two vectors, or rather two vectors that connect two points each are symmetrically related. r_a and r_b give the change of unit cells. Two vectors are also considered symmetrically equivalent if starting and end point are exchanged.

Parameters:
  • from_a (3x1 array) – Starting point of the first vector.

  • to_a (3x1 array) – Ending point of the first vector.

  • from_b (3x1 array) – Starting point of the second vector.

  • to_b (3x1 array) – Ending point of the second vector.

  • r_a (3x1 array) – Change of unit cell of the first vector.

  • r_b (3x1 array) – Change of unit cell of the second vector.

  • tol (float) – Absolute tolerance for checking distance.

Returns:

First bool indicates if the vectors are related,

the second if the vectors are related but the starting and end point are exchanged.

Return type:

tuple[bool, bool]

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

MSONable dict.

as_xyz_str() str[source]

Get a string of the form ‘x, y, z’, ‘-x, -y, z’, ‘-y+1/2, x+1/2, z+1/2’, etc. Only works for integer rotation matrices.

static from_axis_angle_and_translation(axis: ArrayLike, angle: float, angle_in_radians: bool = False, translation_vec: ArrayLike = (0, 0, 0)) SymmOp[source]

Generate a SymmOp for a rotation about a given axis plus translation.

Parameters:
  • axis – The axis of rotation in Cartesian space. For example, [1, 0, 0]indicates rotation about x-axis.

  • angle (float) – Angle of rotation.

  • angle_in_radians (bool) – Set to True if angles are given in radians. Or else, units of degrees are assumed.

  • translation_vec – A translation vector. Defaults to zero.

Returns:

SymmOp for a rotation about given axis and translation.

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

dct – dict.

Returns:

SymmOp from dict representation.

static from_origin_axis_angle(origin: ArrayLike, axis: ArrayLike, angle: float, angle_in_radians: bool = False) SymmOp[source]

Generate a SymmOp for a rotation about a given axis through an origin.

Parameters:
  • origin (3x1 array) – The origin which the axis passes through.

  • axis (3x1 array) – The axis of rotation in Cartesian space. For example, [1, 0, 0]indicates rotation about x-axis.

  • angle (float) – Angle of rotation.

  • angle_in_radians (bool) – Set to True if angles are given in radians. Or else, units of degrees are assumed.

Returns:

SymmOp.

classmethod from_rotation_and_translation(rotation_matrix: ArrayLike = ((1, 0, 0), (0, 1, 0), (0, 0, 1)), translation_vec: ArrayLike = (0, 0, 0), tol: float = 0.1) Self[source]

Create a symmetry operation from a rotation matrix and a translation vector.

Parameters:
  • rotation_matrix (3x3 array) – Rotation matrix.

  • translation_vec (3x1 array) – Translation vector.

  • tol (float) – Tolerance to determine if rotation matrix is valid.

Returns:

SymmOp object

classmethod from_xyz_str(xyz_str: str) Self[source]
Parameters:

xyz_str – string of the form ‘x, y, z’, ‘-x, -y, z’, ‘-2y+1/2, 3x+1/2, z-y+1/2’, etc.

Returns:

SymmOp

property inverse: Self[source]

Inverse of transformation.

static inversion(origin: ArrayLike = (0, 0, 0)) SymmOp[source]

Inversion symmetry operation about axis.

Parameters:

origin (3x1 array) – Origin of the inversion operation. Defaults to [0, 0, 0].

Returns:

SymmOp representing an inversion operation about the origin.

operate(point: ArrayLike) np.ndarray[source]

Apply the operation on a point.

Parameters:

point – Cartesian coordinate.

Returns:

Coordinates of point after operation.

operate_multi(points: ArrayLike) np.ndarray[source]

Apply the operation on a list of points.

Parameters:

points – List of Cartesian coordinates

Returns:

Numpy array of coordinates after operation

static reflection(normal: ArrayLike, origin: ArrayLike = (0, 0, 0)) SymmOp[source]

Get reflection symmetry operation.

Parameters:
  • normal (3x1 array) – Vector of the normal to the plane of reflection.

  • origin (3x1 array) – A point in which the mirror plane passes through.

Returns:

SymmOp for the reflection about the plane

property rotation_matrix: ndarray[source]

A 3x3 numpy.array representing the rotation matrix.

static rotoreflection(axis: ArrayLike, angle: float, origin: ArrayLike = (0, 0, 0)) SymmOp[source]

Get a roto-reflection symmetry operation.

Parameters:
  • axis (3x1 array) – Axis of rotation / mirror normal

  • angle (float) – Angle in degrees

  • origin (3x1 array) – Point left invariant by roto-reflection. Defaults to (0, 0, 0).

Returns:

Roto-reflection operation

transform_tensor(tensor: ndarray) ndarray[source]

Apply rotation portion to a tensor. Note that tensor has to be in full form, not the Voigt form.

Parameters:

tensor (numpy array) – A rank n tensor

Returns:

Transformed tensor.

property translation_vector: ndarray[source]

A rank 1 numpy.array of dim 3 representing the translation vector.

pymatgen.core.periodic_table module

Classes representing: - Element: Element in the periodic table. - Species: Element with optional oxidation state and spin. - DummySpecies: Non-traditional Elements/Species (vacancies/…). - ElementType: element types (metal/noble_gas/halogen/s_block/…).

class DummySpecie(symbol: str = 'X', oxidation_state: float | None = 0, spin: float | None = None)[source]

Bases: DummySpecies

This maps the historical grammatically inaccurate DummySpecie to DummySpecies to maintain backwards compatibility.

Parameters:
  • symbol (str) – An assigned symbol for the dummy specie. Strict rules are applied to the choice of the symbol. The dummy symbol cannot have any part of first two letters that will constitute an Element symbol. Otherwise, a composition may be parsed wrongly. e.g. “X” is fine, but “Vac” is not because Vac contains V, a valid Element.

  • oxidation_state (float) – Oxidation state for dummy specie. Defaults to 0. deprecated and retained purely for backward compatibility.

  • spin – Spin associated with Species. Defaults to None.

class DummySpecies(symbol: str = 'X', oxidation_state: float | None = 0, spin: float | None = None)[source]

Bases: Species

A special specie for representing non-traditional elements or species. For example, representation of vacancies (charged or otherwise), or special sites, etc.

oxi_state[source]

Oxidation state associated with Species.

Type:

int

Z[source]

DummySpecies is always assigned an atomic number equal to the hash number of the symbol. Obviously, it makes no sense whatsoever to use the atomic number of a Dummy specie for anything scientific. The purpose of this is to ensure that for most use cases, a DummySpecies behaves no differently from an Element or Species.

Type:

int

A[source]

Just as for Z, to get a DummySpecies to behave like an Element, it needs atomic mass number A (arbitrarily set to twice Z).

Type:

int

X[source]

DummySpecies is always assigned a Pauling electronegativity of 0.

Type:

float

Parameters:
  • symbol (str) – An assigned symbol for the dummy specie. Strict rules are applied to the choice of the symbol. The dummy symbol cannot have any part of first two letters that will constitute an Element symbol. Otherwise, a composition may be parsed wrongly. e.g. “X” is fine, but “Vac” is not because Vac contains V, a valid Element.

  • oxidation_state (float) – Oxidation state for dummy specie. Defaults to 0. deprecated and retained purely for backward compatibility.

  • spin – Spin associated with Species. Defaults to None.

property A: int | None[source]

Atomic mass number of a DummySpecies.

To behave like an ElementBase object (from which Species inherits), DummySpecies needs an atomic mass number. Consistent with the implementation for ElementBase, this can return an int or None (default).

property X: float[source]

DummySpecies is always assigned a Pauling electronegativity of 0. The effect of this is that DummySpecies are always sorted in front of actual Species.

property Z: int[source]

Proton number of DummySpecies.

DummySpecies is always assigned an atomic number equal to the hash of the symbol. This is necessary for the DummySpecies object to behave like an ElementBase object (which Species inherits from).

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

MSONable dict representation.

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

dct (dict) – Dict representation.

Returns:

DummySpecies

classmethod from_str(species_string: str) Self[source]

Get a Dummy from a string representation.

Parameters:

species_string (str) – A string representation of a dummy species, e.g. “X2+”, “X3+”.

Returns:

A DummySpecies object.

Raises:

ValueError if species_string cannot be interpreted.

property oxi_state: float | None[source]

Oxidation state associated with DummySpecies.

property symbol: str[source]

Symbol for DummySpecies.

class Element(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: ElementBase

Enum representing an element in the periodic table.

This class provides a basic, immutable representation of an element, including all relevant chemical and physical properties. It ensures that elements are handled as singletons, reducing redundancy and improving efficiency. Missing data is represented by None unless otherwise specified.

Z[source]

Atomic number of the element.

Type:

int

symbol[source]

Element symbol (e.g., “H”, “Fe”).

Type:

str

long_name[source]

Full name of the element (e.g., “Hydrogen”).

Type:

str

A[source]

Atomic mass number (sum of protons and neutrons).

Type:

int, optional

atomic_radius_calculated[source]

Calculated atomic radius (Å).

Type:

float, optional

van_der_waals_radius[source]

Van der Waals radius (Å).

Type:

float, optional

mendeleev_no[source]

Mendeleev number based on crystal-structure maps.

Type:

int, optional

electrical_resistivity[source]

Electrical resistivity (Ω·m).

Type:

float, optional

velocity_of_sound[source]

Velocity of sound (m/s).

Type:

float, optional

reflectivity[source]

Reflectivity (%).

Type:

float, optional

refractive_index[source]

Refractive index.

Type:

float, optional

poissons_ratio[source]

Poisson’s ratio.

Type:

float, optional

molar_volume[source]

Molar volume (cm³/mol).

Type:

float, optional

electronic_structure[source]

Electronic structure (e.g., “[Ar].3d6.4s2”).

Type:

str

atomic_orbitals[source]

Orbital energies (Hartree units).

Type:

dict

atomic_orbitals_eV[source]

Orbital energies in electron volts (eV).

Type:

dict

thermal_conductivity[source]

Thermal conductivity (W/m·K).

Type:

float, optional

boiling_point[source]

Boiling point (K).

Type:

float, optional

melting_point[source]

Melting point (K).

Type:

float, optional

critical_temperature[source]

Critical temperature (K).

Type:

float, optional

superconduction_temperature[source]

Superconducting transition temperature (K).

Type:

float, optional

liquid_range[source]

Temperature range for liquid phase (K).

Type:

float, optional

bulk_modulus[source]

Bulk modulus (GPa).

Type:

float, optional

youngs_modulus[source]

Young’s modulus (GPa).

Type:

float, optional

brinell_hardness[source]

Brinell hardness (MPa).

Type:

float, optional

rigidity_modulus[source]

Rigidity modulus (GPa).

Type:

float, optional

mineral_hardness[source]

Mohs hardness.

Type:

float, optional

vickers_hardness[source]

Vickers hardness (MPa).

Type:

float, optional

density_of_solid[source]

Density in solid phase (g/cm³).

Type:

float, optional

coefficient_of_linear_thermal_expansion[source]

Thermal expansion coefficient (K⁻¹).

Type:

float, optional

ground_level[source]

Ground energy level of the element.

Type:

float, optional

ionization_energies[source]

Ionization energies (kJ/mol), indexed from 0.

Type:

list[Optional[float]]

Examples

Create an element instance and access its properties:
>>> hydrogen = Element("H")
>>> hydrogen.symbol
'H'
>>> hydrogen.Z
1
>>> hydrogen.electronic_structure
'1s1'
Access additional attributes such as atomic radius:
>>> hydrogen.atomic_radius_calculated
0.53

Notes

  • This class supports handling of isotopes by incorporating named isotopes

and their respective properties. - Attributes are populated using a JSON file that stores data about all known elements. - Some attributes are calculated or derived based on predefined constants and rules.

References

Solid State Communications, 1984.

Ac = 'Ac'[source]
Ag = 'Ag'[source]
Al = 'Al'[source]
Am = 'Am'[source]
Ar = 'Ar'[source]
As = 'As'[source]
At = 'At'[source]
Au = 'Au'[source]
B = 'B'[source]
Ba = 'Ba'[source]
Be = 'Be'[source]
Bh = 'Bh'[source]
Bi = 'Bi'[source]
Bk = 'Bk'[source]
Br = 'Br'[source]
C = 'C'[source]
Ca = 'Ca'[source]
Cd = 'Cd'[source]
Ce = 'Ce'[source]
Cf = 'Cf'[source]
Cl = 'Cl'[source]
Cm = 'Cm'[source]
Cn = 'Cn'[source]
Co = 'Co'[source]
Cr = 'Cr'[source]
Cs = 'Cs'[source]
Cu = 'Cu'[source]
D = 'D'[source]
Db = 'Db'[source]
Ds = 'Ds'[source]
Dy = 'Dy'[source]
Er = 'Er'[source]
Es = 'Es'[source]
Eu = 'Eu'[source]
F = 'F'[source]
Fe = 'Fe'[source]
Fl = 'Fl'[source]
Fm = 'Fm'[source]
Fr = 'Fr'[source]
Ga = 'Ga'[source]
Gd = 'Gd'[source]
Ge = 'Ge'[source]
H = 'H'[source]
He = 'He'[source]
Hf = 'Hf'[source]
Hg = 'Hg'[source]
Ho = 'Ho'[source]
Hs = 'Hs'[source]
I = 'I'[source]
In = 'In'[source]
Ir = 'Ir'[source]
K = 'K'[source]
Kr = 'Kr'[source]
La = 'La'[source]
Li = 'Li'[source]
Lr = 'Lr'[source]
Lu = 'Lu'[source]
Lv = 'Lv'[source]
Mc = 'Mc'[source]
Md = 'Md'[source]
Mg = 'Mg'[source]
Mn = 'Mn'[source]
Mo = 'Mo'[source]
Mt = 'Mt'[source]
N = 'N'[source]
Na = 'Na'[source]
Nb = 'Nb'[source]
Nd = 'Nd'[source]
Ne = 'Ne'[source]
Nh = 'Nh'[source]
Ni = 'Ni'[source]
No = 'No'[source]
Np = 'Np'[source]
O = 'O'[source]
Og = 'Og'[source]
Os = 'Os'[source]
P = 'P'[source]
Pa = 'Pa'[source]
Pb = 'Pb'[source]
Pd = 'Pd'[source]
Pm = 'Pm'[source]
Po = 'Po'[source]
Pr = 'Pr'[source]
Pt = 'Pt'[source]
Pu = 'Pu'[source]
Ra = 'Ra'[source]
Rb = 'Rb'[source]
Re = 'Re'[source]
Rf = 'Rf'[source]
Rg = 'Rg'[source]
Rh = 'Rh'[source]
Rn = 'Rn'[source]
Ru =