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, which is essentially a {element:amount} mapping type. Composition is written to be immutable and hashable, unlike a standard Python dict.

Note that the key can be either an Element or a Species. Elements and Species are treated differently. i.e., a Fe2+ is not the same as a Fe3+ Species and would be put in separate keys. This differentiation is deliberate to support using Composition to determine the fraction of a particular Species.

Works almost completely like a standard python dictionary, except that __getitem__ is overridden to return 0 when an element is not found. (somewhat like a defaultdict, except it is immutable).

Also adds more convenience methods relevant to compositions, e.g. get_fraction.

It should also be noted that many Composition related functionality takes in a standard string as a convenient input. For example, even though the internal representation of a Fe2O3 composition is {Element(“Fe”): 2, Element(“O”): 3}, you can obtain the amount of Fe simply by comp[“Fe”] instead of the more verbose comp[Element(“Fe”)].

>>> 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

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]) 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.

Returns:

Composition

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[str, Any][source]

Returns: A dict with many keys and values relating to Composition/Formula, including reduced_cell_composition, unit_cell_composition, reduced_cell_formula, elements and 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] with weight fraction of each component {“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, Species (Element + oxidation state) and PeriodicTable.

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.

Basic immutable element object with all relevant properties.

Only one instance of Element for each symbol is stored after creation, ensuring that a particular element behaves like a singleton. For all attributes, missing data (i.e., data for which is not available) is represented by a None unless otherwise stated.

Parameters:

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

Z[source]

Atomic number.

Type:

int

symbol[source]

Element symbol.

Type:

str

long_name[source]

Long name for element. e.g. “Hydrogen”.

Type:

str

A[source]

Atomic mass number (number of protons plus neutrons).

Type:

int

atomic_radius_calculated[source]

Calculated atomic radius for the element. This is the empirical value. Data is obtained from https://wikipedia.org/wiki/Atomic_radii_of_the_elements_(data_page).

Type:

float

van_der_waals_radius[source]

Van der Waals radius for the element. This is the empirical value determined from critical reviews of X-ray diffraction, gas kinetic collision cross-section, and other experimental data by Bondi and later workers. The uncertainty in these values is on the order of 0.1 Å. Data are obtained from “Atomic Radii of the Elements” in CRC Handbook of Chemistry and Physics, 91st Ed.; Haynes, W.M., Ed.; CRC Press: Boca Raton, FL, 2010.

Type:

float

mendeleev_no[source]

Mendeleev number from definition given by Pettifor, D. G. (1984). A chemical scale for crystal-structure maps. Solid State Communications, 51 (1), 31-34.

Type:

int

electrical_resistivity[source]

Electrical resistivity.

Type:

float

velocity_of_sound[source]

Velocity of sound.

Type:

float

reflectivity[source]

Reflectivity.

Type:

float

refractive_index[source]

Refractive index.

Type:

float

poissons_ratio[source]

Poisson’s ratio.

Type:

float

molar_volume[source]

Molar volume.

Type:

float

electronic_structure[source]

Electronic structure. e.g. The electronic structure for Fe is represented as [Ar].3d6.4s2.

Type:

str

atomic_orbitals[source]

Atomic Orbitals. Energy of the atomic orbitals as a dict. e.g. The orbitals energies in Hartree are represented as {‘1s’: -1.0, ‘2s’: -0.1}. Data is obtained from https://www.nist.gov/pml/data/atomic-reference-data-electronic-structure-calculations. The LDA values for neutral atoms are used.

Type:

dict

atomic_orbitals_eV[source]

Atomic Orbitals. Same as atomic_orbitals but energies are in eV.

Type:

dict

thermal_conductivity[source]

Thermal conductivity.

Type:

float

boiling_point[source]

Boiling point.

Type:

float

melting_point[source]

Melting point.

Type:

float

critical_temperature[source]

Critical temperature.

Type:

float

superconduction_temperature[source]

Superconduction temperature.

Type:

float

liquid_range[source]

Liquid range.

Type:

float

bulk_modulus[source]

Bulk modulus.

Type:

float

youngs_modulus[source]

Young’s modulus.

Type:

float

brinell_hardness[source]

Brinell hardness.

Type:

float

rigidity_modulus[source]

Rigidity modulus.

Type:

float

mineral_hardness[source]

Mineral hardness.

Type:

float

vickers_hardness[source]

Vicker’s hardness.

Type:

float

density_of_solid[source]

Density of solid phase.

Type:

float

coefficient_of_linear_thermal_expansion[source]

Coefficient of linear thermal expansion.

Type:

float

ground_level[source]

Ground level for element.

Type:

float

ionization_energies[source]

List of ionization energies. First value is the first ionization energy, second is the second ionization energy, etc. Note that this is zero-based indexing! So Element.ionization_energies[0] refer to the 1st ionization energy. Values are from the NIST Atomic Spectra Database. Missing values are None.

Type:

list[Optional[float]]

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 = 'Ru'[source]
S = 'S'[source]
Sb = 'Sb'[source]
Sc = 'Sc'[source]
Se = 'Se'[source]
Sg = 'Sg'[source]
Si = 'Si'[source]
Sm = 'Sm'[source]
Sn = 'Sn'[source]
Sr = 'Sr'[source]
T = 'T'[source]
Ta = 'Ta'[source]
Tb = 'Tb'[source]
Tc = 'Tc'[source]
Te = 'Te'[source]
Th = 'Th'[source]
Ti = 'Ti'[source]
Tl = 'Tl'[source]
Tm = 'Tm'[source]
Ts = 'Ts'[source]
U = 'U'[source]
V = 'V'[source]
W = 'W'[source]
Xe = 'Xe'[source]
Y = 'Y'[source]
Yb = 'Yb'[source]
Zn = 'Zn'[source]
Zr = 'Zr'[source]
class ElementBase(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Element class defined without any enum values so it can be subclassed.

This class is needed to get nested (as|from)_dict to work properly. All emmet classes that had Element classes required custom construction whereas this definition behaves more like dataclasses so serialization is less troublesome. There were many times where objects in as_dict serialized only when they were top level. See https://github.com/materialsproject/pymatgen/issues/2999.

Basic immutable element object with all relevant properties.

Only one instance of Element for each symbol is stored after creation, ensuring that a particular element behaves like a singleton. For all attributes, missing data (i.e., data for which is not available) is represented by a None unless otherwise stated.

Parameters:

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

Z[source]

Atomic number.

Type:

int

symbol[source]

Element symbol.

Type:

str

long_name[source]

Long name for element. e.g. “Hydrogen”.

Type:

str

A[source]

Atomic mass number (number of protons plus neutrons).

Type:

int

atomic_radius_calculated[source]

Calculated atomic radius for the element. This is the empirical value. Data is obtained from https://wikipedia.org/wiki/Atomic_radii_of_the_elements_(data_page).

Type:

float

van_der_waals_radius[source]

Van der Waals radius for the element. This is the empirical value determined from critical reviews of X-ray diffraction, gas kinetic collision cross-section, and other experimental data by Bondi and later workers. The uncertainty in these values is on the order of 0.1 Å. Data are obtained from “Atomic Radii of the Elements” in CRC Handbook of Chemistry and Physics, 91st Ed.; Haynes, W.M., Ed.; CRC Press: Boca Raton, FL, 2010.

Type:

float

mendeleev_no[source]

Mendeleev number from definition given by Pettifor, D. G. (1984). A chemical scale for crystal-structure maps. Solid State Communications, 51 (1), 31-34.

Type:

int

electrical_resistivity[source]

Electrical resistivity.

Type:

float

velocity_of_sound[source]

Velocity of sound.

Type:

float

reflectivity[source]

Reflectivity.

Type:

float

refractive_index[source]

Refractive index.

Type:

float

poissons_ratio[source]

Poisson’s ratio.

Type:

float

molar_volume[source]

Molar volume.

Type:

float

electronic_structure[source]

Electronic structure. e.g. The electronic structure for Fe is represented as [Ar].3d6.4s2.

Type:

str

atomic_orbitals[source]

Atomic Orbitals. Energy of the atomic orbitals as a dict. e.g. The orbitals energies in Hartree are represented as {‘1s’: -1.0, ‘2s’: -0.1}. Data is obtained from https://www.nist.gov/pml/data/atomic-reference-data-electronic-structure-calculations. The LDA values for neutral atoms are used.

Type:

dict

atomic_orbitals_eV[source]

Atomic Orbitals. Same as atomic_orbitals but energies are in eV.

Type:

dict

thermal_conductivity[source]

Thermal conductivity.

Type:

float

boiling_point[source]

Boiling point.

Type:

float

melting_point[source]

Melting point.

Type:

float

critical_temperature[source]

Critical temperature.

Type:

float

superconduction_temperature[source]

Superconduction temperature.

Type:

float

liquid_range[source]

Liquid range.

Type:

float

bulk_modulus[source]

Bulk modulus.

Type:

float

youngs_modulus[source]

Young’s modulus.

Type:

float

brinell_hardness[source]

Brinell hardness.

Type:

float

rigidity_modulus[source]

Rigidity modulus.

Type:

float

mineral_hardness[source]

Mineral hardness.

Type:

float

vickers_hardness[source]

Vicker’s hardness.

Type:

float

density_of_solid[source]

Density of solid phase.

Type:

float

coefficient_of_linear_thermal_expansion[source]

Coefficient of linear thermal expansion.

Type:

float

ground_level[source]

Ground level for element.

Type:

float

ionization_energies[source]

List of ionization energies. First value is the first ionization energy, second is the second ionization energy, etc. Note that this is zero-based indexing! So Element.ionization_energies[0] refer to the 1st ionization energy. Values are from the NIST Atomic Spectra Database. Missing values are None.

Type:

list[Optional[float]]

property X: float[source]

Pauling electronegativity of element. Note that if an element does not have an Pauling electronegativity, a NaN float is returned.

as_dict() dict[Literal['element', '@module', '@class'], str][source]

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

property atomic_mass: FloatWithUnit[source]

Returns: float: The atomic mass of the element in amu.

property atomic_mass_number: FloatWithUnit | None[source]

Returns: float: The atomic mass of the element in amu.

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

The LDA energies in eV for neutral atoms, by orbital.

This property contains the same info as self.atomic_orbitals, but uses eV for units, per matsci issue https://matsci.org/t/unit-of-atomic-orbitals-energy/54325 In short, self.atomic_orbitals was meant to be in eV all along but is now kept as Hartree for backwards compatibility.

property atomic_radius: FloatWithUnit | None[source]

Returns: float | None: The atomic radius of the element in Ångstroms. Can be None for some elements like noble gases.

property average_anionic_radius: FloatWithUnit[source]

Average anionic radius for element (with units). The average is taken over all negative oxidation states of the element for which data is present.

property average_cationic_radius: FloatWithUnit[source]

Average cationic radius for element (with units). The average is taken over all positive oxidation states of the element for which data is present.

property average_ionic_radius: FloatWithUnit[source]

Average ionic radius for element (with units). The average is taken over all oxidation states of the element for which data is present.

property block: str[source]

The block character “s, p, d, f”.

property common_oxidation_states: tuple[int, ...][source]

Tuple of common oxidation states.

property data: dict[str, Any][source]

Dict of data for element.

property electron_affinity: float[source]

The amount of energy released when an electron is attached to a neutral atom.

property electronic_structure: str[source]

Electronic structure as string, with only valence electrons. The electrons are listed in order of increasing prinicpal quantum number

(orbital number), irrespective of the actual energy level,

e.g., The electronic structure for Fe is represented as ‘[Ar].3d6.4s2’ even though the 3d electrons are higher in energy than the 4s.

References

Kramida, A., Ralchenko, Yu., Reader, J., and NIST ASD Team (2023). NIST Atomic Spectra Database (ver. 5.11). https://physics.nist.gov/asd [2024, June 3]. National Institute of Standards and Technology, Gaithersburg, MD. DOI: https://doi.org/10.18434/T4W30F

static from_Z(Z: int, A: int | None = None) Element[source]

Get an element from an atomic number.

Parameters:
  • Z (int) – Atomic number (number of protons)

  • A (int | None) – Atomic mass number (number of protons + neutrons)

Returns:

Element with atomic number Z.

static from_dict(dct: dict) Element[source]

Deserialize from MSONable dict representation.

static from_name(name: str) Element[source]

Get an element from its long name.

Parameters:

name – Long name of the element, e.g. ‘Hydrogen’ or ‘Iron’. Not case-sensitive.

Returns:

Element with the name ‘name’

static from_row_and_group(row: int, group: int) Element[source]

Get an element from a row and group number.

Important Note: For lanthanoids and actinoids, the row number must be 8 and 9, respectively, and the group number must be between 3 (La, Ac) and 17 (Lu, Lr). This is different than the value for Element(symbol).row and Element(symbol).group for these elements.

Parameters:
  • row (int) – (pseudo) row number. This is the standard row number except for the lanthanoids and actinoids for which it is 8 or 9, respectively.

  • group (int) – (pseudo) group number. This is the standard group number except for the lanthanoids and actinoids for which it is 3 (La, Ac) to 17 (Lu, Lr).

Note

The 18 group number system is used, i.e. noble gases are group 18.

property full_electronic_structure: list[tuple[int, str, int]][source]

Full electronic structure as list of tuples, in order of increasing energy level (according to the Madelung rule). Therefore, the final element in the list gives the electronic structure of the valence shell.

For example, the electronic structure for Fe is represented as: [(1, “s”, 2), (2, “s”, 2), (2, “p”, 6), (3, “s”, 2), (3, “p”, 6), (4, “s”, 2), (3, “d”, 6)].

References

Kramida, A., Ralchenko, Yu., Reader, J., and NIST ASD Team (2023). NIST Atomic Spectra Database (ver. 5.11). https://physics.nist.gov/asd [2024, June 3]. National Institute of Standards and Technology, Gaithersburg, MD. DOI: https://doi.org/10.18434/T4W30F

property ground_state_term_symbol: str[source]

Ground state term symbol. Selected based on Hund’s Rule.

property group: int[source]

The periodic table group of the element. Note: For lanthanoids and actinoids, the group is always 3.

property icsd_oxidation_states: tuple[int, ...][source]

Tuple of all oxidation states with at least 10 instances in ICSD database AND at least 1% of entries for that element.

property ionic_radii: dict[int, FloatWithUnit][source]

All ionic radii of the element as a dict of {oxidation state: ionic radii}. Radii are given in angstrom.

property ionization_energy: float | None[source]

First ionization energy of element.

property is_actinoid: bool[source]

True if element is a actinoid.

property is_alkali: bool[source]

True if element is an alkali metal.

property is_alkaline: bool[source]

True if element is an alkaline earth metal (group II).

property is_chalcogen: bool[source]

True if element is a chalcogen.

property is_halogen: bool[source]

True if element is a halogen.

property is_lanthanoid: bool[source]

True if element is a lanthanoid.

property is_metal: bool[source]

True if is a metal.

property is_metalloid: bool[source]

True if element is a metalloid.

property is_noble_gas: bool[source]

True if element is noble gas.

property is_post_transition_metal: bool[source]

True if element is a post-transition or poor metal.

property is_quadrupolar: bool[source]

Check if this element can be quadrupolar.

property is_radioactive: bool[source]

True if element is radioactive.

property is_rare_earth: bool[source]

True if element is a rare earth element, including Lanthanides (La) series, Actinides (Ac) series, Scandium (Sc) and Yttrium (Y).

property is_rare_earth_metal: bool[source]

True if element is a rare earth metal, Lanthanides (La) series and Actinides (Ac) series.

This property is Deprecated, and scheduled for removal after 2025-01-01.

property is_transition_metal: bool[source]

True if element is a transition metal.

static is_valid_symbol(symbol: str) bool[source]

Check if symbol (e.g., “H”) is a valid element symbol.

Parameters:

symbol (str) – Element symbol

Returns:

True if symbol is a valid element.

Return type:

bool

property iupac_ordering: int[source]

Ordering according to 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.

property max_oxidation_state: float[source]

Maximum oxidation state for element.

property min_oxidation_state: float[source]

Minimum oxidation state for element.

property n_electrons: int[source]

Total number of electrons in the Element.

property nmr_quadrupole_moment: dict[str, FloatWithUnit][source]

A dictionary the nuclear electric quadrupole moment in units of e*millibarns for various isotopes.

property number: int[source]

Alternative attribute for atomic number Z.

property oxidation_states: tuple[int, ...][source]

Tuple of all known oxidation states.

static print_periodic_table(filter_function: Callable | None = None) None[source]

A pretty ASCII printer for the periodic table, based on some filter_function.

Parameters:

filter_function – A filtering function taking an Element as input and returning a boolean. For example, setting filter_function = lambda el: el.X > 2 will print a periodic table containing only elements with Pauling electronegativity > 2.

property row: int[source]

The periodic table row of the element. Note: For lanthanoids and actinoids, the row is always 6 or 7, respectively.

property term_symbols: list[list[str]][source]

All possible Russell-Saunders term symbol of the Element. eg. L = 1, n_e = 2 (s2) returns [[‘1D2’], [‘3P0’, ‘3P1’, ‘3P2’], [‘1S0’]].

property valence: tuple[int | np.nan, int][source]

Valence subshell angular moment (L) and number of valence e- (v_e), obtained from full electron config, where L=0, 1, 2, or 3 for s, p, d, and f orbitals, respectively.

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

Bases: Enum

Enum for element types.

actinoid = 'actinoid'[source]
alkali = 'alkali'[source]
alkaline = 'alkaline'[source]
chalcogen = 'chalcogen'[source]
d_block = 'd-block'[source]
f_block = 'f-block'[source]
halogen = 'halogen'[source]
lanthanoid = 'lanthanoid'[source]
metal = 'metal'[source]
metalloid = 'metalloid'[source]
noble_gas = 'noble_gas'[source]
p_block = 'p-block'[source]
post_transition_metal = 'post_transition_metal'[source]
quadrupolar = 'quadrupolar'[source]
radioactive = 'radioactive'[source]
rare_earth_metal = 'rare_earth_metal'[source]
s_block = 's-block'[source]
transition_metal = 'transition_metal'[source]
class Specie(symbol: SpeciesLike, oxidation_state: float | None = None, spin: float | None = None)[source]

Bases: Species

This maps the historical grammatically inaccurate Specie to Species to maintain backwards compatibility.

Parameters:
  • symbol (str) – Element symbol optionally incl. oxidation state. E.g. Fe, Fe2+, O2-.

  • oxidation_state (float) – Explicit oxidation state of element, e.g. -2, -1, 0, 1, 2, … If oxidation state is present in symbol, this argument is ignored.

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

Raises:

ValueError – If oxidation state passed both in symbol string and via oxidation_state kwarg.

class Species(symbol: SpeciesLike, oxidation_state: float | None = None, spin: float | None = None)[source]

Bases: MSONable, Stringify

An extension of Element with optional oxidation state and spin. Properties associated with Species should be “idealized” values, not calculated values. For example, high-spin Fe2+ may be assigned an idealized spin of +5, but an actual Fe2+ site may be calculated to have a magmom of +4.5. Calculated properties should be assigned to Site objects, and not Species.

Parameters:
  • symbol (str) – Element symbol optionally incl. oxidation state. E.g. Fe, Fe2+, O2-.

  • oxidation_state (float) – Explicit oxidation state of element, e.g. -2, -1, 0, 1, 2, … If oxidation state is present in symbol, this argument is ignored.

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

Raises:

ValueError – If oxidation state passed both in symbol string and via oxidation_state kwarg.

STRING_MODE = 'SUPERSCRIPT'[source]
as_dict() dict[source]

JSON-able dictionary representation.

property electronic_structure: str[source]

Electronic structure as string, with only valence electrons. The electrons are listed in order of increasing prinicpal quantum number

(orbital number), irrespective of the actual energy level,

e.g., The electronic structure for Fe is represented as ‘[Ar].3d6.4s2’ even though the 3d electrons are higher in energy than the 4s.

References

Kramida, A., Ralchenko, Yu., Reader, J., and NIST ASD Team (2023). NIST Atomic Spectra Database (ver. 5.11). https://physics.nist.gov/asd [2024, June 3]. National Institute of Standards and Technology, Gaithersburg, MD. DOI: https://doi.org/10.18434/T4W30F

property element: Element[source]

Underlying element object.

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

dct (dict) – Dict representation.

Returns:

Species.

classmethod from_str(species_string: str) Self[source]

Get a Species from a string representation.

Parameters:

species_string (str) – A typical string representation of a species, e.g. “Mn2+”, “Fe3+”, “O2-“.

Returns:

A Species object.

Raises:

ValueError if species_string cannot be interpreted.

property full_electronic_structure: list[tuple[int, str, int]][source]

Full electronic structure as list of tuples, in order of increasing energy level (according to the Madelung rule). Therefore, the final element in the list gives the electronic structure of the valence shell.

For example, the electronic structure for Fe+2 is represented as: [(1, “s”, 2), (2, “s”, 2), (2, “p”, 6), (3, “s”, 2), (3, “p”, 6), (3, “d”, 6)].

References

Kramida, A., Ralchenko, Yu., Reader, J., and NIST ASD Team (2023). NIST Atomic Spectra Database (ver. 5.11). https://physics.nist.gov/asd [2024, June 3]. National Institute of Standards and Technology, Gaithersburg, MD. DOI: https://doi.org/10.18434/T4W30F

get_crystal_field_spin(coordination: Literal['oct', 'tet'] = 'oct', spin_config: Literal['low', 'high'] = 'high') float[source]

Calculate the crystal field spin based on coordination and spin configuration. Only works for transition metal species.

Parameters:
  • coordination ("oct" | "tet") – Tetrahedron or octahedron crystal site coordination

  • spin_config ("low" | "high") – Whether the species is in a high or low spin state

Returns:

Crystal field spin in Bohr magneton.

Return type:

float

Raises:
  • AttributeError if species is not a valid transition metal or has – an invalid oxidation state.

  • ValueError if invalid coordination or spin_config.

get_nmr_quadrupole_moment(isotope: str | None = None) float[source]

Get the nuclear electric quadrupole moment in units of e * millibarns.

Parameters:

isotope (str) – the isotope to get the quadrupole moment for default is None, which gets the lowest mass isotope

get_shannon_radius(cn: str, spin: Literal['', 'Low Spin', 'High Spin'] = '', radius_type: Literal['ionic', 'crystal'] = 'ionic') float[source]

Get the local environment specific ionic radius for species.

Parameters:
  • cn (str) – Coordination using roman letters. Supported values are I-IX, as well as IIIPY, IVPY and IVSQ.

  • spin (str) – Some species have different radii for different spins. You can get specific values using “High Spin” or “Low Spin”. Leave it as “” if not available. If only one spin data is available, it is returned and this spin parameter is ignored.

  • radius_type (str) – Either “crystal” or “ionic” (default).

Returns:

Shannon radius for specie in the specified environment.

property ionic_radius: float | None[source]

Ionic radius of specie. Returns None if data is not present.

property n_electrons: int[source]

Total number of electrons in the Species.

property oxi_state: float | None[source]

Oxidation state of Species.

property spin: float | None[source]

Spin of Species.

to_pretty_string() str[source]

String without properties.

property valence: tuple[int | np.nan, int][source]

Valence subshell angular moment (L) and number of valence e- (v_e), obtained from full electron config, where L=0, 1, 2, or 3 for s, p, d, and f orbitals, respectively.

get_el_sp(obj: int) Element[source]
get_el_sp(obj: SpeciesLike) Element | Species | DummySpecies

Utility function to get an Element, Species or DummySpecies from any input.

If obj is an Element or a Species, it is returned as is. If obj is an int or a string representing an integer, the Element with the atomic number obj is returned. If obj is a string, Species parsing will be attempted (e.g. Mn2+). Failing that Element parsing will be attempted (e.g. Mn). Failing that DummyElement parsing will be attempted.

Parameters:

obj (SpeciesLike) – An arbitrary object. Supported objects are actual Element/Species, integers (representing atomic numbers) or strings (element symbols or species strings).

Raises:

ValueError – if obj cannot be converted into an Element or Species.

Returns:

with a bias for the maximum number

of properties that can be determined.

Return type:

Element | Species | DummySpecies

pymatgen.core.sites module

This module defines classes representing non-periodic and periodic sites.

class PeriodicSite(species: SpeciesLike | CompositionLike, coords: ArrayLike, lattice: Lattice, to_unit_cell: bool = False, coords_are_cartesian: bool = False, properties: dict | None = None, label: str | None = None, skip_checks: bool = False)[source]

Bases: Site, MSONable

Extension of generic Site object to periodic systems. PeriodicSite includes a lattice system.

Create a periodic site.

Parameters:
  • species

    Species on the site. Can be: i. A Composition-type object (preferred) ii. An element / species specified either as a string

    symbols, e.g. “Li”, “Fe2+”, “P” or atomic numbers, e.g. 3, 56, or actual Element or Species objects.

    iii.Dict of elements/species and occupancies, e.g.

    {“Fe” : 0.5, “Mn”:0.5}. This allows the setup of disordered structures.

  • coords – Coordinates of site, fractional coordinates by default. See coords_are_cartesian for more details.

  • lattice – Lattice associated with the site.

  • to_unit_cell – Translates fractional coordinate to the basic unit cell, i.e. all fractional coordinates satisfy 0 <= a < 1. Defaults to False.

  • coords_are_cartesian – Set to True if you are providing Cartesian coordinates. Defaults to False.

  • properties – Properties associated with the site as a dict, e.g. {“magmom”: 5}. Defaults to None.

  • label – Label for the site. Defaults to None.

  • skip_checks – Whether to ignore all the usual checks and just create the site. Use this if the PeriodicSite is created in a controlled manner and speed is desired.

property a: float[source]

Fractional a coordinate.

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

JSON-serializable dict representation of PeriodicSite.

Parameters:

verbosity (int) – Verbosity level. Default of 0 only includes the matrix representation. Set to 1 for more details such as Cartesian coordinates, etc.

property b: float[source]

Fractional b coordinate.

property c: float[source]

Fractional c coordinate.

property coords: ndarray[source]

Cartesian coordinates.

distance(other: Self, jimage: ArrayLike | None = None) float[source]

Get distance between two sites assuming periodic boundary conditions.

Parameters:
  • other (PeriodicSite) – Other site 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 between the two sites.

Return type:

float

distance_and_image(other: Self, jimage: ArrayLike | None = None) tuple[float, np.ndarray][source]

Get distance and instance between two sites assuming periodic boundary conditions. If the index jimage of two sites atom j 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 of atom j is specified it returns the distance between the ith atom and the specified jimage atom, the given jimage is also returned.

Parameters:
  • other (PeriodicSite) – Other site 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.

Return type:

tuple[float, np.ndarray]

distance_and_image_from_frac_coords(fcoords: ArrayLike, jimage: ArrayLike | None = None) tuple[float, np.ndarray][source]

Get distance between site and a fractional coordinate assuming periodic boundary conditions. If the index jimage of two sites atom j 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 of atom j is specified it returns the distance between the i atom and the specified jimage atom, the given jimage is also returned.

Parameters:
  • fcoords (3x1 array) – fractional coordinates 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.

Return type:

tuple[float, np.ndarray]

property frac_coords: ndarray[source]

Fractional coordinates.

classmethod from_dict(dct: dict, lattice: Lattice | None = None) Self[source]

Create PeriodicSite from dict representation.

Parameters:
  • dct (dict) – dict representation of PeriodicSite

  • lattice – Optional lattice to override lattice specified in d. Useful for ensuring all sites in a structure share the same lattice.

Returns:

PeriodicSite

is_periodic_image(other: Self, tolerance: float = 1e-08, check_lattice: bool = True) bool[source]

Check if sites are periodic images of each other.

Parameters:
  • other (PeriodicSite) – Other site

  • tolerance (float) – Tolerance to compare fractional coordinates

  • check_lattice (bool) – Whether to check if the two sites have the same lattice.

Returns:

True if sites are periodic images of each other.

Return type:

bool

property lattice: Lattice[source]

Lattice associated with PeriodicSite.

to_unit_cell(in_place: bool = False) Self | None[source]

Move frac coords to within the unit cell.

property x: float[source]

Cartesian x coordinate.

property y: float[source]

Cartesian y coordinate.

property z: float[source]

Cartesian z coordinate.

class Site(species: SpeciesLike | CompositionLike, coords: ArrayLike, properties: dict | None = None, label: str | None = None, skip_checks: bool = False)[source]

Bases: Hashable, MSONable

A generalized non-periodic site. This is essentially a composition at a point in space, with some optional properties associated with it. A Composition is used to represent the atoms and occupancy, which allows for disordered site representation. Coords are given in standard Cartesian coordinates.

Create a non-periodic Site.

Parameters:
  • species

    Species on the site. Can be: i. A Composition-type object (preferred) ii. An element / species specified either as a string

    symbols, e.g. “Li”, “Fe2+”, “P” or atomic numbers, e.g. 3, 56, or actual Element or Species objects.

    iii.Dict of elements/species and occupancies, e.g.

    {“Fe” : 0.5, “Mn”:0.5}. This allows the setup of disordered structures.

  • coords – Cartesian coordinates of site.

  • properties – Properties associated with the site as a dict, e.g. {“magmom”: 5}. Defaults to None.

  • label – Label for the site. Defaults to None.

  • skip_checks – Whether to ignore all the usual checks and just create the site. Use this if the Site is created in a controlled manner and speed is desired.

as_dict() dict[source]

JSON-serializable dict representation for Site.

distance(other: Site) float[source]

Get distance between two sites.

Parameters:

other – Other site.

Returns:

distance

Return type:

float

distance_from_point(pt: Vector3D) float[source]

Get distance between the site and a point in space.

Parameters:

pt – Cartesian coordinates of point.

Returns:

distance

Return type:

float

classmethod from_dict(dct: dict) Self[source]

Create Site from dict representation.

property is_ordered: bool[source]

True if site is an ordered site, i.e., with a single species with occupancy 1.

property label: str[source]

Site label.

position_atol = 1e-05[source]
property specie: Element | Species | DummySpecies[source]

The Species/Element at the site. Only works for ordered sites. Otherwise an AttributeError is raised. Use this property sparingly. Robust design should make use of the property species instead. Note that the singular of species is also species. So the choice of this variable name is governed by programmatic concerns as opposed to grammar.

Raises:

AttributeError if Site is not ordered.

property species: Composition[source]

The species on the site as a composition, e.g. Fe0.5Mn0.5.

property species_string: str[source]

String representation of species on the site.

property x: float[source]

Cartesian x coordinate.

property y: float[source]

Cartesian y coordinate.

property z: float[source]

Cartesian z coordinate.

pymatgen.core.spectrum module

This module defines classes to represent any type of spectrum, essentially any x y value pairs.

class Spectrum(x: NDArray, y: NDArray, *args, **kwargs)[source]

Bases: MSONable

Base class for any type of XAS, essentially just x, y values. Examples include XRD patterns, XANES, EXAFS, NMR, DOS, etc.

Implements basic tools like application of smearing, normalization, addition multiplication, etc.

Subclasses should extend this object and ensure that super is called with ALL args and kwargs. That ensures subsequent things like add and mult work properly.

Parameters:
  • x (ndarray) – A ndarray of N values.

  • y (ndarray) – A ndarray of N x k values. The first dimension must be the same as that of x. Each of the k values are interpreted as separate.

  • *args – All subclasses should provide args other than x and y when calling super, e.g. super().__init__( x, y, arg1, arg2, kwarg1=val1, ..). This guarantees the +, -, *, etc. operators work properly.

  • **kwargs – Same as that for *args.

XLABEL = 'x'[source]
YLABEL = 'y'[source]
copy() Self[source]
Returns:

Copy of Spectrum object.

get_interpolated_value(x: float) float | list[float][source]

Get an interpolated y value for a particular x value.

Parameters:

x – x value to return the y value for

Returns:

Value of y at x

normalize(mode: Literal['max', 'sum'] = 'max', value: float = 1.0) None[source]

Normalize the spectrum with respect to the sum of intensity.

Parameters:
  • mode ("max" | "sum") – Normalization mode. “max” sets the max y value to value, e.g. in XRD patterns. “sum” sets the sum of y to a value, i.e., like a probability density.

  • value (float) – Value to normalize to. Defaults to 1.

smear(sigma: float = 0.0, func: Literal['gaussian', 'lorentzian'] | Callable = 'gaussian') None[source]

Apply Gaussian/Lorentzian smearing to spectrum y value.

Parameters:
  • sigma – Std dev for Gaussian smear function

  • func – “gaussian” or “lorentzian” or a callable. If this is a callable, the sigma value is ignored. The callable should only take a single argument (a numpy array) and return a set of weights.

lorentzian(x: NDArray, x_0: float = 0, sigma: float = 1.0) NDArray[source]

The Lorentzian smearing function.

Parameters:
  • x – x values

  • x_0 – Center

  • sigma – FWHM.

Returns:

Value of lorentzian at x.

pymatgen.core.structure module

This module provides classes to define non-periodic Molecule and periodic Structure, along with their immutable counterparts IMolecule and IStructure.

class IMolecule(species: Sequence[CompositionLike], coords: Sequence[ArrayLike], charge: float = 0.0, spin_multiplicity: int | None = None, validate_proximity: bool = False, site_properties: dict | None = None, labels: Sequence[str | None] | None = None, charge_spin_check: bool = True, properties: dict | None = None)[source]

Bases: SiteCollection, MSONable

Basic immutable Molecule object without periodicity. Essentially a sequence of sites. IMolecule is made to be immutable so that they can function as keys in a dict. For a mutable object, use the Molecule class.

Molecule extends Sequence and Hashable, which means that in many cases, it can be used like any Python sequence. Iterating through a molecule is equivalent to going through the sites in sequence.

Create a IMolecule.

Parameters:
  • species – list of atomic species. Possible kinds of input include a list of dict of elements/species and occupancies, a List of elements/specie specified as actual Element/Species, Strings (“Fe”, “Fe2+”) or atomic numbers (1,56).

  • coords (3x1 array) – list of Cartesian coordinates of each species.

  • charge (float) – Charge for the molecule. Defaults to 0.

  • spin_multiplicity (int) – Spin multiplicity for molecule. Defaults to None, which means that the spin multiplicity is set to 1 if the molecule has no unpaired electrons and to 2 if there are unpaired electrons.

  • validate_proximity (bool) – Whether to check if there are sites that are less than 1 Ang apart. 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.

  • labels (list[str]) – Labels associated with the sites as a list of strings, e.g. [‘Li1’, ‘Li2’]. Must have the same length as the species and fractional coords. Defaults to None for no labels.

  • charge_spin_check (bool) – Whether to check that the charge and spin multiplicity are compatible with each other. Defaults to True.

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

as_dict() dict[source]

JSON-serializable dict representation of Molecule.

break_bond(ind1: int, ind2: int, tol: float = 0.2) tuple[Self, Self][source]

Get two molecules based on breaking the bond between atoms at index ind1 and ind2.

Parameters:
  • ind1 (int) – 1st site index

  • ind2 (int) – 2nd site index

  • 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.

Returns:

The clusters formed from breaking the bond.

Return type:

tuple[IMolecule, IMolecule]

property center_of_mass: NDArray[source]

Center of mass of molecule.

property charge: float[source]

Charge of molecule.

copy() Self[source]

Convenience method to get a copy of the molecule.

Returns:

IMolecule

classmethod from_dict(dct: dict) Self[source]

Reconstitute a Molecule object from a dict representation created using as_dict().

Parameters:

dct (dict) – dict representation of Molecule.

Returns:

IMolecule

classmethod from_file(filename: PathLike) Self | None[source]

Read a molecule from a file. Supported formats include xyz, gaussian input (gjf|g03|g09|com|inp), Gaussian output (.out|and pymatgen’s JSON-serialized molecules. Using openbabel, many more extensions are supported but requires openbabel to be installed.

Parameters:

filename (PathLike) – The file to read.

Returns:

Molecule

classmethod from_sites(sites: Sequence[Site], charge: float = 0, spin_multiplicity: int | None = None, validate_proximity: bool = False, charge_spin_check: bool = True, properties: dict | None = None) Self[source]

Convenience constructor to make a Molecule from a list of sites.

Parameters:
  • sites ([Site]) – Sequence of Sites.

  • charge (int) – Charge of molecule. Defaults to 0.

  • spin_multiplicity (int) – Spin multicipity. Defaults to None, in which it is determined automatically.

  • validate_proximity (bool) – Whether to check that atoms are too close.

  • charge_spin_check (bool) – Whether to check that the charge and spin multiplicity are compatible with each other. Defaults to True.

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

Raises:

ValueError – If sites is empty

Returns:

IMolecule

classmethod from_str(input_string: str, fmt: Literal['xyz', 'gjf', 'g03', 'g09', 'com', 'inp', 'json', 'yaml']) Self | Molecule[source]

Reads the molecule from a string.

Parameters:
  • input_string (str) – String to parse.

  • fmt (str) – Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include “xyz”, “gjf”, “g03”, “json”. If you have OpenBabel installed, any of the formats supported by OpenBabel. Non-case sensitive.

Returns:

IMolecule or Molecule.

get_boxed_structure(a: float, b: float, c: float, images: ArrayLike = (1, 1, 1), random_rotation: bool = False, min_dist: float = 1.0, cls=None, offset: ArrayLike | None = None, no_cross: bool = False, reorder: bool = True) IStructure | Structure[source]

Create a Structure from a Molecule by putting the Molecule in the center of a orthorhombic box. Useful for creating Structure for calculating molecules using periodic codes.

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

  • b (float) – b-lattice parameter.

  • c (float) – c-lattice parameter.

  • images – No. of boxed images in each direction. Defaults to (1, 1, 1), meaning single molecule with 1 lattice parameter in each direction.

  • random_rotation (bool) – Whether to apply a random rotation to each molecule. This jumbles all the molecules so that they are not exact images of each other.

  • min_dist (float) – The minimum distance that atoms should be from each other. This is only used if random_rotation is True. The randomized rotations are searched such that no two atoms are less than min_dist from each other.

  • cls – The Structure class to instantiate (defaults to pymatgen structure)

  • offset – Translation to offset molecule from center of mass coords

  • no_cross – Whether to forbid molecule coords from extending beyond boundary of box.

  • reorder – Whether to reorder the sites to be in electronegativity order.

Returns:

Structure containing molecule in a box.

get_centered_molecule() Self[source]

Get a Molecule centered at the center of mass.

Returns:

IMolecule centered with center of mass at origin.

get_covalent_bonds(tol: float = 0.2) list[CovalentBond][source]

Determine the covalent bonds in a molecule.

Parameters:

tol (float) – The tol to determine bonds in a structure. See CovalentBond.is_bonded.

Returns:

List of bonds

get_distance(i: int, j: int) float[source]

Get distance between site i and j.

Parameters:
  • i (int) – 1st site index

  • j (int) – 2nd site index

Returns:

Distance between the two sites.

get_neighbors(site: Site, r: float) list[Neighbor][source]

Get all neighbors to a site within a sphere of radius r. Excludes the site itself.

Parameters:
  • site (Site) – Site at the center of the sphere.

  • r (float) – Radius of sphere.

Returns:

Neighbor

get_neighbors_in_shell(origin: ArrayLike, r: float, dr: float) list[Neighbor][source]

Get all sites in a shell centered on origin (coords) between radii r-dr and r+dr.

Parameters:
  • origin (3x1 array) – Cartesian coordinates of center of sphere.

  • r (float) – Inner radius of shell.

  • dr (float) – Width of shell.

Returns:

Neighbor

get_sites_in_sphere(pt: ArrayLike, r: float) list[Neighbor][source]

Find all sites within a sphere from a point.

Parameters:
  • pt (3x1 array) – Cartesian coordinates of center of sphere

  • r (float) – Radius of sphere.

Returns:

Neighbor

get_zmatrix() str[source]

Get a z-matrix representation of the molecule.

property nelectrons: float[source]

Number of electrons in the molecule.

property spin_multiplicity: float[source]

Spin multiplicity of molecule.

to(filename: str = '', fmt: str = '') str | None[source]

Outputs the molecule to a file or string.

Parameters:
  • filename (str) – If provided, output will be written to a file. If fmt is not specified, the format is determined from the filename. Defaults is None, i.e. string output.

  • fmt (str) – Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include “xyz”, “gjf”, “g03”, “json”. If you have OpenBabel installed, any of the formats supported by OpenBabel. Non-case sensitive.

Returns:

String representation of molecule in given format. If a filename

is provided, the same string is written to the file.

Return type:

str

class IStructure(lattice: ArrayLike | Lattice, species: Sequence[CompositionLike], coords: Sequence[ArrayLike], charge: float | None = None, validate_proximity: bool = False, to_unit_cell: bool = False, coords_are_cartesian: bool = False, site_properties: dict | None = None, labels: Sequence[str | None] | None = None, properties: dict | None = None)[source]

Bases: SiteCollection, MSONable

Basic immutable Structure object with periodicity. Essentially a sequence of PeriodicSites having a common lattice. IStructure is made to be (somewhat) immutable so that they can function as keys in a dict. To make modifications, use the standard Structure object instead. Structure extends Sequence and Hashable, which means that in many cases, it can be used like any Python sequence. Iterating through a structure is equivalent to going through the sites in sequence.

Create a periodic structure.

Parameters:
  • lattice (Lattice/3x3 array) – The lattice, either as a pymatgen.core.Lattice or simply as any 2D 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.

  • charge (int) – overall charge of the structure. Defaults to behavior in SiteCollection where total charge is the sum of the oxidation states.

  • 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 map all sites into the unit cell, i.e. fractional coords between 0 and 1. 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.

  • labels (list[str]) – Labels associated with the sites as a list of strings, e.g. [‘Li1’, ‘Li2’]. Must have the same length as the species and fractional coords. Defaults to None for no labels.

  • properties (dict) – Properties associated with the whole structure. Will be serialized when writing the structure to JSON or YAML but is lost when converting to other formats.

CellType[source]

alias of Literal[‘primitive’, ‘conventional’]

as_dataframe() pd.DataFrame[source]

Create a Pandas DataFrame of the sites. Structure-level attributes are stored in DataFrame.attrs.

Example

Species a b c x y z magmom 0 (Si) 0.0 0.0 0.0 0.0 0.0 0.0 5 1 (Si) 0.0 0.0 0.0 0.0 0.0 0.0 -5

as_dict(verbosity: int = 1, fmt: Literal['abivars'] | None = None, **kwargs) dict[str, Any][source]

Dict representation of Structure.

Parameters:
  • verbosity (int) – Verbosity level. Default of 1 includes both direct and Cartesian coordinates for all sites, lattice parameters, etc. Useful for reading and for insertion into a database. Set to 0 for an extremely lightweight version that only includes sufficient information to reconstruct the object.

  • fmt ("abivars" | None) – Specifies a format for the dict. Defaults to None, which is the default format used in pymatgen. Or “abivars”.

  • **kwargs – Allow passing of other kwargs needed for certain

  • formats

  • "abivars". (e.g.)

Returns:

JSON-serializable dict representation.

property charge: float[source]

Overall charge of the structure.

copy(site_properties: dict[str, Any] | None = None, sanitize: bool = False, properties: dict[str, Any] | None = None) Self[source]

Convenience method to get a copy of the structure, with options to add site properties.

Parameters:
  • site_properties (dict) – Properties to add or override. The properties are specified in the same way as the constructor, i.e., as a dict of the form {property: [values]}. The properties should be in the order of the original structure if you are performing sanitization.

  • sanitize (bool) – If True, this method will return a sanitized structure. Sanitization performs a few things: (i) The sites are sorted by electronegativity, (ii) a LLL lattice reduction is carried out to obtain a relatively orthogonalized cell, (iii) all fractional coords for sites are mapped into the unit cell.

  • properties (dict) – General properties to add or override.

Returns:

A copy of the Structure, with optionally new site_properties and optionally sanitized.

property density: float[source]

The density in units of g/cm^3.

property distance_matrix: ndarray[source]

The distance matrix between all sites in the structure. For periodic structures, this should return the nearest image distance.

property frac_coords[source]

Fractional coordinates as a Nx3 numpy array.

classmethod from_dict(dct: dict[str, Any], fmt: Literal['abivars'] | None = None) Self[source]

Reconstitute a Structure from a dict representation of Structure created using as_dict().

Parameters:
  • dct (dict) – Dict representation of structure.

  • fmt ('abivars' | None) – Use structure_from_abivars() to parse the dict. Defaults to None.

Returns:

Structure object

classmethod from_file(filename: PathLike, primitive: bool = False, sort: bool = False, merge_tol: float = 0.0, **kwargs) Structure | Self[source]

Read a structure from a file. For example, anything ending in a “cif” is assumed to be a Crystallographic Information Format file. Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT, vasprun.xml, CSSR, Netcdf and pymatgen’s JSON-serialized structures.

Parameters:
  • filename (PathLike) – The file to read.

  • primitive (bool) – Whether to convert to a primitive cell. Defaults to False.

  • sort (bool) – Whether to sort sites. Default to False.

  • merge_tol (float) – If this is some positive number, sites that are within merge_tol from each other will be merged. Usually 0.01 should be enough to deal with common numerical issues.

  • kwargs – Passthrough to relevant reader. E.g. if the file has CIF format, the kwargs will be passed through to CifParser.

Returns:

Structure.

classmethod from_id(id_: str, source: Literal['Materials Project', 'COD'] = 'Materials Project', **kwargs) Structure[source]

Load a structure file based on an id, usually from an online source.

Parameters:
  • id – The id associated with the structure. E.g., the Materials Project id.

  • source – Source of the data. Defaults to “Materials Project”.

  • **kwargs – Pass-through to any API calls.

classmethod from_magnetic_spacegroup(msg: str | MagneticSpaceGroup, lattice: list | np.ndarray | Lattice, species: Sequence[str | Element | Species | DummySpecies | Composition], coords: Sequence[Sequence[float]], site_properties: dict[str, Sequence], coords_are_cartesian: bool = False, tol: float = 1e-05, labels: Sequence[str | None] | None = None) Self[source]

Generate a structure using a magnetic spacegroup. Note that only symmetrically distinct species, coords and magmoms should be provided.] All equivalent sites are generated from the spacegroup operations.

Parameters:
  • msg (str/list/pymatgen.symmetry.maggroups.MagneticSpaceGroup) – The magnetic spacegroup. If a string, it will be interpreted as one of the notations supported by MagneticSymmetryGroup, e.g. “R-3’c” or “Fm’-3’m”. If a list of two ints, it will be interpreted as the number of the spacegroup in its Belov, Neronova and Smirnova (BNS) setting.

  • lattice (Lattice/3x3 array) – The lattice, either as a pymatgen.core.Lattice or simply as any 2D 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]. Note that no attempt is made to check that the lattice is compatible with the spacegroup specified. This may be introduced in a future version.

  • species ([Species]) –

    Sequence of species on each site. Can take in flexible input, including: i. 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.

    1. 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.

  • 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. Unlike Structure.from_spacegroup(), this argument is mandatory, since magnetic moment information has to be included. Note that the direction of the supplied magnetic moment relative to the crystal is important, even if the resulting structure is used for collinear calculations.

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

  • tol (float) – A fractional tolerance to deal with numerical precision issues in determining if orbits are the same.

  • labels (list[str]) – Labels associated with the sites as a list of strings, e.g. [‘Li1’, ‘Li2’]. Must have the same length as the species and fractional coords. Defaults to None for no labels.

Returns:

IStructure

classmethod from_sites(sites: list[PeriodicSite], charge: float | None = None, validate_proximity: bool = False, to_unit_cell: bool = False, properties: dict | None = None) Self[source]

Convenience constructor to make a IStructure from a list of sites.

Parameters:
  • sites – Sequence of PeriodicSites. Sites must have the same lattice.

  • charge – Charge of structure.

  • 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.

  • properties (dict) – Properties associated with the whole structure. Will be serialized when writing the structure to JSON or YAML but is lost when converting to other formats.

Raises:

ValueError – If sites is empty or sites do not have the same lattice.

Returns:

Note that missing properties are set as None.

Return type:

IStructure

classmethod from_spacegroup(sg: str | int, lattice: list | np.ndarray | Lattice, species: Sequence[str | Element | Species | DummySpecies | Composition], coords: Sequence[Sequence[float]], site_properties: dict[str, Sequence] | None = None, coords_are_cartesian: bool = False, tol: float = 1e-05, labels: Sequence[str | None] | None = None) Self[source]

Generate a structure using a spacegroup. Note that only symmetrically distinct species and coords should be provided. All equivalent sites are generated from the spacegroup operations.

Parameters:
  • sg (str | int) – The spacegroup. If a string, it will be interpreted as one of the notations supported by pymatgen.symmetry.groups.Spacegroup. e.g. “R-3c” or “Fm-3m”. If an int, it will be interpreted as an international number.

  • lattice (Lattice/3x3 array) – The lattice, either as a pymatgen.core.Lattice or simply as any 2D 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]. Note that no attempt is made to check that the lattice is compatible with the spacegroup specified. This may be introduced in a future version.

  • 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.

  • 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.

  • tol (float) – A fractional tolerance to deal with numerical precision issues in determining if orbits are the same.

  • labels (list[str]) – Labels associated with the sites as a list of strings, e.g. [‘Li1’, ‘Li2’]. Must have the same length as the species and fractional coords. Defaults to None for no labels.

classmethod from_str(input_string: str, fmt: FileFormats, primitive: bool = False, sort: bool = False, merge_tol: float = 0.0, **kwargs) Structure | Self[source]

Read a structure from a string.

Parameters:
  • input_string (str) – String to parse.

  • fmt (str) – A file format specification. One of “cif”, “poscar”, “cssr”, “json”, “yaml”, “yml”, “xsf”, “mcsqs”, “res”.

  • primitive (bool) – Whether to find a primitive cell. Defaults to False.

  • sort (bool) – Whether to sort the sites in accordance to the default ordering criteria, i.e., electronegativity.

  • merge_tol (float) – If this is some positive number, sites that are within merge_tol from each other will be merged. Usually 0.01 should be enough to deal with common numerical issues.

  • **kwargs – Passthrough to relevant parser.

Returns:

IStructure | Structure

get_all_neighbors(r: float, include_index: bool = False, include_image: bool = False, sites: Sequence[PeriodicSite] | None = None, numerical_tol: float = 1e-08) list[list[PeriodicNeighbor]][source]

Get neighbors for each atom in the unit cell, out to a distance r. Use this method if you are planning on looping over all sites in the crystal. If you only want neighbors for a particular site, use the method get_neighbors as it may not have to build such a large supercell However if you are looping over all sites in the crystal, this method is more efficient since it only performs one pass over a large enough supercell to contain all possible atoms out to a distance r. The return type is a [(site, dist) …] since most of the time, subsequent processing requires the distance.

A note about periodic images: Before computing the neighbors, this operation translates all atoms to within the unit cell (having fractional coordinates within [0,1)). This means that the “image” of a site does not correspond to how much it has been translates from its current position, but which image of the unit cell it resides.

Parameters:
  • r (float) – Radius of sphere.

  • include_index (bool) – Deprecated. Now, the non-supercell site index is always included in the returned data.

  • include_image (bool) – Deprecated. Now the supercell image is always included in the returned data.

  • sites (list of Sites or None) – sites for getting all neighbors, default is None, which means neighbors will be obtained for all sites. This is useful in the situation where you are interested only in one subspecies type, and makes it a lot faster.

  • numerical_tol (float) – This is a numerical tolerance for distances. Sites which are < numerical_tol are determined to be coincident with the site. Sites which are r + numerical_tol away is deemed to be within r from the site. The default of 1e-8 should be ok in most instances.

Returns:

a list of

list of neighbors for each site in structure.

Return type:

[[pymatgen.core.structure.PeriodicNeighbor], …]

get_all_neighbors_old(r: float, include_index: bool = False, include_image: bool = False, include_site: bool = True)[source]

Get neighbors for each atom in the unit cell, out to a distance r. Use this method if you are planning on looping over all sites in the crystal. If you only want neighbors for a particular site, use the method get_neighbors as it may not have to build such a large supercell However if you are looping over all sites in the crystal, this method is more efficient since it only performs one pass over a large enough supercell to contain all possible atoms out to a distance r. The return type is a [(site, dist) …] since most of the time, subsequent processing requires the distance.

A note about periodic images: Before computing the neighbors, this operation translates all atoms to within the unit cell (having fractional coordinates within [0,1)). This means that the “image” of a site does not correspond to how much it has been translates from its current position, but which image of the unit cell it resides.

Parameters:
  • r (float) – Radius of sphere.

  • include_index (bool) – Whether to include the non-supercell site in the returned data

  • include_image (bool) – Whether to include the supercell image in the returned data

  • include_site (bool) – Whether to include the site in the returned data. Defaults to True.

Returns:

Neighbors for each site in structure.

Return type:

list[list[PeriodicNeighbor]]

get_all_neighbors_py(r: float, include_index: bool = False, include_image: bool = False, sites: Sequence[PeriodicSite] | None = None, numerical_tol: float = 1e-08) list[list[PeriodicNeighbor]][source]

Get neighbors for each atom in the unit cell, out to a distance r. Use this method if you are planning on looping over all sites in the crystal. If you only want neighbors for a particular site, use the method get_neighbors as it may not have to build such a large supercell However if you are looping over all sites in the crystal, this method is more efficient since it only performs one pass over a large enough supercell to contain all possible atoms out to a distance r. The return type is a [(site, dist) …] since most of the time, subsequent processing requires the distance.

A note about periodic images: Before computing the neighbors, this operation translates all atoms to within the unit cell (having fractional coordinates within [0,1)). This means that the “image” of a site does not correspond to how much it has been translates from its current position, but which image of the unit cell it resides.

Parameters:
  • r (float) – Radius of sphere.

  • include_index (bool) – Deprecated. Now, the non-supercell site index is always included in the returned data.

  • include_image (bool) – Deprecated. Now the supercell image is always included in the returned data.

  • sites (list of Sites or None) – sites for getting all neighbors, default is None, which means neighbors will be obtained for all sites. This is useful in the situation where you are interested only in one subspecies type, and makes it a lot faster.

  • numerical_tol (float) – This is a numerical tolerance for distances. Sites which are < numerical_tol are determined to be coincident with the site. Sites which are r + numerical_tol away is deemed to be within r from the site. The default of 1e-8 should be ok in most instances.

Returns:

Neighbors for each site in structure.

Return type:

list[list[PeriodicNeighbor]]

get_distance(i: int, j: int, jimage=None) float[source]

Get distance between site i and j assuming periodic boundary conditions. If the index jimage of two sites atom j is not specified it selects the jimage nearest to the i atom and returns the distance and jimage indices in terms of lattice vector translations if the index jimage of atom j is specified it returns the distance between the i atom and the specified jimage atom.

Parameters:
  • i (int) – 1st site index

  • j (int) – 2nd site index

  • jimage – Number of lattice translations in each lattice direction. Default is None for nearest image.

Returns:

distance

get_miller_index_from_site_indexes(site_ids: list[int], round_dp: int = 4, verbose: bool = True) MillerIndex[source]

Get the Miller index of a plane from a set of sites indexes.

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

Parameters:
  • site_ids (list[int]) – A list of site indexes to consider. A minimum of three site indexes are required. If more than three sites are provided, the best plane that minimises the distance to all sites will be calculated.

  • 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_neighbor_list(r: float, sites: Sequence[PeriodicSite] | None = None, numerical_tol: float = 1e-08, exclude_self: bool = True) tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray][source]

Get neighbor lists using numpy array representations without constructing Neighbor objects. If the cython extension is installed, this method will be orders of magnitude faster than get_all_neighbors_old and 2-3x faster than get_all_neighbors. The returned values are a tuple of numpy arrays (center_indices, points_indices, offset_vectors, distances). Atom center_indices[i] has neighbor atom points_indices[i] that is translated by offset_vectors[i] lattice vectors, and the distance is distances[i].

Parameters:
  • r (float) – Radius of sphere

  • sites (list of Sites or None) – sites for getting all neighbors, default is None, which means neighbors will be obtained for all sites. This is useful in the situation where you are interested only in one subspecies type, and makes it a lot faster.

  • numerical_tol (float) – This is a numerical tolerance for distances. Sites which are < numerical_tol are determined to be coincident with the site. Sites which are r + numerical_tol away is deemed to be within r from the site. The default of 1e-8 should be ok in most instances.

  • exclude_self (bool) – whether to exclude atom neighboring with itself within numerical tolerance distance, default to True

Returns:

(center_indices, points_indices, offset_vectors, distances)

Return type:

tuple

get_neighbors(site: PeriodicSite, r: float, include_index: bool = False, include_image: bool = False) list[PeriodicNeighbor][source]

Get all neighbors to a site within a sphere of radius r. Excludes the site itself.

Parameters:
  • site (Site) – Which is the center of the sphere.

  • r (float) – Radius of sphere.

  • include_index (bool) – Deprecated. Now, the non-supercell site index is always included in the returned data.

  • include_image (bool) – Deprecated. Now the supercell image is always included in the returned data.

Returns:

PeriodicNeighbor

get_neighbors_in_shell(origin: ArrayLike, r: float, dr: float, include_index: bool = False, include_image: bool = False) list[PeriodicNeighbor][source]

Get all sites in a shell centered on origin (coords) between radii r-dr and r+dr.

Parameters:
  • origin (3x1 array) – Cartesian coordinates of center of sphere.

  • r (float) – Inner radius of shell.

  • dr (float) – Width of shell.

  • include_index (bool) – Deprecated. Now, the non-supercell site index is always included in the returned data.

  • include_image (bool) – Deprecated. Now the supercell image is always included in the returned data.

Returns:

[NearestNeighbor] where Nearest Neighbor is a named tuple containing (site, distance, index, image).

get_neighbors_old(site, r, include_index=False, include_image=False)[source]

Get all neighbors to a site within a sphere of radius r. Excludes the site itself.

Parameters:
  • site (Site) – Which is the center of the sphere.

  • r (float) – Radius of sphere.

  • include_index (bool) – Whether the non-supercell site index is included in the returned data

  • include_image (bool) – Whether to include the supercell image is included in the returned data

Returns:

PeriodicNeighbor

get_orderings(mode: Literal['enum', 'sqs'] = 'enum', **kwargs) list[Structure][source]

Get list of orderings for a disordered structure. If structure does not contain disorder, the default structure is returned.

Parameters:
  • mode ("enum" | "sqs") – Either “enum” or “sqs”. If enum, the enumlib will be used to return all distinct orderings. If sqs, mcsqs will be used to return an sqs structure.

  • kwargs – kwargs passed to either pymatgen.command_line..enumlib_caller.EnumlibAdaptor or pymatgen.command_line.mcsqs_caller.run_mcsqs. For run_mcsqs, a default cluster search of 2 cluster interactions with 1NN distance and 3 cluster interactions with 2NN distance is set.

Returns:

List[Structure]

get_primitive_structure(tolerance: float = 0.25, use_site_props: bool = False, constrain_latt: list | dict | None = None) Self[source]

Find a smaller unit cell than the input. Sometimes it doesn’t find the smallest possible one, so this method is recursively called until it is unable to find a smaller cell.

NOTE: If the tolerance is greater than 1/2 of the minimum inter-site distance in the primitive cell, the algorithm will reject this lattice.

Parameters:
  • tolerance (float) – Tolerance for each coordinate of a particular site in Angstroms. For example, [0.1, 0, 0.1] in cartesian coordinates will be considered to be on the same coordinates as [0, 0, 0] for a tolerance of 0.25. Defaults to 0.25.

  • use_site_props (bool) – Whether to account for site properties in differentiating sites.

  • constrain_latt (list/dict) – List of lattice parameters we want to preserve, e.g. [“alpha”, “c”] or dict with the lattice parameter names as keys and values we want the parameters to be e.g. {“alpha”: 90, “c”: 2.5}.

Returns:

The most primitive structure found.

get_reduced_structure(reduction_algo: Literal['niggli', 'LLL'] = 'niggli') Self[source]

Get a reduced structure.

Parameters:

reduction_algo ("niggli" | "LLL") – The lattice reduction algorithm to use. Defaults to “niggli”.

Returns:

Niggli- or LLL-reduced structure.

Return type:

Structure

get_sites_in_sphere(pt: ArrayLike, r: float, include_index: bool = False, include_image: bool = False) list[PeriodicNeighbor][source]

Find all sites within a sphere from the point, including a site (if any) sitting on the point itself. 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:
  • pt (3x1 array) – Cartesian coordinates of center of sphere.

  • r (float) – Radius of sphere in Angstrom.

  • include_index (bool) – Whether the non-supercell site index is included in the returned data.

  • include_image (bool) – Whether to include the supercell image is included in the returned data.

Returns:

PeriodicNeighbor

get_sorted_structure(key: Callable | None = None, reverse: bool = False) Self | Structure[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.

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.

get_space_group_info(symprec: float = 0.01, angle_tolerance: float = 5.0) tuple[str, int][source]

Get the spacegroup of a structure.

Parameters:
  • symprec (float) – Same definition as in SpacegroupAnalyzer. Defaults to 1e-2.

  • angle_tolerance (float) – Same definition as in SpacegroupAnalyzer. Defaults to 5 degrees.

Returns:

spacegroup_symbol, international_number

Raises:
  • pymatgen.symmetry.analyzer.SymmetryUndeterminedError if symmetry cannot

  • be determined. This can happen for numerical reasons, for example if

  • atoms are placed unphysically close together.

get_symmetric_neighbor_list(r: float, sg: str | None, unique: bool = False, numerical_tol: float = 1e-08, exclude_self: bool = True) tuple[ndarray, ...][source]

Similar to ‘get_neighbor_list’ with sites=None, but the neighbors are grouped by symmetry. The returned values are a tuple of numpy arrays (center_indices, points_indices, offset_vectors, distances, symmetry_indices). Atom center_indices[i] has neighbor atom points_indices[i] that is translated by offset_vectors[i] lattice vectors, and the distance is distances[i]. Symmetry_idx groups the bonds that are related by a symmetry of the provided space group and symmetry_op is the operation that relates the first bond of the same symmetry_idx to the respective atom. The first bond maps onto itself via the Identity. The output is sorted w.r.t. to symmetry_indices. If unique is True only one of the two bonds connecting two points is given. Out of the two, the bond that does not reverse the sites is chosen.

Parameters:
  • r (float) – Radius of sphere

  • sg (str | int) – The spacegroup the symmetry operations of which will be used to classify the neighbors. If a string, it will be interpreted as one of the notations supported by pymatgen.symmetry.groups.Spacegroup. e.g. “R-3c” or “Fm-3m”. If an int, it will be interpreted as an international number. If None, ‘get_space_group_info’ will be used to determine the space group, default to None.

  • unique (bool) – Whether a bond is given for both, or only a single direction is given. The default is False.

  • numerical_tol (float) – This is a numerical tolerance for distances. Sites which are < numerical_tol are determined to be coincident with the site. Sites which are r + numerical_tol away is deemed to be within r from the site. The default of 1e-8 should be ok in most instances.

  • exclude_self (bool) – whether to exclude atom neighboring with itself within numerical tolerance distance, default to True

Returns:

(center_indices, points_indices, offset_vectors, distances,

symmetry_indices, symmetry_ops)

Return type:

tuple

interpolate(end_structure: Self | Structure, nimages: int | Iterable = 10, interpolate_lattices: bool = False, pbc: bool = True, autosort_tol: float = 0, end_amplitude: float = 1) list[Self][source]

Interpolate between this structure and end_structure. Useful for construction of NEB inputs. To obtain useful results, the cell setting and order of sites must consistent across the start and end structures.

Parameters:
  • end_structure (Structure) – structure to interpolate between this structure and end. Must be in the same setting and have the same site ordering to yield useful results.

  • nimages (int,list) – No. of interpolation images or a list of interpolation images. Defaults to 10 images.

  • interpolate_lattices (bool) – Whether to interpolate the lattices. Interpolates the lengths and angles (rather than the matrix) so orientation may be affected.

  • pbc (bool) – Whether to use periodic boundary conditions to find the shortest path between endpoints.

  • autosort_tol (float) – A distance tolerance in angstrom in which to automatically sort end_structure to match to the closest points in this particular structure. This is usually what you want in a NEB calculation. 0 implies no sorting. Otherwise, a 0.5 value usually works pretty well.

  • end_amplitude (float) – The fractional amplitude of the endpoint of the interpolation, or a cofactor of the distortion vector connecting structure to end_structure. Thus, 0 implies no distortion, 1 implies full distortion to end_structure (default), 0.5 implies distortion to a point halfway between structure and end_structure, and -1 implies full distortion in the opposite direction to end_structure.

Returns:

List of interpolated structures. The starting and ending structures included as the first and last structures respectively. A total of (nimages + 1) structures are returned.

property is_3d_periodic: bool[source]

Whether the Lattice is periodic in all directions.

property lattice: Lattice[source]

Lattice of the structure.

matches(other: Self | Structure, anonymous: bool = False, **kwargs) bool[source]

Check whether this structure is similar to another structure. Basically a convenience method to call structure matching.

Parameters:
  • other (IStructure | Structure) – Another structure.

  • anonymous (bool) – Whether to use anonymous structure matching which allows distinct species in one structure to map to another.

  • **kwargs – Same **kwargs as in pymatgen.analysis.structure_matcher.StructureMatcher.

Returns:

True if the structures are similar under some affine transformation.

Return type:

bool

property pbc: PbcLike[source]

The periodicity of the structure.

property properties: dict[source]

Properties associated with the whole Structure. Note that this information is only guaranteed to be saved if serializing to native pymatgen output formats (JSON/YAML).

to(filename: PathLike = '', fmt: FileFormats = '', **kwargs) str[source]

Output the structure to a file or string.

Parameters:
  • filename (PathLike) – If provided, output will be written to a file. If fmt is not specified, the format is determined from the filename. Defaults is None, i.e. string output.

  • fmt (str) – Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include “cif”, “poscar”, “cssr”, “json”, “xsf”, “mcsqs”, “prismatic”, “yaml”, “yml”, “fleur-inpgen”, “pwmat”, “aims”. Non-case sensitive.

  • **kwargs – Kwargs passthru to relevant methods. e.g. This allows the passing of parameters like symprec to the CifWriter.__init__ method for generation of symmetric CIFs.

Returns:

String representation of molecule in given format. If a filename

is provided, the same string is written to the file.

Return type:

str

to_cell(cell_type: Literal['primitive', 'conventional'], **kwargs) Structure[source]

Get a cell based on the current structure.

Parameters:
  • cell_type ("primitive" | "conventional") – Whether to return a primitive or conventional cell.

  • kwargs – Any keyword supported by pymatgen.symmetry.analyzer.SpacegroupAnalyzer such as symprec=0.01, angle_tolerance=5, international_monoclinic=True and keep_site_properties=False.

Returns:

with the requested cell type.

Return type:

Structure

to_conventional(**kwargs) Structure[source]

Get a conventional cell based on the current structure.

Parameters:

kwargs – Any keyword supported by pymatgen.symmetry.analyzer.SpacegroupAnalyzer such as symprec=0.01, angle_tolerance=5, international_monoclinic=True and keep_site_properties=False.

Returns:

with the requested cell type.

Return type:

Structure

to_primitive(**kwargs) Structure[source]

Get a primitive cell based on the current structure.

Parameters:

kwargs – Any keyword supported by pymatgen.symmetry.analyzer.SpacegroupAnalyzer such as symprec=0.01, angle_tolerance=5, international_monoclinic=True and keep_site_properties=False.

Returns:

with the requested cell type.

Return type:

Structure

unset_charge() None[source]

Reset the charge to None. E.g. to compute it dynamically based on oxidation states.

property volume: float[source]

The volume of the structure in Angstrom^3.

class Molecule(species: Sequence[SpeciesLike], coords: Sequence[ArrayLike], charge: float = 0.0, spin_multiplicity: int | None = None, validate_proximity: bool = False, site_properties: dict | None = None, labels: Sequence[str | None] | None = None, charge_spin_check: bool = True, properties: dict | None = None)[source]

Bases: IMolecule, MutableSequence

Mutable Molecule. It has all the methods in IMolecule, and allows a user to perform edits on the molecule.

Create a mutable Molecule.

Parameters:
  • species – list of atomic species. Possible kinds of input include a list of dict of elements/species and occupancies, a List of elements/specie specified as actual Element/Species, Strings (“Fe”, “Fe2+”) or atomic numbers (1,56).

  • coords (3x1 array) – list of Cartesian coordinates of each species.

  • charge (float) – Charge for the molecule. Defaults to 0.

  • spin_multiplicity (int) – Spin multiplicity for molecule. Defaults to None, which means that the spin multiplicity is set to 1 if the molecule has no unpaired electrons and to 2 if there are unpaired electrons.

  • validate_proximity (bool) – Whether to check if there are sites that are less than 1 Ang apart. 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.

  • labels (list[str]) – Labels associated with the sites as a list of strings, e.g. [‘Li1’, ‘Li2’]. Must have the same length as the species and fractional coords. Defaults to None for no labels.

  • charge_spin_check (bool) – Whether to check that the charge and spin multiplicity are compatible with each other. Defaults to True.

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

append(species: CompositionLike, coords: ArrayLike, validate_proximity: bool = False, properties: dict | None = None) Self[source]

Append a site to the molecule.

Parameters:
  • species – Species of inserted site

  • coords – Coordinates of inserted site

  • validate_proximity (bool) – Whether to check if inserted site is too close to an existing site. Defaults to False.

  • properties (dict) – A dict of properties for the Site.

Returns:

New molecule with inserted site.

apply_operation(symm_op: SymmOp) Self[source]

Apply a symmetry operation to the molecule.

Parameters:

symm_op (SymmOp) – Symmetry operation to apply.

Returns:

self after symmetry operation.

Return type:

Molecule

calculate(calculator: Literal['gfn2-xtb'] | Calculator = 'gfn2-xtb', verbose: bool = False) Calculator[source]

Perform an ASE calculation.

Parameters:
  • calculator – An ASE Calculator or “gfn2-xtb”. Defaults to ‘gfn2-xtb’.

  • verbose (bool) – whether to print stdout. Defaults to False.

Returns:

ASE Calculator instance with a results attribute containing the output.

Return type:

Calculator

insert(idx: int, species: CompositionLike, coords: ArrayLike, validate_proximity: bool = False, properties: dict | None = None, label: str | None = None) Self[source]

Insert a site to the molecule.

Parameters:
  • idx (int) – Index to insert site

  • species – species of inserted site

  • coords (3x1 array) – coordinates of inserted site

  • validate_proximity (bool) – Whether to check if inserted site is too close to an existing site. Defaults to True.

  • properties (dict) – Dict of properties for the Site.

  • label (str) – Label of inserted site

Returns:

New molecule with inserted site.

perturb(distance: float) Self[source]

Perform a random perturbation of the sites in a structure to break symmetries.

Parameters:

distance (float) – Distance in angstroms by which to perturb each site.

Returns:

self with perturbed sites.

Return type:

Molecule

relax(calculator: str | Calculator = 'gfn2-xtb', optimizer: str | Optimizer = 'FIRE', steps: int = 500, fmax: float = 0.1, opt_kwargs: dict | None = None, return_trajectory: bool = False, verbose: bool = False) Self | tuple[Self, TrajectoryObserver][source]

Perform a molecule relaxation using an ASE calculator.

Parameters:
  • calculator – An ASE Calculator or a string from the following options: “gfn2-xtb”. Defaults to ‘gfn2-xtb’.

  • optimizer (str) – name of the ASE optimizer class to use

  • steps (int) – max number of steps for relaxation. Defaults to 500.

  • fmax (float) – total force tolerance for relaxation convergence. Defaults to 0.1 eV/A.

  • opt_kwargs (dict) – kwargs for the ASE optimizer class.

  • return_trajectory (bool) – Whether to return the trajectory of relaxation. Defaults to False.

  • verbose (bool) – whether to print out relaxation steps. Defaults to False.

Returns:

Relaxed Molecule or if return_trajectory=True,

2-tuple of Molecule and ASE TrajectoryObserver.

Return type:

Molecule | tuple[Molecule, Trajectory]

remove_sites(indices: Sequence[int]) Self[source]

Delete sites with at indices.

Parameters:

indices – Sequence of indices of sites to delete.

Returns:

self with sites removed.

Return type:

Molecule

remove_species(species: Sequence[SpeciesLike]) Self[source]

Remove all occurrences of a species from a molecule.

Parameters:

species – Species to remove.

Returns:

self with species removed.

Return type:

Molecule

rotate_sites(indices: Sequence[int] | None = None, theta: float = 0.0, axis: ArrayLike | None = None, anchor: ArrayLike | None = None) Self[source]

Rotate specific sites by some angle around vector at anchor.

Parameters:
  • indices (list) – List of site indices on which to perform the translation.

  • theta (float) – Angle in radians

  • axis (3x1 array) – Rotation axis vector.

  • anchor (3x1 array) – Point of rotation.

Returns:

self with rotated sites.

Return type:

Molecule

set_charge_and_spin(charge: float, spin_multiplicity: int | None = None) Self[source]

Set the charge and spin multiplicity.

Parameters:
  • charge (int) – Charge for the molecule. Defaults to 0.

  • spin_multiplicity (int) – Spin multiplicity for molecule. Defaults to None, which means that the spin multiplicity is set to 1 if the molecule has no unpaired electrons and to 2 if there are unpaired electrons.

Returns:

self with new charge and spin multiplicity set.

Return type:

Molecule

substitute(index: int, func_group: IMolecule | Self | str, bond_order: int = 1) Self[source]

Substitute atom at index with a functional group.

Parameters:
  • index (int) – Index of atom to substitute.

  • func_group

    Substituent molecule. There are two options:

    1. Providing an actual molecule as the input. The first atom must be a DummySpecies X, indicating the position of nearest neighbor. The second atom must be the next nearest atom. For example, for a methyl group substitution, func_group should be X-CH3, where X is the first site and C is the second site. What the code will do is to remove the index site, and connect the nearest neighbor to the C atom in CH3. The X-C bond indicates the directionality to connect the atoms.

    2. A string name. The molecule will be obtained from the relevant template in func_groups.json.

  • bond_order (int) – A specified bond order to calculate the bond length between the attached functional group and the nearest neighbor site. Defaults to 1.

Returns:

self after substitution.

Return type:

Molecule

translate_sites(indices: Sequence[int] | None = None, vector: ArrayLike | None = None) Self[source]

Translate specific sites by some vector, keeping the sites within the unit cell.

Parameters:
  • indices (list) – List of site indices on which to perform the translation.

  • vector (3x1 array) – Translation vector for sites.

Returns:

self with translated sites.

Return type:

Molecule

class Neighbor(species: Composition, coords: NDArray, properties: dict | None = None, nn_distance: float = 0.0, index: int = 0, label: str | None = None)[source]

Bases: Site

Simple Site subclass to contain a neighboring atom that skips all the unnecessary checks for speed. Can be used as a fixed-length tuple of size 3 to retain backwards compatibility with past use cases.

(site, nn_distance, index).

In future, usage should be to call attributes, e.g. Neighbor.index, Neighbor.distance, etc.

Parameters:
  • species – Same as Site

  • coords – Same as Site, but must be fractional.

  • properties – Same as Site

  • nn_distance – Distance to some other Site.

  • index – Index within structure.

  • label – Label for the site. Defaults to None.

as_dict() dict[source]

Note that method calls the super of Site, which is MSONable itself.

classmethod from_dict(dct: dict) Site[source]

Get a Neighbor from a dict.

Parameters:

dct – MSONable dict format.

Returns:

Neighbor

class PeriodicNeighbor(species: Composition, coords: NDArray, lattice: Lattice, properties: dict | None = None, nn_distance: float = 0.0, index: int = 0, image: tuple = (0, 0, 0), label: str | None = None)[source]

Bases: PeriodicSite

Simple PeriodicSite subclass to contain a neighboring atom that skips all the unnecessary checks for speed. Can be used as a fixed-length tuple of size 4 to retain backwards compatibility with past use cases:

(site, distance, index, image).

Should access attributes in the future, e.g. PeriodicNeighbor.index, PeriodicNeighbor.distance, etc.

Parameters:
  • species (Composition) – Same as PeriodicSite

  • coords (np.ndarray) – Same as PeriodicSite, but must be fractional.

  • lattice (Lattice) – Same as PeriodicSite

  • properties (dict, optional) – Same as PeriodicSite. Defaults to None.

  • nn_distance (float, optional) – Distance to some other Site.. Defaults to 0.0.

  • index (int, optional) – Index within structure.. Defaults to 0.

  • image (tuple, optional) – PeriodicImage. Defaults to (0, 0, 0).

  • label (str, optional) – Label for the site. Defaults to None.

as_dict() dict[source]

Note that method calls the super of Site, which is MSONable itself.

property coords: NDArray[source]

Cartesian coords.

classmethod from_dict(dct: dict) Self[source]

Get a PeriodicNeighbor from a dict.

Parameters:

dct – MSONable dict format.

Returns:

PeriodicNeighbor

class SiteCollection[source]

Bases: Sequence, ABC

Basic SiteCollection. Essentially a sequence of Sites or PeriodicSites. This serves as a base class for Molecule (a collection of Site, i.e., no periodicity) and Structure (a collection of PeriodicSites, i.e., periodicity). Not meant to be instantiated directly.

DISTANCE_TOLERANCE = 0.5[source]
add_oxidation_state_by_element(oxidation_states: dict[str, float]) Self[source]

Add oxidation states.

Parameters:

oxidation_states (dict) – Dict of oxidation states. e.g. {“Li”:1, “Fe”:2, “P”:5, “O”:-2}

Raises:

ValueError if oxidation states are not specified for all elements.

Returns:

self with oxidation states.

Return type:

SiteCollection

add_oxidation_state_by_guess(**kwargs) Self[source]

Decorates the structure with oxidation state, guessing using Composition.oxi_state_guesses(). If multiple guesses are found we take the first one.

Parameters:

**kwargs – parameters to pass into oxi_state_guesses()

add_oxidation_state_by_site(oxidation_states: list[float]) Self[source]

Add oxidation states to a structure by site.

Parameters:

oxidation_states (list[float]) – List of oxidation states. E.g. [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2]

Raises:

ValueError if oxidation states are not specified for all sites.

Returns:

self with oxidation states.

Return type:

SiteCollection

add_site_property(property_name: str, values: Sequence | np.ndarray) Self[source]

Add a property to a site. Note: This is the preferred method for adding magnetic moments, selective dynamics, and related site-specific properties to a structure/molecule object.

Examples

structure.add_site_property(“magmom”, [1.0, 0.0]) structure.add_site_property(“selective_dynamics”, [[True, True, True], [False, False, False]])

Parameters:
  • property_name (str) – The name of the property to add.

  • values (list) – A sequence of values. Must be same length as number of sites.

Raises:

ValueError – if len(values) != number of sites.

Returns:

self with site property added.

Return type:

SiteCollection

add_spin_by_element(spins: dict[str, float]) Self[source]

Add spin states to structure.

Parameters:

spins (dict) – Dict of spins associated with elements or species, e.g. {“Ni”:+5} or {“Ni2+”:5}

add_spin_by_site(spins: Sequence[float]) Self[source]

Add spin states to structure by site.

Parameters:

spins (list) – e.g. [+5, -5, 0, 0]

property alphabetical_formula: str[source]

The formula as a string.

property atomic_numbers: tuple[int, ...][source]

Tuple of atomic numbers.

property cart_coords: ndarray[source]

An np.array of the Cartesian coordinates of sites in the structure.

property charge: float[source]

The net charge of the structure based on oxidation states. If Elements are found, a charge of 0 is assumed.

property chemical_system: str[source]

The chemical system of the structure.

property chemical_system_set: set[str][source]

The set of chemical systems in the structure. E.g. {“Al”, “Ga”, “In”, “N”} for a AlGaInN quaternary.

property composition: Composition[source]

The structure’s corresponding Composition object.

abstract copy() Self[source]

Get a copy of itself. Concrete subclasses should implement this method.

property distance_matrix: ndarray[source]

The distance matrix between all sites in the structure. For periodic structures, this is overwritten to return the nearest image distance.

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

The elements in the structure as a list of Element objects.

extract_cluster(target_sites: list[Site], **kwargs) list[Site][source]

Extract a cluster of atoms based on bond lengths.

Parameters:
  • target_sites (list[Site]) – Initial sites from which to nucleate cluster.

  • **kwargs – kwargs passed through to CovalentBond.is_bonded.

Returns:

list[Site/PeriodicSite] Cluster of atoms.

property formula: str[source]

The formula as a string.

from_ase_atoms(**kwargs) Structure[source]

Convert ase.Atoms to pymatgen Structure.

Parameters:

kwargs – Passed to AseAtomsAdaptor.get_structure.

Returns:

Structure

abstract classmethod from_file(filename: str) None[source]

Read in SiteCollection from a filename.

abstract classmethod from_str(input_string: str, fmt: Any) None[source]

Read in SiteCollection from a string.

get_angle(i: int, j: int, k: int) float[source]

Get angle specified by three sites.

Parameters:
  • i – 1st site index

  • j – 2nd site index

  • k – 3rd site index

Returns:

Angle in degrees.

get_dihedral(i: int, j: int, k: int, l: int) float[source]

Get dihedral angle specified by four sites.

Parameters:
  • i (int) – 1st site index

  • j (int) – 2nd site index

  • k (int) – 3rd site index

  • l (int) – 4th site index

Returns:

Dihedral angle in degrees.

abstract get_distance(i: int, j: int) float[source]

Get distance between sites at index i and j.

Parameters:
  • i – 1st site index

  • j – 2nd site index

Returns:

Distance between sites at index i and index j.

group_by_types() Iterator[Site | PeriodicSite][source]

Iterate over species grouped by type.

indices_from_symbol(symbol: str) tuple[int, ...][source]

Get a tuple with the sequential indices of the sites that contain an element with the given chemical symbol.

property is_ordered: bool[source]

Check if structure is ordered, meaning no partial occupancies in any of the sites.

is_valid(tol: float = 0.5) bool[source]

True if SiteCollection does not contain atoms that are too close together. Note that the distance definition is based on type of SiteCollection. Cartesian distances are used for non-periodic Molecules, while PBC is taken into account for periodic structures.

Parameters:

tol (float) – Distance tolerance. Default is 0.5 Angstrom, which is fairly large.

Returns:

True if SiteCollection does not contain atoms that are too close together.

Return type:

bool

property labels: list[str | None][source]

Site labels as a list.

property n_elems: int[source]

Number of types of atoms.

property ntypesp: int[source]

Number of types of atoms.

property num_sites: int[source]

Number of sites.

property reduced_formula: str[source]

The reduced formula as a string.

relabel_sites(ignore_uniq: bool = False) Self[source]

Relabel sites to ensure they are unique.

Site labels are updated in-place, and relabeled by suffixing _1, _2, …, _n for duplicates. Call Structure.copy().relabel_sites() to avoid modifying the original structure.

Parameters:

ignore_uniq (bool) – If True, do not relabel sites that already have unique labels. Defaults to False.

Returns:

self with relabeled sites.

Return type:

SiteCollection

remove_oxidation_states() Self[source]

Removes oxidation states from a structure.

remove_site_property(property_name: str) Self[source]

Removes a property to a site.

Parameters:

property_name (str) – The name of the property to remove.

Returns:

self with property removed.

Return type:

SiteCollection

remove_spin() Self[source]

Remove spin states from structure.

replace_species(species_mapping: dict[SpeciesLike, SpeciesLike | dict[SpeciesLike, float]], in_place: bool = True) Self[source]

Replace species.

Note that this resets the label of any affected site to species_string.

Parameters:
  • species_mapping (dict) – Species to swap. Species can be elements too. e.g. {Element(“Li”): Element(“Na”)} performs a Li for Na substitution. The second species can be a sp_and_occu dict. For example, a site with 0.5 Si that is passed the mapping {Element(‘Si’): {Element(‘Ge’): 0.75, Element(‘C’): 0.25} } will have .375 Ge and .125 C.

  • in_place (bool) – Whether to perform the substitution in place or modify a copy. Defaults to True.

Returns:

self or new SiteCollection (depending on in_place) with species replaced.

Return type:

SiteCollection

property site_properties: dict[str, Sequence][source]

The site properties as a dict of sequences. E.g. {“magmom”: (5, -5), “charge”: (-4, 4)}.

property sites: list[PeriodicSite] | tuple[PeriodicSite, ...][source]

The sites in the Structure.

property species: list[Element | Species][source]

Only works for ordered structures.

Raises:

AttributeError – If structure is disordered.

Returns:

species at each site of the structure.

Return type:

list[Species]

property species_and_occu: list[Composition][source]

List of species and occupancies at each site of the structure.

property symbol_set: tuple[str, ...][source]

Tuple with the set of chemical symbols. Note that len(symbol_set) == len(types_of_specie).

abstract to(filename: str = '', fmt: Literal['cif', 'poscar', 'cssr', 'json', 'yaml', 'yml', 'xsf', 'mcsqs', 'res', 'pwmat', 'aims', ''] = '') str | None[source]

Generate string representations (cif, json, poscar, ….) of SiteCollections (e.g., molecules / structures). Should return str or None if written to a file.

to_ase_atoms(**kwargs) Atoms[source]

Convert the structure/molecule to an ase.Atoms object.

Parameters:

kwargs – Passed to ase.Atoms init.

Returns:

ase.Atoms

to_file(filename: str = '', fmt: Literal['cif', 'poscar', 'cssr', 'json', 'yaml', 'yml', 'xsf', 'mcsqs', 'res', 'pwmat', 'aims', ''] = '') str | None[source]

A more intuitive alias for .to().

property types_of_specie: tuple[Element | Species | DummySpecies, ...][source]

Specie -> Species rename, to maintain backwards compatibility.

property types_of_species: tuple[Element | Species | DummySpecies, ...][source]

Tuple of types of species.

class Structure(lattice: ArrayLike | Lattice, species: Sequence[CompositionLike], coords: Sequence[ArrayLike] | np.ndarray, charge: float | None = None, validate_proximity: bool = False, to_unit_cell: bool = False, coords_are_cartesian: bool = False, site_properties: dict | None = None, labels: Sequence[str | None] | None = None, properties: dict | None = None)[source]

Bases: IStructure, MutableSequence

Mutable version of structure.

Create a periodic structure.

Parameters:
  • lattice – The lattice, either as a pymatgen.core.Lattice or simply as any 2D 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

    List 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.

  • charge (float) – overall charge of the structure. Defaults to behavior in SiteCollection where total charge is the sum of the oxidation states.

  • 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 map all sites into the unit cell, i.e., fractional coords between 0 and 1. 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.

  • labels (list[str]) – Labels associated with the sites as a list of strings, e.g. [‘Li1’, ‘Li2’]. Must have the same length as the species and fractional coords. Defaults to None for no labels.

  • properties (dict) – Properties associated with the whole structure. Will be serialized when writing the structure to JSON or YAML but is lost when converting to other formats.

append(species: CompositionLike, coords: ArrayLike, coords_are_cartesian: bool = False, validate_proximity: bool = False, properties: dict | None = None) Self[source]

Append a site to the structure.

Parameters:
  • species – Species of inserted site

  • coords (3x1 array) – Coordinates of inserted site

  • coords_are_cartesian (bool) – Whether coordinates are cartesian. Defaults to False.

  • validate_proximity (bool) – Whether to check if inserted site is too close to an existing site. Defaults to False.

  • properties (dict) – Properties of the site.

Returns:

New structure with inserted site.

apply_operation(symm_op: SymmOp, fractional: bool = False) Self[source]

Apply a symmetry operation to the structure in place and return the modified structure. The lattice is operated on by the rotation matrix only. Coords are operated in full and then transformed to the new lattice.

Parameters:
  • symm_op (SymmOp) – Symmetry operation to apply.

  • fractional (bool) – Whether the symmetry operation is applied in fractional space. Defaults to False, i.e., symmetry operation is applied in Cartesian coordinates.

Returns:

post-operation structure

Return type:

Structure

apply_strain(strain: ArrayLike, inplace: bool = True) Self[source]

Apply a strain to the lattice.

Parameters:
  • strain (float or list) – Amount of strain to apply. Can be a float, or a sequence of 3 numbers. e.g. 0.01 means all lattice vectors are increased by 1%. This is equivalent to calling modify_lattice with a lattice with lattice parameters that are 1% larger.

  • inplace (bool) – True applies the strain in-place, False returns a Structure copy. Defaults to True.

Returns:

self if inplace=True else new structure with strain applied.

Return type:

Structure

calculate(calculator: str | Calculator = 'm3gnet', verbose: bool = False) Calculator[source]

Perform an ASE calculation.

Parameters:
  • calculator – An ASE Calculator or a string from the following options: “m3gnet”. Defaults to ‘m3gnet’, i.e. the M3GNet universal potential.

  • verbose (bool) – whether to print stdout. Defaults to False.

Returns:

ASE Calculator instance with a results attribute containing the output.

Return type:

Calculator

classmethod from_prototype(prototype: str, species: Sequence, **kwargs) Self[source]

Rapidly construct common prototype structures.

Parameters:
  • prototype – Name of prototype. e.g. cubic, rocksalt, perovksite etc.

  • species – List of species corresponding to symmetrically distinct sites.

  • **kwargs – Lattice parameters, e.g. a = 3.0, b = 4, c = 5. Only the required lattice parameters need to be specified. For example, if it is a cubic prototype, only a needs to be specified.

Returns:

with given prototype and species.

Return type:

Structure

insert(idx: int, species: CompositionLike, coords: ArrayLike, coords_are_cartesian: bool = False, validate_proximity: bool = False, properties: dict | None = None, label: str | None = None) Self[source]

Insert a site to the structure.

Parameters:
  • idx (int) – Index to insert site

  • species (species-like) – Species of inserted site

  • coords (3x1 array) – Coordinates of inserted site

  • coords_are_cartesian (bool) – Whether coordinates are cartesian. Defaults to False.

  • validate_proximity (bool) – Whether to check if inserted site is too close to an existing site. Controlled by self.DISTANCE_TOLERANCE. Defaults to False.

  • properties (dict) – Properties associated with the site.

  • label (str) – Label associated with the site.

Returns:

New structure with inserted site.

property lattice: Lattice[source]

Lattice associated with structure.

make_supercell(scaling_matrix: ArrayLike, to_unit_cell: bool = True, in_place: bool = True) Self[source]

Create a supercell.

Parameters:
  • scaling_matrix (ArrayLike) –

    A scaling matrix for transforming the lattice vectors. Has to be all integers. Several options are possible:

    1. A full 3x3 scaling matrix defining the linear combination the old lattice vectors. e.g. [[2,1,0],[0,3,0],[0,0, 1]] generates a new structure with lattice vectors a’ = 2a + b, b’ = 3b, c’ = c where a, b, and c are the lattice vectors of the original structure.

    2. An sequence of three scaling factors. e.g. [2, 1, 1] specifies that the supercell should have dimensions 2a x b x c.

    3. A number, which simply scales all lattice vectors by the same factor.

  • to_unit_cell (bool) – Whether or not to fold sites back into the unit cell if they have fractional coords > 1. Defaults to True.

  • in_place (bool) – Whether to perform the operation in-place or to return a new Structure object. Defaults to True.

Returns:

self if in_place is True else self.copy() after making supercell

Return type:

Structure

merge_sites(tol: float = 0.01, mode: Literal['sum', 'delete', 'average'] = 'sum') Self[source]

Merges sites (adding occupancies) within tol of each other. Removes site properties.

Parameters:
  • tol (float) – Tolerance for distance to merge sites.

  • mode ("sum" | "delete" | "average") – “delete” means duplicate sites are deleted. “sum” means the occupancies are summed for the sites. “average” means that the site is deleted but the properties are averaged Only first letter is considered.

Returns:

self with merged sites.

Return type:

Structure

perturb(distance: float, min_distance: float | None = None) Self[source]

Perform a random perturbation of the sites in a structure to break symmetries. Modifies the structure in place.

Parameters:
  • distance (float) – Distance in angstroms by which to perturb each site.

  • min_distance (None, int, or float) – if None, all displacements will be equal amplitude. If int or float, perturb each site a distance drawn from the uniform distribution between ‘min_distance’ and ‘distance’.

Returns:

self with perturbed sites.

Return type:

Structure

relax(calculator: str | Calculator = 'm3gnet', relax_cell: bool = True, optimizer: str | Optimizer = 'FIRE', steps: int = 500, fmax: float = 0.1, stress_weight: float = 0.01, opt_kwargs: dict | None = None, return_trajectory: bool = False, verbose: bool = False) Structure | tuple[Structure, TrajectoryObserver | Trajectory][source]

Perform a crystal structure relaxation using an ASE calculator.

Parameters:
  • calculator – An ASE Calculator or a string from the following options: “m3gnet”. Defaults to ‘m3gnet’, i.e. the M3GNet universal potential.

  • relax_cell (bool) – whether to relax the lattice cell. Defaults to True.

  • optimizer (str) – name of the ASE optimizer class to use

  • steps (int) – max number of steps for relaxation. Defaults to 500.

  • fmax (float) – total force tolerance for relaxation convergence. Here fmax is a sum of force and stress forces. Defaults to 0.1.

  • stress_weight (float) – the stress weight for relaxation with M3GNet. Defaults to 0.01.

  • opt_kwargs (dict) – kwargs for the ASE optimizer class.

  • return_trajectory (bool) – Whether to return the trajectory of relaxation. Defaults to False.

  • verbose (bool) – whether to print out relaxation steps. Defaults to False.

Returns:

Relaxed structure or if return_trajectory=True,

2-tuple of Structure and matgl TrajectoryObserver.

Return type:

Structure | tuple[Structure, Trajectory]

remove_sites(indices: Sequence[int | None]) Self[source]

Delete sites with at indices.

Parameters:

indices – Sequence of indices of sites to delete.

Returns:

self with sites removed.

Return type:

Structure

remove_species(species: Sequence[SpeciesLike]) Self[source]

Remove all occurrences of several species from a structure.

Parameters:

species – Sequence of species to remove, e.g. [“Li”, “Na”].

Returns:

self with species removed.

Return type:

Structure

replace(idx: int, species: CompositionLike, coords: ArrayLike | None = None, coords_are_cartesian: bool = False, properties: dict | None = None, label: str | None = None) Self[source]

Replace a single site. Takes either a species or a dict of species and occupations.

Parameters:
  • idx (int) – Index of the site in the sites list.

  • species (species-like) – Species of replacement site

  • coords (3x1 array) – Coordinates of replacement site. If None, the current coordinates are assumed.

  • coords_are_cartesian (bool) – Whether coordinates are cartesian. Defaults to False.

  • properties (dict) – Properties associated with the site.

  • label (str) – Label associated with the site.

Returns:

self with replaced site.

Return type:

Structure

rotate_sites(indices: list[int] | None = None, theta: float = 0.0, axis: ArrayLike | None = None, anchor: ArrayLike | None = None, to_unit_cell: bool = True) Self[source]

Rotate specific sites by some angle around vector at anchor. Modifies the structure in place.

Parameters:
  • indices (list) – List of site indices on which to perform the translation.

  • theta (float) – Angle in radians

  • axis (3x1 array) – Rotation axis vector.

  • anchor (3x1 array) – Point of rotation.

  • to_unit_cell (bool) – Whether new sites are transformed to unit cell

Returns:

self with rotated sites.

Return type:

Structure

scale_lattice(volume: float) Self[source]

Perform scaling of the lattice vectors so that length proportions and angles are preserved.

Parameters:

volume (float) – New volume of the unit cell in A^3.

Returns:

self with scaled lattice.

Return type:

Structure

set_charge(new_charge: float = 0.0) Self[source]

Set the overall structure charge.

Parameters:

new_charge (float) – new charge to set

Returns:

self with new charge set.

Return type:

Structure

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

Sort a structure in place. The parameters have the same meaning as in list.sort(). By default, sites are sorted by the electronegativity of the species. The difference between this method and get_sorted_structure (which also works in IStructure) is that the latter returns a new Structure, while this modifies the original.

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.

Returns:

self sorted.

Return type:

Structure

substitute(index: int, func_group: IMolecule | Molecule | str, bond_order: int = 1) Self[source]

Substitute atom at index with a functional group.

Parameters:
  • index (int) – Index of atom to substitute.

  • func_group

    Substituent molecule. There are two options:

    1. Providing an actual Molecule as the input. The first atom must be a DummySpecies X, indicating the position of nearest neighbor. The second atom must be the next nearest atom. For example, for a methyl group substitution, func_group should be X-CH3, where X is the first site and C is the second site. What the code will do is to remove the index site, and connect the nearest neighbor to the C atom in CH3. The X-C bond indicates the directionality to connect the atoms.

    2. A string name. The molecule will be obtained from the relevant template in func_groups.json.

  • bond_order (int) – A specified bond order to calculate the bond length between the attached functional group and the nearest neighbor site. Defaults to 1.

Returns:

self with functional group attached.

Return type:

Structure

translate_sites(indices: int | Sequence[int], vector: ArrayLike, frac_coords: bool = True, to_unit_cell: bool = True) Self[source]

Translate specific sites by some vector, keeping the sites within the unit cell. Modifies the structure in place.

Parameters:
  • indices – Integer or List of site indices on which to perform the translation.

  • vector – Translation vector for sites.

  • frac_coords (bool) – Whether the vector corresponds to fractional or Cartesian coordinates.

  • to_unit_cell (bool) – Whether new sites are transformed to unit cell

Returns:

self with translated sites.

Return type:

Structure

exception StructureError[source]

Bases: Exception

Exception class for Structure. Raised when the structure has problems, e.g. atoms that are too close.

pymatgen.core.surface module

This module implements representation of Slab, SlabGenerator for generating Slabs, ReconstructionGenerator to generate reconstructed Slabs, and some related utility functions.

If you use this module, please consider citing the following work:

  1. Tran, Z. Xu, B. Radhakrishnan, D. Winston, W. Sun, K. A. Persson,

S. P. Ong, “Surface Energies of Elemental Crystals”, Scientific Data, 2016, 3:160080, doi: 10.1038/sdata.2016.80.

Sun, W.; Ceder, G. Efficient creation and convergence of surface slabs, Surface Science, 2013, 617, 53-59, doi:10.1016/j.susc.2013.05.016.

class ReconstructionGenerator(initial_structure: Structure, min_slab_size: float, min_vacuum_size: float, reconstruction_name: str)[source]

Bases: object

Build a reconstructed Slab from a given initial Structure.

This class needs a pre-defined dictionary specifying the parameters needed such as the SlabGenerator parameters, transformation matrix, sites to remove/add and slab/vacuum sizes.

slabgen_params[source]

Parameters for the SlabGenerator.

Type:

dict

trans_matrix[source]

A 3x3 transformation matrix to generate the reconstructed slab. Only the a and b lattice vectors are actually changed while the c vector remains the same. This matrix is what the Wood’s notation is based on.

Type:

np.ndarray

reconstruction_json[source]

The full JSON or dictionary containing the instructions for building the slab.

Type:

dict

Generate reconstructed slabs from a set of instructions.

Parameters:
  • initial_structure (Structure) – Initial input structure. Note that to ensure that the Miller indices correspond to usual crystallographic definitions, you should supply a conventional unit cell structure.

  • min_slab_size (float) – Minimum Slab size in Angstrom.

  • min_vacuum_size (float) – Minimum vacuum layer size in Angstrom.

  • reconstruction_name (str) –

    Name of the dict containing the build instructions. The dictionary can contain any item, however any instructions archived in pymatgen for public use need to contain the following keys and items to ensure compatibility with the ReconstructionGenerator:

    ”name” (str): A descriptive name for the reconstruction,

    typically including the type of structure, the Miller index, the Wood’s notation and additional descriptors for the reconstruction. Example: “fcc_110_missing_row_1x2”

    ”description” (str): A detailed description of the

    reconstruction, intended to assist future contributors in avoiding duplicate entries. Please read the description carefully before adding to prevent duplications.

    ”reference” (str): Optional reference to the source of

    the reconstruction.

    ”spacegroup” (dict): A dictionary indicating the space group

    of the reconstruction. e.g. {“symbol”: “Fm-3m”, “number”: 225}.

    ”miller_index” ([h, k, l]): Miller index of the reconstruction “Woods_notation” (str): For a reconstruction, the a and b

    lattice may change to accommodate the symmetry. This notation indicates the change in the vectors relative to the primitive (p) or conventional (c) slab cell. E.g. p(2x1).

    Reference: Wood, E. A. (1964). Vocabulary of surface crystallography. Journal of Applied Physics, 35(4), 1306-1312.

    ”transformation_matrix” (numpy array): A 3x3 matrix to

    transform the slab. Only the a and b lattice vectors should change while the c vector remains the same.

    ”SlabGenerator_parameters” (dict): A dictionary containing

    the parameters for the SlabGenerator, excluding the miller_index, min_slab_size and min_vac_size. As the Miller index is already specified and the min_slab_size and min_vac_size can be changed regardless of the reconstruction type. Having a consistent set of SlabGenerator parameters allows for the instructions to be reused.

    ”points_to_remove” (list[site]): A list of sites to

    remove where the first two indices are fractional (in a and b) and the third index is in units of 1/d (in c), see the below “Notes” for details.

    ”points_to_add” (list[site]): A list of sites to add

    where the first two indices are fractional (in a an b) and the third index is in units of 1/d (in c), see the below “Notes” for details.

    ”base_reconstruction” (dict, Optional): A dictionary specifying

    an existing reconstruction model upon which the current reconstruction is built to avoid repetition. E.g. the alpha reconstruction of halites is based on the octopolar reconstruction but with the topmost atom removed. The dictionary for the alpha reconstruction would therefore contain the item “reconstruction_base”: “halite_111_octopolar_2x2”, and additional sites can be added by “points_to_add”.

Notes

  1. For “points_to_remove” and “points_to_add”, the third index

    for the c vector is specified in units of 1/d, where d represents the spacing between atoms along the hkl (the c vector), relative to the topmost site in the unreconstructed slab. For instance, a point of [0.5, 0.25, 1] corresponds to the 0.5 fractional coordinate of a, 0.25 fractional coordinate of b, and a distance of 1 atomic layer above the topmost site. Similarly, [0.5, 0.25, -0.5] corresponds to a point half an atomic layer below the topmost site, and [0.5, 0.25, 0] corresponds to a point at the same position along c as the topmost site. This approach is employed because while the primitive units of a and b remain constant, the user can vary the length of the c direction by adjusting the slab layer or the vacuum layer.

  2. The dictionary should only provide “points_to_remove” and

    “points_to_add” for the top surface. The ReconstructionGenerator will modify the bottom surface accordingly to return a symmetric Slab.

build_slabs() list[Slab][source]
Build reconstructed Slabs by:
  1. Obtaining the unreconstructed Slab using the specified parameters for the SlabGenerator.

  2. Applying the appropriate lattice transformation to the a and b lattice vectors.

  3. Remove and then add specified sites from both surfaces.

Returns:

The reconstructed slabs.

Return type:

list[Slab]

get_unreconstructed_slabs() list[Slab][source]

Generate the unreconstructed (super) Slabs.

TODO (@DanielYang59): this should be a private method.

class Slab(lattice: Lattice | np.ndarray, species: Sequence[Any], coords: np.ndarray, miller_index: MillerIndex, oriented_unit_cell: Structure, shift: float, scale_factor: np.ndarray, reorient_lattice: bool = True, validate_proximity: bool = False, to_unit_cell: bool = False, reconstruction: str | None = None, coords_are_cartesian: bool = False, site_properties: dict | None = None, energy: float | None = None)[source]

Bases: Structure

Hold information for a Slab, with additional attributes pertaining to slabs, but the init method does not actually create a slab. Also has additional methods that returns other information about a Slab such as the surface area, normal, and atom adsorption.

Note that all Slabs have the surface normal oriented perpendicular to the a and b lattice vectors. This means the lattice vectors a and b are in the surface plane and the c vector is out of the surface plane (though not necessarily perpendicular to the surface).

A Structure object with additional information and methods pertaining to Slabs.

Parameters:
  • lattice (Lattice/3x3 array) – The lattice, either as a pymatgen.core.Lattice or simply as any 2D array. Each row should correspond to a lattice vector. e.g. [[10,0,0], [20,10,0], [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.

  • miller_index (MillerIndex) – Miller index of plane parallel to surface. Note that this is referenced to the input structure. If you need this to be based on the conventional cell, you should supply the conventional structure.

  • oriented_unit_cell (Structure) – The oriented_unit_cell from which this Slab is created (by scaling in the c-direction).

  • shift (float) – The NEGATIVE of shift in the c-direction applied to get the termination.

  • scale_factor (np.ndarray) – scale_factor Final computed scale factor that brings the parent cell to the surface cell.

  • reorient_lattice (bool) – reorients the lattice parameters such that the c direction is along the z axis.

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

  • reconstruction (str) – Type of reconstruction. Defaults to None if the slab is not reconstructed.

  • to_unit_cell (bool) – Translates fractional coordinates 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.

  • energy (float) – A value for the energy.

add_adsorbate_atom(indices: list[int], species: str | Element | Species, distance: float, specie: Species | Element | str | None = None) Self[source]

Add adsorbate onto the Slab, along the c lattice vector.

Parameters:
  • indices (list[int]) – Indices of sites on which to put the adsorbate. Adsorbate will be placed relative to the center of these sites.

  • species (str | Element | Species) – The species to add.

  • distance (float) – between centers of the adsorbed atom and the given site in Angstroms, along the c lattice vector.

  • specie – Deprecated argument in #3691. Use ‘species’ instead.

Returns:

self with adsorbed atom.

Return type:

Slab

as_dict(**kwargs) dict[source]

MSONable dict.

property center_of_mass: ndarray[source]

The center of mass of the Slab in fractional coordinates.

copy(site_properties: dict[str, Any] | None = None) Self[source]

Get a copy of the Slab, with options to update site properties.

Parameters:

site_properties (dict) – Properties to update. The properties are specified in the same way as the constructor, i.e., as a dict of the form {property: [values]}.

Returns:

A copy of the Structure, with optionally new site_properties

property dipole: ndarray[source]

The dipole moment of the Slab in the direction of the surface normal.

Note that the Slab must be oxidation state decorated for this to work properly. Otherwise, the Slab will always have a dipole moment of 0.

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

dct – dict.

Returns:

Created from dict.

Return type:

Slab

get_orthogonal_c_slab() Self[source]

Generate a Slab where the normal (c lattice vector) is forced to be orthogonal to the surface a and b lattice vectors.

Note that this breaks inherent symmetries in the slab.

It should be pointed out that orthogonality is not required to get good surface energies, but it can be useful in cases where the slabs are subsequently used for postprocessing of some kind, e.g. generating grain boundaries or interfaces.

get_sorted_structure(key=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.

get_surface_sites(tag: bool = False) dict[str, list][source]

Get the surface sites and their indices in a dictionary. Useful for analysis involving broken bonds and for finding adsorption sites.

The oriented unit cell of the slab will determine the coordination number of a typical site. We use VoronoiNN to determine the coordination number of sites. Due to the pathological error resulting from some surface sites in the VoronoiNN, we assume any site that has this error is a surface site as well. This will only work for single-element systems for now.

Parameters:

tag (bool) – Add attribute “is_surf_site” (bool) to all sites of the Slab. Defaults to False.

Returns:

A dictionary grouping sites on top and bottom of the slab together.

{“top”: [sites with indices], “bottom”: [sites with indices]}

get_symmetric_site(point: ArrayLike, cartesian: bool = False) ArrayLike[source]

Use symmetry operations to find an equivalent site on the other side of the slab. Works mainly for slabs with Laue symmetry.

This is useful for retaining the non-polar and symmetric properties of a slab when creating adsorbed structures or symmetric reconstructions.

Parameters:
  • point (ArrayLike) – Fractional coordinate of the original site.

  • cartesian (bool) – Use Cartesian coordinates.

Returns:

Fractional coordinate. A site equivalent to the

original site, but on the other side of the slab

Return type:

ArrayLike

get_tasker2_slabs(tol: float = 0.01, same_species_only: bool = True) list[Self][source]

Get a list of slabs that have been Tasker 2 corrected.

Parameters:
  • tol (float) – Fractional tolerance to determine if atoms are within same plane.

  • same_species_only (bool) – If True, only those are of the exact same species as the atom at the outermost surface are considered for moving. Otherwise, all atoms regardless of species within tol are considered for moving. Default is True (usually the desired behavior).

Returns:

Tasker 2 corrected slabs.

Return type:

list[Slab]

is_polar(tol_dipole_per_unit_area: float = 0.001) bool[source]

Check if the Slab is polar by computing the normalized dipole per unit area. Normalized dipole per unit area is used as it is more reliable than using the absolute value, which varies with surface area.

Note that the Slab must be oxidation state decorated for this to work properly. Otherwise, the Slab will always have a dipole moment of 0.

Parameters:

tol_dipole_per_unit_area (float) – A tolerance above which the Slab is considered polar.

is_symmetric(symprec: float = 0.1) bool[source]
Check if Slab is symmetric, i.e., contains inversion, mirror on (hkl) plane,

or screw axis (rotation and translation) about [hkl].

Parameters:

symprec (float) – Symmetry precision used for SpaceGroup analyzer.

Returns:

True if surfaces are symmetric.

Return type:

bool

property normal: ndarray[source]

The surface normal vector of the Slab, normalized to unit length.

property surface_area: float[source]

The surface area of the Slab.

symmetrically_add_atom(species: str | Element | Species, point: ArrayLike, specie: str | Element | Species | None = None, coords_are_cartesian: bool = False) None[source]

Add a species at a selected site in a Slab. Will also add an equivalent site on the other side to maintain symmetry.

Parameters:
  • species (str | Element | Species) – The species to add.

  • point (ArrayLike) – The coordinate of the target site.

  • specie – Deprecated argument name in #3691. Use ‘species’ instead.

  • coords_are_cartesian (bool) – If the site is in Cartesian coordinates.

symmetrically_remove_atoms(indices: list[int]) None[source]

Remove sites from a list of indices. Will also remove the equivalent site on the other side of the slab to maintain symmetry.

Parameters:

indices (list[int]) – The indices of the sites to remove.

TODO(@DanielYang59): 1. Reuse public method get_symmetric_site to get equi sites? 2. If not 1, get_equi_sites has multiple nested loops

class SlabGenerator(initial_structure: Structure, miller_index: MillerIndex, min_slab_size: float, min_vacuum_size: float, lll_reduce: bool = False, center_slab: bool = False, in_unit_planes: bool = False, primitive: bool = True, max_normal_search: int | None = None, reorient_lattice: bool = True)[source]

Bases: object

Generate different slabs using shift values determined by where a unique termination can be found, along with other criteria such as where a termination doesn’t break a polyhedral bond. The shift value then indicates where the slab layer will begin and terminate in the slab-vacuum system.

oriented_unit_cell[source]

An oriented unit cell of the parent structure.

Type:

Structure

parent[source]

Parent structure from which Slab was derived.

Type:

Structure

lll_reduce[source]

Whether the slabs will be orthogonalized.

Type:

bool

center_slab[source]

Whether the slabs will be centered in the slab-vacuum system.

Type:

bool

slab_scale_factor[source]

Scale factor that brings the parent cell to the surface cell.

Type:

float

miller_index[source]

Miller index of plane parallel to surface.

Type:

tuple

min_slab_size[source]

Minimum size of layers containing atoms, in angstroms.

Type:

float

min_vac_size[source]

Minimum vacuum layer size, in angstroms.

Type:

float

Calculate the slab scale factor and uses it to generate an oriented unit cell (OUC) of the initial structure. Also stores the initial information needed later on to generate a slab.

Parameters:
  • initial_structure (Structure) – Initial input structure. Note that to ensure that the Miller indices correspond to usual crystallographic definitions, you should supply a conventional unit cell structure.

  • miller_index ([h, k, l]) – Miller index of the plane parallel to the surface. Note that this is referenced to the input structure. If you need this to be based on the conventional cell, you should supply the conventional structure.

  • min_slab_size (float) – In Angstroms or number of hkl planes

  • min_vacuum_size (float) – In Angstroms or number of hkl planes

  • lll_reduce (bool) – Whether to perform an LLL reduction on the final structure.

  • center_slab (bool) – Whether to center the slab in the cell with equal vacuum spacing from the top and bottom.

  • in_unit_planes (bool) – Whether to set min_slab_size and min_vac_size in number of hkl planes or Angstrom (default). Setting in units of planes is useful to ensure some slabs to have a certain number of layers, e.g. for Cs(100), 10 Ang will result in a slab with only 2 layers, whereas Fe(100) will have more layers. The slab thickness will be in min_slab_size/math.ceil(self._proj_height/dhkl) multiples of oriented unit cells.

  • primitive (bool) – Whether to reduce generated slabs to primitive cell. Note this does NOT generate a slab from a primitive cell, it means that after slab generation, we attempt to reduce the generated slab to primitive cell.

  • max_normal_search (int) – If set to a positive integer, the code will search for a normal lattice vector that is as perpendicular to the surface as possible, by considering multiple linear combinations of lattice vectors up to this value. This has no bearing on surface energies, but may be useful as a preliminary step to generate slabs for absorption or other sizes. It may not be the smallest possible cell for simulation. Normality is not guaranteed, but the oriented cell will have the c vector as normal as possible to the surface. The max absolute Miller index is usually sufficient.

  • reorient_lattice (bool) – reorient the lattice such that the c direction is parallel to the third lattice vector

get_slab(shift: float = 0, tol: float = 0.1, energy: float | None = None) Slab[source]
[Private method] Generate a slab based on a given termination

coordinate along the lattice c direction.

You should RARELY use this method directly.

Parameters:
  • shift (float) – The termination coordinate along the lattice c direction in fractional coordinates.

  • tol (float) – Tolerance to determine primitive cell.

  • energy (float) – The energy to assign to the slab.

Returns:

from a shifted oriented unit cell.

Return type:

Slab

get_slabs(bonds: dict[tuple[Species | Element, Species | Element], float] | None = None, ftol: float = 0.1, tol: float = 0.1, max_broken_bonds: int = 0, symmetrize: bool = False, repair: bool = False, ztol: float = 0, filter_out_sym_slabs: bool = True) list[Slab][source]

Generate slabs with shift values calculated from the internal gen_possible_terminations func. If the user decide to avoid breaking any polyhedral bond (by setting bonds), any shift value that do so would be filtered out.

Parameters:
  • bonds (dict) – A {(species1, species2): max_bond_dist} dict. For example, PO4 groups may be defined as {(“P”, “O”): 3}.

  • tol (float) – Fractional tolerance for getting primitive cells and matching structures.

  • ftol (float) – Threshold for fcluster to check if two atoms are on the same plane. Default to 0.1 Angstrom in the direction of the surface normal.

  • max_broken_bonds (int) – Maximum number of allowable broken bonds for the slab. Use this to limit number of slabs. Defaults to 0, which means no bonds could be broken.

  • symmetrize (bool) – Whether to enforce the equivalency of slab surfaces.

  • repair (bool) – Whether to repair terminations with broken bonds (True) or just omit them (False). Default to False as repairing terminations can lead to many more possible slabs.

  • ztol (float) – Fractional tolerance for determine overlapping z-ranges, smaller ztol might result in more possible Slabs.

  • filter_out_sym_slabs (bool) – If True filter out identical slabs with different terminations.

Returns:

All possible Slabs of a particular surface,

sorted by the number of bonds broken.

Return type:

list[Slab]

move_to_other_side(init_slab: Slab, index_of_sites: list[int]) Slab[source]

Move surface sites to the opposite surface of the Slab.

If a selected site resides on the top half of the Slab, it would be moved to the bottom side, and vice versa. The distance moved is equal to the thickness of the Slab.

Note

You should only use this method on sites close to the surface, otherwise it would end up deep inside the vacuum layer.

Parameters:
  • init_slab (Slab) – The Slab whose sites would be moved.

  • index_of_sites (list[int]) – Indices representing the sites to move.

Returns:

The Slab with selected sites moved.

Return type:

Slab

nonstoichiometric_symmetrized_slab(init_slab: Slab) list[Slab][source]

Symmetrize the two surfaces of a Slab, but may break the stoichiometry.

How it works:

1. Check whether two surfaces of the slab are equivalent. If the point group of the slab has an inversion symmetry ( ie. belong to one of the Laue groups), then it’s assumed that the surfaces are equivalent.

2.If not symmetrical, sites at the bottom of the slab will be removed until the slab is symmetric, which may break the stoichiometry.

Parameters:

init_slab (Slab) – The initial Slab.

Returns:

The symmetrized Slabs.

Return type:

list[Slabs]

repair_broken_bonds(slab: Slab, bonds: dict[tuple[Species | Element, Species | Element], float]) Slab[source]

Repair broken bonds (specified by the bonds parameter) due to slab cleaving, and repair them by moving undercoordinated atoms to the other surface.

How it works:

For example a P-O4 bond may have P and O(4-x) on one side of the surface, and Ox on the other side, this method would first move P (the reference atom) to the other side, find its missing nearest neighbours (Ox), and move P and Ox back together.

Parameters:
  • slab (Slab) – The Slab to repair.

  • bonds (dict) – A {(species1, species2): max_bond_dist} dict. For example, PO4 groups may be defined as {(“P”, “O”): 3}.

Returns:

The repaired Slab.

Return type:

Slab

center_slab(slab: Structure) Structure[source]

Relocate the slab to the center such that its center (the slab region) is close to z=0.5.

This makes it easier to find surface sites and apply operations like doping.

There are two possible cases:

1. When the slab region is completely positioned between two vacuum layers in the cell but is not centered, we simply shift the slab to the center along z-axis. 2. If the slab completely resides outside the cell either from the bottom or the top, we iterate through all sites that spill over and shift all sites such that it is now on the other side. An edge case being, either the top of the slab is at z = 0 or the bottom is at z = 1.

Parameters:

slab (Structure) – The slab to center.

Returns:

The centered slab.

Return type:

Structure

generate_all_slabs(structure: Structure, max_index: int, min_slab_size: float, min_vacuum_size: float, bonds: dict | None = None, tol: float = 0.1, ftol: float = 0.1, max_broken_bonds: int = 0, lll_reduce: bool = False, center_slab: bool = False, primitive: bool = True, max_normal_search: int | None = None, symmetrize: bool = False, repair: bool = False, include_reconstructions: bool = False, in_unit_planes: bool = False) list[Slab][source]

Find all unique Slabs up to a given Miller index.

Slabs oriented along certain Miller indices may be equivalent to other Miller indices under symmetry operations. To avoid duplication, such equivalent slabs would be filtered out. For instance, CsCl has equivalent slabs in the (0,0,1), (0,1,0), and (1,0,0) directions under symmetry operations.

Parameters:
  • structure (Structure) – Initial input structure. To ensure that the Miller indices correspond to usual crystallographic definitions, you should supply a conventional unit cell.

  • max_index (int) – The maximum Miller index to go up to.

  • min_slab_size (float) – The minimum slab size in Angstrom.

  • min_vacuum_size (float) – The minimum vacuum layer thickness in Angstrom.

  • bonds (dict) – A {(species1, species2): max_bond_dist} dict. For example, PO4 groups may be defined as {(“P”, “O”): 3}.

  • tol (float) – Tolerance for getting primitive cells and matching structures.

  • ftol (float) – Tolerance in Angstrom for fcluster to check if two atoms are on the same plane. Default to 0.1 Angstrom in the direction of the surface normal.

  • max_broken_bonds (int) – Maximum number of allowable broken bonds for the slab. Use this to limit the number of slabs. Defaults to zero, which means no bond can be broken.

  • lll_reduce (bool) – Whether to perform an LLL reduction on the final Slab.

  • center_slab (bool) – Whether to center the slab in the cell with equal vacuum spacing from the top and bottom.

  • primitive (bool) – Whether to reduce generated slabs to primitive cell. Note this does NOT generate a slab from a primitive cell, it means that after slab generation, we attempt to reduce the generated slab to primitive cell.

  • max_normal_search (int) – If set to a positive integer, the code will search for a normal lattice vector that is as perpendicular to the surface as possible, by considering multiple linear combinations of lattice vectors up to this value. This has no bearing on surface energies, but may be useful as a preliminary step to generate slabs for absorption or other sizes. It may not be the smallest possible cell for simulation. Normality is not guaranteed, but the oriented cell will have the c vector as normal as possible to the surface. The max absolute Miller index is usually sufficient.

  • symmetrize (bool) – Whether to ensure the surfaces of the slabs are equivalent.

  • repair (bool) – Whether to repair terminations with broken bonds or just omit them.

  • include_reconstructions (bool) – Whether to include reconstructed slabs available in the reconstructions_archive.json file. Defaults to False.

  • in_unit_planes (bool) – Whether to set min_slab_size and min_vac_size in number of hkl planes or Angstrom (default). Setting in units of planes is useful to ensure some slabs to have a certain number of layers, e.g. for Cs(100), 10 Ang will result in a slab with only 2 layers, whereas Fe(100) will have more layers. The slab thickness will be in min_slab_size/math.ceil(self._proj_height/dhkl) multiples of oriented unit cells.

get_d(slab: Slab) float[source]

Determine the z-spacing between the bottom two layers for a Slab.

get_slab_regions(slab: Slab, blength: float = 3.5) list[tuple[float, float]][source]

Find the z-ranges for the slab region.

Useful for discerning where the slab ends and vacuum begins if the slab is not fully within the cell.

Parameters:
  • slab (Slab) – The Slab to analyse.

  • blength (float) – The bond length between atoms in Angstrom. You generally want this value to be larger than the actual bond length in order to find atoms that are part of the slab.

TODO (@DanielYang59): this should be a method for Slab? TODO (@DanielYang59): maybe project all z coordinates to 1D?

get_symmetrically_distinct_miller_indices(structure: Structure, max_index: int, return_hkil: bool = False) list[source]

Find all symmetrically distinct indices below a certain max-index for a given structure. Analysis is based on the symmetry of the reciprocal lattice of the structure.

Parameters:
  • structure (Structure) – The input structure.

  • max_index (int) – The maximum index. For example, 1 means that (100), (110), and (111) are returned for the cubic structure. All other indices are equivalent to one of these.

  • return_hkil (bool) – Whether to return hkil (True) form of Miller index for hexagonal systems, or hkl (False).

get_symmetrically_equivalent_miller_indices(structure: Structure, miller_index: tuple[int, ...], return_hkil: bool = True, system: CrystalSystem | None = None) list[source]

Get indices for all equivalent sites within a given structure. Analysis is based on the symmetry of its reciprocal lattice.

Parameters:
  • structure (Structure) – Structure to analyze.

  • miller_index (tuple) – Designates the family of Miller indices to find. Can be hkl or hkil for hexagonal systems.

  • return_hkil (bool) – Whether to return hkil (True) form of Miller index for hexagonal systems, or hkl (False).

  • system – The crystal system of the structure.

hkl_transformation(transf: np.ndarray, miller_index: MillerIndex) Tuple3Ints[source]

Transform the Miller index from setting A to B with a transformation matrix.

Parameters:
  • transf (3x3 array) – The matrix that transforms a lattice from A to B.

  • miller_index (MillerIndex) – The Miller index [h, k, l] to transform.

miller_index_from_sites(lattice: Lattice | ArrayLike, coords: ArrayLike, coords_are_cartesian: bool = True, round_dp: int = 4, verbose: bool = True) Tuple3Ints[source]

Get the Miller index of a plane, determined by a given set of coordinates.

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

Parameters:
  • lattice (matrix or Lattice) – A 3x3 lattice matrix or Lattice object.

  • coords (ArrayLike) – A list or numpy array of coordinates. Can be Cartesian or fractional coordinates.

  • coords_are_cartesian (bool, optional) – Whether the coordinates are in Cartesian coordinates, or fractional (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[int]

pymatgen.core.tensors module

This module provides a base class Tensor for tensor-like objects and methods for basic tensor manipulation. It also provides SquareTensor, which provides basic methods for creating and manipulating rank 2 tensors.

class SquareTensor(input_array: NDArray, vscale: NDArray | None = None)[source]

Bases: Tensor

Base class for doing useful general operations on second rank tensors (stress, strain etc.).

Create a SquareTensor object. Note that the constructor uses __new__ rather than __init__ according to the standard method of subclassing numpy ndarrays. Error is thrown when the class is initialized with non-square matrix.

Parameters:
  • input_array (3x3 array-like) – the 3x3 array-like representing the content of the tensor

  • vscale (6x1 array-like) – 6x1 array-like scaling the Voigt-notation vector with the tensor entries

property det: Self[source]

Shorthand for the determinant of the SquareTensor.

get_scaled(scale_factor: float) Self[source]

Scales the tensor by a certain multiplicative scale factor.

Parameters:

scale_factor (float) – scalar multiplier to be applied to the SquareTensor object

property inv: Self[source]

Shorthand for matrix inverse on SquareTensor.

is_rotation(tol: float = 0.001, include_improper: bool = True) bool[source]

Test to see if tensor is a valid rotation matrix, performs a test to check whether the inverse is equal to the transpose and if the determinant is equal to one within the specified tolerance.

Parameters:
  • tol (float) – tolerance to both tests of whether the the determinant is one and the inverse is equal to the transpose

  • include_improper (bool) – whether to include improper rotations in the determination of validity

polar_decomposition(side: str = 'right') tuple[source]

Calculate matrices for polar decomposition.

property principal_invariants: NDArray[source]

A list of principal invariants for the tensor, which are the values of the coefficients of the characteristic polynomial for the matrix.

refine_rotation() Self[source]

Helper method for refining rotation matrix by ensuring that second and third rows are perpendicular to the first. Gets new y vector from an orthogonal projection of x onto y and the new z vector from a cross product of the new x and y.

Parameters:

rotation (tol to test for)

Returns:

new rotation matrix

property trans: Self[source]

Shorthand for transpose on SquareTensor.

class Tensor(input_array: NDArray, vscale: NDArray | None = None, check_rank: int | None = None)[source]

Bases: ndarray, MSONable

Base class for doing useful general operations on Nth order tensors, without restrictions on the type (stress, elastic, strain, piezo, etc.).

Create a Tensor object. Note that the constructor uses __new__ rather than __init__ according to the standard method of subclassing numpy ndarrays.

Parameters:
  • input_array – (array-like with shape 3^N): array-like representing a tensor quantity in standard (i.e. non-Voigt) notation

  • vscale – (N x M array-like): a matrix corresponding to the coefficients of the Voigt-notation tensor

  • check_rank – (int): If not None, checks that input_array’s rank == check_rank. Defaults to None.

as_dict(voigt: bool = False) dict[source]

Serializes the tensor object.

Parameters:

voigt (bool) – flag for whether to store entries in Voigt notation. Defaults to false, as information may be lost in conversion.

Returns:

serialized format tensor object

Return type:

dict

average_over_unit_sphere(quad: dict | None = None) Self[source]

Average the tensor projection over the unit with option for custom quadrature.

Parameters:

quad (dict) – quadrature for integration, should be dictionary with “points” and “weights” keys defaults to quadpy.sphere.Lebedev(19) as read from file

Returns:

Average of tensor projected into vectors on the unit sphere

convert_to_ieee(structure: Structure, initial_fit: bool = True, refine_rotation: bool = True) Self[source]

Given a structure associated with a tensor, attempts a calculation of the tensor in IEEE format according to the 1987 IEEE standards.

Parameters:
  • structure (Structure) – a structure associated with the tensor to be converted to the IEEE standard

  • initial_fit (bool) – flag to indicate whether initial tensor is fit to the symmetry of the structure. Defaults to true. Note that if false, inconsistent results may be obtained due to symmetrically equivalent, but distinct transformations being used in different versions of spglib.

  • refine_rotation (bool) – whether to refine the rotation produced by the ieee transform generator, default True

einsum_sequence(other_arrays: NDArray, einsum_string: str | None = None) NDArray[source]

Calculate the result of an einstein summation expression.

fit_to_structure(structure: Structure, symprec: float = 0.1)[source]

Get a tensor that is invariant with respect to symmetry operations corresponding to a structure.

Parameters:
  • structure (Structure) – structure from which to generate symmetry operations

  • symprec (float) – symmetry tolerance for the Spacegroup Analyzer used to generate the symmetry operations

classmethod from_dict(dct: dict) Self[source]

Instantiate Tensors from dicts (using MSONable API).

Returns:

hydrated tensor object

Return type:

Tensor

classmethod from_values_indices(values: list[float], indices: NDArray, populate: bool = False, structure: Structure | None = None, voigt_rank: int | None = None, vsym: bool = True, verbose: bool = False) Self[source]

Create a tensor from values and indices, with options for populating the remainder of the tensor.

Parameters:
  • values (floats) – numbers to place at indices

  • indices (array-likes) – indices to place values at

  • populate (bool) – whether to populate the tensor

  • structure (Structure) – structure to base population or fit_to_structure on

  • voigt_rank (int) – full tensor rank to indicate the shape of the resulting tensor. This is necessary if one provides a set of indices more minimal than the shape of the tensor they want, e.g. Tensor.from_values_indices((0, 0), 100)

  • vsym (bool) – whether to voigt symmetrize during the optimization procedure

  • verbose (bool) – whether to populate verbosely

classmethod from_voigt(voigt_input: NDArray) Self[source]

Constructor based on the voigt notation vector or matrix.

Parameters:

voigt_input (array-like) – voigt input for a given tensor

get_grouped_indices(voigt: bool = False, **kwargs) list[list][source]

Get index sets for equivalent tensor values.

Parameters:
  • voigt (bool) – whether to get grouped indices of voigt or full notation tensor, defaults to false

  • **kwargs

    keyword args for np.isclose. Can take atol and rtol for absolute and relative tolerance, e.g.

    >>> tensor.group_array_indices(atol=1e-8)
    

    or

    >>> tensor.group_array_indices(rtol=1e-5)
    

Returns:

list of index groups where tensor values are equivalent to within tolerances

static get_ieee_rotation(structure: Structure, refine_rotation: bool = True) SquareTensor[source]

Given a structure associated with a tensor, determines the rotation matrix for IEEE conversion according to the 1987 IEEE standards.

Parameters:
  • structure (Structure) – a structure associated with the tensor to be converted to the IEEE standard

  • refine_rotation (bool) – whether to refine the rotation using SquareTensor.refine_rotation

get_symbol_dict(voigt: bool = True, zero_index: bool = False, **kwargs) dict[str, NDArray][source]

Create a summary dict for tensor with associated symbol.

Parameters:
  • voigt (bool) – whether to get symbol dict for voigt notation tensor, as opposed to full notation, defaults to true

  • zero_index (bool) – whether to set initial index to zero, defaults to false, since tensor notations tend to use one-indexing, rather than zero indexing like python

  • **kwargs

    keyword args for np.isclose. Can take atol and rtol for absolute and relative tolerance, e.g.

    >>> tensor.get_symbol_dict(atol=1e-8)
    

    or

    >>> tensor.get_symbol_dict(rtol=1e-5)
    

Returns:

list of index groups where tensor values are equivalent to within tolerances

static get_voigt_dict(rank: int) dict[tuple[int, ...], tuple[int, ...]][source]

Get a dictionary that maps indices in the tensor to those in a voigt representation based on input rank.

Parameters:

rank (int) – Tensor rank to generate the voigt map

is_fit_to_structure(structure: Structure, tol: float = 0.01) bool[source]

Test whether a tensor is invariant with respect to the symmetry operations of a particular structure by testing whether the residual of the symmetric portion is below a tolerance.

Parameters:
  • structure (Structure) – structure to be fit to

  • tol (float) – tolerance for symmetry testing

is_symmetric(tol: float = 1e-05) bool[source]

Test whether a tensor is symmetric or not based on the residual with its symmetric part, from self.symmetrized.

Parameters:

tol (float) – tolerance to test for symmetry

is_voigt_symmetric(tol: float = 1e-06) bool[source]

Test symmetry of tensor to that necessary for voigt-conversion by grouping indices into pairs and constructing a sequence of possible permutations to be used in a tensor transpose.

populate(structure: Structure, prec: float = 1e-05, maxiter: int = 200, verbose: bool = False, precond: bool = True, vsym: bool = True) Self[source]

Takes a partially populated tensor, and populates the non-zero entries according to the following procedure, iterated until the desired convergence (specified via prec) is achieved.

  1. Find non-zero entries

  2. Symmetrize the tensor with respect to crystal symmetry and (optionally) voigt symmetry

  3. Reset the non-zero entries of the original tensor

Parameters:
  • structure (Structure) – structure to base population on

  • prec (float) – precision for determining a non-zero value. Defaults to 1e-5.

  • maxiter (int) – maximum iterations for populating the tensor

  • verbose (bool) – whether to populate verbosely

  • precond (bool) – whether to precondition by cycling through all symmops and storing new nonzero values, default True

  • vsym (bool) – whether to enforce voigt symmetry, defaults to True

Returns:

Populated tensor

Return type:

Tensor

project(n: NDArray) Self[source]

Project a tensor into a vector. Returns the tensor dotted into a unit vector along the input n.

Parameters:

n (3x1 array-like) – direction to project onto

Returns:

scalar value corresponding to the projection of

the tensor into the vector

Return type:

float

rotate(matrix: NDArray, tol: float = 0.001) Self[source]

Apply a rotation directly, and tests input matrix to ensure a valid rotation.

Parameters:
  • matrix (3x3 array-like) – rotation matrix to be applied to tensor

  • tol (float) – tolerance for testing rotation matrix validity

round(decimals: int = 0) Self[source]

Wrapper around numpy.round to ensure object of same type is returned.

Parameters:

decimals – Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.

Returns:

rounded tensor of same type

Return type:

Tensor

structure_transform(original_structure: Structure, new_structure: Structure, refine_rotation: bool = True) Self[source]

Transforms a tensor from one basis for an original structure into a new basis defined by a new structure.

Parameters:
  • original_structure (Structure) – structure corresponding to the basis of the current tensor

  • new_structure (Structure) – structure corresponding to the desired basis

  • refine_rotation (bool) – whether to refine the rotations generated in get_ieee_rotation

Returns:

Tensor that has been transformed such that its basis corresponds to the new_structure’s basis

symbol = 'T'[source]
property symmetrized: Self[source]

A generally symmetrized tensor, calculated by taking the sum of the tensor and its transpose with respect to all possible permutations of indices.

transform(symm_op: SymmOp) Self[source]

Apply a transformation (via a symmetry operation) to a tensor.

Parameters:

symm_op (SymmOp) – a symmetry operation to apply to the tensor

property voigt: NDArray[source]

The tensor in Voigt notation.

property voigt_symmetrized: Self[source]

A “voigt”-symmetrized tensor, i.e. a Voigt-notation tensor such that it is invariant w.r.t. permutation of indices.

zeroed(tol: float = 0.001) Self[source]

Get the matrix with all entries below a certain threshold (i.e. tol) set to zero.

class TensorCollection(tensor_list: Sequence, base_class=<class 'pymatgen.core.tensors.Tensor'>)[source]

Bases: Sequence, MSONable

A sequence of tensors that can be used for fitting data or for having a tensor expansion.

Parameters:
  • tensor_list – List of tensors.

  • base_class – Class to be used.

as_dict(voigt: bool = False) dict[source]
Parameters:

voigt – Whether to use Voigt form.

Returns:

Dict representation of TensorCollection.

convert_to_ieee(structure: Structure, initial_fit: bool = True, refine_rotation: bool = True) Self[source]

Convert all tensors to IEEE.

Parameters:
  • structure – Structure

  • initial_fit – Whether to perform an initial fit.

  • refine_rotation – Whether to refine the rotation.

Returns:

TensorCollection.

fit_to_structure(structure: Structure, symprec: float = 0.1) Self[source]

Fit all tensors to a Structure.

Parameters:
  • structure – Structure

  • symprec – symmetry precision.

Returns:

TensorCollection.

classmethod from_dict(dct: dict) Self[source]

Create TensorCollection from dict.

Parameters:

dct – dict

Returns:

TensorCollection

classmethod from_voigt(voigt_input_list: list[Tensor], base_class=<class 'pymatgen.core.tensors.Tensor'>) Self[source]

Create TensorCollection from voigt form.

Parameters:
  • voigt_input_list – List of voigt tensors

  • base_class – Class for tensor.

Returns:

TensorCollection.

is_fit_to_structure(structure: Structure, tol: float = 0.01) bool[source]
Parameters:
  • structure – Structure

  • tol – tolerance.

Returns:

Whether all tensors are fitted to Structure.

is_symmetric(tol: float = 1e-05) bool[source]
Parameters:

tol – tolerance.

Returns:

Whether all tensors are symmetric.

is_voigt_symmetric(tol: float = 1e-06) bool[source]
Parameters:

tol – tolerance.

Returns:

Whether all tensors are voigt symmetric.

property ranks: list[source]

Ranks for all tensors.

rotate(matrix, tol: float = 0.001) Self[source]

Rotates TensorCollection.

Parameters:
  • matrix – Rotation matrix.

  • tol – tolerance.

Returns:

TensorCollection.

round(*args, **kwargs) Self[source]

Round all tensors.

Parameters:
  • args – Passthrough to Tensor.round

  • kwargs – Passthrough to Tensor.round

Returns:

TensorCollection.

property symmetrized: Self[source]

TensorCollection where all tensors are symmetrized.

transform(symm_op: SymmOp) Self[source]

Transforms TensorCollection with a symmetry operation.

Parameters:

symm_op – SymmetryOperation.

Returns:

TensorCollection.

property voigt: list[NDArray][source]

TensorCollection where all tensors are in Voigt form.

property voigt_symmetrized: Self[source]

TensorCollection where all tensors are voigt symmetrized.

zeroed(tol: float = 0.001) Self[source]
Parameters:

tol – Tolerance.

Returns:

TensorCollection where small values are set to 0.

class TensorMapping(tensors: Sequence[Tensor] = (), values: Sequence = (), tol: float = 1e-05)[source]

Bases: MutableMapping

Base class for tensor mappings, which function much like a dictionary, but use numpy routines to determine approximate equality to keys for getting and setting items.

This is intended primarily for convenience with things like stress-strain pairs and fitting data manipulation. In general, it is significantly less robust than a typical hashing and should be used with care.

Initialize a TensorMapping.

Parameters:
  • tensors (Sequence[Tensor], optional) – Defaults to (,).

  • values (Sequence, optional) – Values to be associated with tensors. Defaults to (,).

  • tol (float, optional) – an absolute tolerance for getting and setting items in the mapping. Defaults to 1e-5.

Raises:

ValueError – if tensors and values are not the same length

items()[source]

Items in mapping.

values()[source]

Values in mapping.

get_uvec(vec: NDArray) NDArray[source]

Get a unit vector parallel to input vector.

symmetry_reduce(tensors, structure: Structure, tol: float = 1e-08, **kwargs) TensorMapping[source]

Convert a list of tensors corresponding to a structure and returns a dictionary consisting of unique tensor keys with SymmOp values corresponding to transformations that will result in derivative tensors from the original list.

Parameters:
  • tensors (list of tensors) – list of Tensor objects to test for symmetrically-equivalent duplicates

  • structure (Structure) – structure from which to get symmetry

  • tol (float) – tolerance for tensor equivalence

  • kwargs – keyword arguments for the SpacegroupAnalyzer

Returns:

dictionary consisting of unique tensors with symmetry operations corresponding to those which will reconstruct the remaining tensors as values

pymatgen.core.trajectory module

This module provides classes to define a simulation trajectory, which could come from either relaxation or molecular dynamics.

class Trajectory(species: list[str | Element | Species | DummySpecies | Composition], coords: list[list[Vector3D]] | np.ndarray | list[np.ndarray], charge: float | None = None, spin_multiplicity: float | None = None, lattice: Lattice | Matrix3D | list[Lattice] | list[Matrix3D] | np.ndarray | None = None, *, site_properties: SitePropsType | None = None, frame_properties: list[dict] | None = None, constant_lattice: bool | None = True, time_step: float | None = None, coords_are_displacement: bool = False, base_positions: list[list[Vector3D]] | np.ndarray | None = None)[source]

Bases: MSONable

Trajectory of a geometry optimization or molecular dynamics simulation.

Provides basic functions such as slicing trajectory, combining trajectories, and obtaining displacements.

In below, N denotes the number of sites in the structure, and M denotes the number of frames in the trajectory.

Parameters:
  • species

    shape (N,). List of species on each site. Can take in flexible input, including: i. 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.

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

  • coords – shape (M, N, 3). fractional coordinates of the sites.

  • charge – int or float. Charge of the system. This is only used for Molecule-based trajectories.

  • spin_multiplicity – int or float. Spin multiplicity of the system. This is only used for Molecule-based trajectories.

  • lattice – shape (3, 3) or (M, 3, 3). Lattice of the structures in the trajectory; should be used together with constant_lattice. If constant_lattice=True, this should be a single lattice that is common for all structures in the trajectory (e.g. in an NVT run). If constant_lattice=False, this should be a list of lattices, each for one structure in the trajectory (e.g. in an NPT run or a relaxation that allows changing the cell size). This is only used for Structure-based trajectories.

  • site_properties – Properties associated with the sites. This should be a list of M dicts for a single dict. If a list of dicts, each provides the site properties for a frame. Each value in a dict should be a sequence of length N, giving the properties of the N sites. For example, for a trajectory with M=2 and N=4, the site_properties can be: [{“magmom”:[5,5,5,5]}, {“magmom”:[5,5,5,5]}]. If a single dict, the site properties in the dict apply to all frames in the trajectory. For example, for a trajectory with M=2 and N=4, {“magmom”:[2,2,2,2]} means that, through the entire trajectory, the magmom are kept constant at 2 for all four atoms.

  • frame_properties – Properties associated with the structure (e.g. total energy). This should be a sequence of M dicts, with each dict providing the properties for a frame. For example, for a trajectory with M=2, the frame_properties can be [{‘energy’:1.0}, {‘energy’:2.0}].

  • constant_lattice – Whether the lattice changes during the simulation. Should be used together with lattice. See usage there. This is only used for Structure-based trajectories.

  • time_step – Time step of MD simulation in femto-seconds. Should be None for a trajectory representing a geometry optimization.

  • coords_are_displacement – Whether coords are given in displacements (True) or positions (False). Note, if this is True, coords of a frame (say i) should be relative to the previous frame (i.e. i-1), but not relative to the base_position.

  • base_positions – shape (N, 3). The starting positions of all atoms in the trajectory. Used to reconstruct positions when converting from displacements to positions. Only needs to be specified if coords_are_displacement=True. Defaults to the first index of coords when coords_are_displacement=False.

as_dict() dict[source]

Return the trajectory as a MSONable dict.

extend(trajectory: Self) None[source]

Append a trajectory to the current one.

The lattice, coords, and all other properties are combined.

Parameters:

trajectory – Trajectory to append.

classmethod from_file(filename: str | Path, constant_lattice: bool = True, **kwargs) Self[source]

Create trajectory from XDATCAR, vasprun.xml file, or ASE trajectory (.traj) file.

Parameters:
  • filename (str | Path) – Path to the file to read from.

  • constant_lattice (bool) – Whether the lattice changes during the simulation, such as in an NPT MD simulation. Defaults to True.

  • **kwargs – Additional kwargs passed to Trajectory constructor.

Returns:

containing the structures or molecules in the file.

Return type:

Trajectory

classmethod from_molecules(molecules: list[Molecule], **kwargs) Self[source]

Create trajectory from a list of molecules.

Note: Assumes no atoms removed during simulation.

Parameters:
  • molecules – pymatgen Molecule objects.

  • **kwargs – Additional kwargs passed to Trajectory constructor.

Returns:

A trajectory from the structures.

classmethod from_structures(structures: list[Structure], constant_lattice: bool = True, **kwargs) Self[source]

Create trajectory from a list of structures.

Note: Assumes no atoms removed during simulation.

Parameters:
  • structures – pymatgen Structure objects.

  • constant_lattice – Whether the lattice changes during the simulation, such as in an NPT MD simulation.

  • **kwargs – Additional kwargs passed to Trajectory constructor.

Returns:

A trajectory from the structures.

get_molecule(idx: int) Molecule[source]

Get molecule at specified index.

Parameters:

idx – Index of molecule.

Returns:

A pymatgen Molecule object.

get_structure(idx: int) Structure[source]

Get structure at specified index.

Parameters:

idx – Index of structure.

Returns:

A pymatgen Structure object.

to_displacements() None[source]

Convert positions of trajectory into displacements between consecutive frames.

base_positions and coords should both be in fractional coords. Does not work for absolute coords because the atoms are to be wrapped into the simulation box.

This is the opposite operation of to_positions().

to_positions() None[source]

Convert displacements between consecutive frames into positions.

base_positions and coords should both be in fractional coords or absolute coords.

This is the opposite operation of to_displacements().

write_Xdatcar(filename: PathLike = 'XDATCAR', system: str | None = None, significant_figures: int = 6) None[source]

Write to Xdatcar file.

The supported kwargs are the same as those for the Xdatcar_from_structs.get_str method and are passed through directly.

Parameters:
  • filename – File to write. It’s prudent to end the filename with ‘XDATCAR’, as most visualization and analysis software require this for autodetection.

  • system – Description of system (e.g. 2D MoS2).

  • significant_figures – Significant figures in the output file.

pymatgen.core.units module

This module defines commonly used units for energy, length, temperature, time and charge.

Also defines the following classes: - FloatWithUnit, a subclass of float, which supports

conversion to another, and additions and subtractions perform automatic conversion if units are detected.

  • ArrayWithUnit, a subclass of numpy’s ndarray with similar unit features.

class ArrayWithUnit(input_array: NDArray, unit: str | Unit, unit_type: str | None = None)[source]

Bases: ndarray

Subclasses numpy.ndarray to attach a unit type. Typically, you should use the pre-defined unit type subclasses such as EnergyArray, LengthArray, etc. instead of using ArrayWithUnit directly.

Support conversion, addition and subtraction of the same unit type. e.g. 1 m + 20 cm will be automatically converted to 1.2 m (units follow the leftmost quantity).

>>> energy_arr_a = EnergyArray([1, 2], "Ha")
>>> energy_arr_b = EnergyArray([1, 2], "eV")
>>> energy_arr_c = energy_arr_a + energy_arr_b
>>> print(energy_arr_c)
[ 1.03674933  2.07349865] Ha
>>> energy_arr_c.to("eV")
array([ 28.21138386,  56.42276772]) eV

Override __new__.

property as_base_units[source]

This ArrayWithUnit in base SI units, including derived units.

Returns:

ArrayWithUnit in base SI units

conversions() str[source]

Get a string showing the available conversions. Useful tool in interactive mode.

property supported_units: dict[source]

Supported units for specific unit type.

to(new_unit: str | Unit) Self[source]

Convert to a new unit.

Parameters:

new_unit (str | Unit) – New unit type.

Returns:

ArrayWithUnit in the new unit.

Example usage: >>> energy = EnergyArray([1, 1.1], “Ha”) >>> energy.to(“eV”) array([ 27.21138386, 29.93252225]) eV

property unit: Unit[source]

The unit, e.g. “eV”.

property unit_type: str | None[source]

The type of unit. Energy, Charge, etc.

Charge = functools.partial(<class 'pymatgen.core.units.FloatWithUnit'>, unit_type='charge')[source]

A float with a charge unit.

Parameters:
  • val (float) – Value

  • unit (Unit) – e.g. C, e (electron charge). Must be valid unit or UnitError is raised.

Energy = functools.partial(<class 'pymatgen.core.units.FloatWithUnit'>, unit_type='energy')[source]

A float with an energy unit.

Parameters:
  • val (float) – Value

  • unit (Unit) – e.g. eV, kJ, etc. Must be valid unit or UnitError is raised.

class FloatWithUnit(val, unit: str | Unit, unit_type: str | None = None)[source]

Bases: float

Subclasses float to attach a unit type. Typically, you should use the pre-defined unit type subclasses such as Energy, Length, etc. instead of using FloatWithUnit directly.

Support conversion, addition and subtraction of the same unit type. e.g. 1 m + 20 cm will be automatically converted to 1.2 m (units follow the leftmost quantity). Note that FloatWithUnit does not override the eq method for float, i.e., units are not checked when testing for equality. The reason is to allow this class to be used transparently wherever floats are expected.

Example usage:
>>> energy_a = Energy(1.1, "Ha")
>>> energy_b = Energy(3, "eV")
>>> energy_c = energy_a + energy_b
>>> print(energy_c)
1.2102479761938871 Ha
>>> energy_c.to("eV")
32.932522246000005 eV

Initialize a float with unit.

Parameters:
  • val (float) – Value

  • unit (str | Unit) – A unit. e.g. “C”.

  • unit_type (str) – A type of unit. e.g. “charge”

property as_base_units[source]

This FloatWithUnit in base SI units, including derived units.

Returns:

FloatWithUnit in base SI units

classmethod from_str(string: str) Self[source]

Convert string to FloatWithUnit.

Example usage:

Memory.from_str(“1. MB”).

property supported_units: tuple[source]

Supported units for specific unit type.

to(new_unit: str | Unit) Self[source]

Convert to a new unit. Right now, only support 1 to 1 mapping of units of each type.

Parameters:

new_unit (str | Unit) – New unit type.

Returns:

FloatWithUnit in the new unit.

Example usage: >>> energy = Energy(1.1, “eV”) >>> energy = Energy(1.1, “Ha”) >>> energy.to(“eV”) 29.932522246 eV

property unit: Unit[source]

The unit, e.g. “eV”.

property unit_type: str | None[source]

The type of unit. Energy, Charge, etc.

Length = functools.partial(<class 'pymatgen.core.units.FloatWithUnit'>, unit_type='length')[source]

A float with a length unit.

Parameters:
  • val (float) – Value

  • unit (Unit) – e.g. m, ang, bohr, etc. Must be valid unit or UnitError is raised.

Mass = functools.partial(<class 'pymatgen.core.units.FloatWithUnit'>, unit_type='mass')[source]

A float with a mass unit.

Parameters:
  • val (float) – Value

  • unit (Unit) – e.g. amu, kg, etc. Must be valid unit or UnitError is raised.

Memory = functools.partial(<class 'pymatgen.core.units.FloatWithUnit'>, unit_type='memory')[source]

A float with a memory unit.

Parameters:
  • val (float) – Value

  • unit (Unit) – e.g. KB, MB, GB, TB. Must be valid unit or UnitError is raised.

Temp = functools.partial(<class 'pymatgen.core.units.FloatWithUnit'>, unit_type='temperature')[source]

A float with a temperature unit.

Parameters:
  • val (float) – Value

  • unit (Unit) – e.g. K. Only K (kelvin) is supported.

Time = functools.partial(<class 'pymatgen.core.units.FloatWithUnit'>, unit_type='time')[source]

A float with a time unit.

Parameters:
  • val (float) – Value

  • unit (Unit) – e.g. s, min, h. Must be valid unit or UnitError is raised.

class Unit(unit_def: str | dict[str, int])[source]

Bases: Mapping

Represent a unit, e.g. “m” for meters, etc. Supports compound units. Only integer powers are supported.

Parameters:

unit_def – A definition for the unit. Either a mapping of unit to powers, e.g. {“m”: 2, “s”: -1} represents “m^2 s^-1”, or simply as a string “kg m^2 s^-1”. Note that the supported format uses “^” as the power operator and all units must be space-separated.

property as_base_units: tuple[dict, float][source]

Convert all units to base SI units, including derived units.

Returns:

(base_units_dict, scaling factor). base_units_dict will not

contain any constants, which are gathered in the scaling factor.

Return type:

tuple[dict, float]

get_conversion_factor(new_unit: str | Unit) float[source]

Get the conversion factor between this unit and a new unit. Compound units are supported, but must have the same powers in each unit type.

Parameters:

new_unit (str | Unit) – The new unit.

exception UnitError[source]

Bases: BaseException

Exception class for unit errors.

obj_with_unit(obj: Any, unit: str) FloatWithUnit | ArrayWithUnit | dict[str, FloatWithUnit | ArrayWithUnit][source]

Get a FloatWithUnit instance if obj is scalar, a dictionary of objects with units if obj is a dict, else an instance of ArrayWithUnit.

Parameters:
  • obj (Any) – Object to be given a unit.

  • unit (str) – Specific units (eV, Ha, m, ang, etc.).

unitized(unit)[source]

Decorator to assign units to the output of a function. You can also use it to standardize the output units of a function that already returns a FloatWithUnit or ArrayWithUnit. For sequences, all values in the sequences are assigned the same unit. It works with Python sequences only. The creation of numpy arrays loses all unit information. For mapping types, the values are assigned units.

Parameters:

unit – Specific unit (eV, Ha, m, ang, etc.).

Example

@unitized(unit=”kg”) def get_mass():

return 123.45

pymatgen.core.xcfunc module

This module provides class for XC correlation functional.

class XcFunc(xc: LibxcFunc | None = None, x: LibxcFunc | None = None, c: LibxcFunc | None = None)[source]

Bases: MSONable

Store information about the XC correlation functional.

Client code usually creates the object by calling the class methods:

  • from_name

  • from_type_name

or code-specific methods such as:

  • from_abinit_ixc

Ax XcFunc instance is hashable and can therefore be used as key in dictionaries.

The implementation is based on the libxc conventions and is inspired to the XML specification for atomic PAW datasets documented at:

For convenience, part of the pawxml documentation is reported here.

The xc_functional element defines the exchange-correlation functional used for generating the dataset. It has the two attributes type and name.

The type attribute can be LDA, GGA, MGGA or HYB. The name attribute designates the exchange-correlation functional and can be specified in the following ways:

[1] Taking the names from the LibXC library. The correlation and exchange names

are stripped from their XC_ part and combined with a + sign. Here is an example for an LDA functional:

<xc_functional type=”LDA”, name=”LDA_X+LDA_C_PW”/>

and this is what PBE will look like:

<xc_functional type=”GGA”, name=”GGA_X_PBE+GGA_C_PBE”/>

[2] Using one of the following pre-defined aliases:

type name LibXC equivalent Reference LDA PW LDA_X+LDA_C_PW LDA exchange; Perdew, Wang, PRB 45, 13244 (1992) GGA PW91 GGA_X_PW91+GGA_C_PW91 Perdew et al PRB 46, 6671 (1992) GGA PBE GGA_X_PBE+GGA_C_PBE Perdew, Burke, Ernzerhof, PRL 77, 3865 (1996) GGA RPBE GGA_X_RPBE+GGA_C_PBE Hammer, Hansen, Nørskov, PRB 59, 7413 (1999) GGA revPBE GGA_X_PBE_R+GGA_C_PBE Zhang, Yang, PRL 80, 890 (1998) GGA PBEsol GGA_X_PBE_SOL+GGA_C_PBE_SOL Perdew et al, PRL 100, 136406 (2008) GGA AM05 GGA_X_AM05+GGA_C_AM05 Armiento, Mattsson, PRB 72, 085108 (2005) GGA BLYP GGA_X_B88+GGA_C_LYP Becke, PRA 38, 3098 (1988); Lee, Yang, Parr, PRB 37, 785

Parameters:
  • xc – LibxcFunc for XC functional.

  • x – LibxcFunc for exchange part. Mutually exclusive with xc.

  • c – LibxcFunc for correlation part. Mutually exclusive with xc.

abinitixc_to_libxc: ClassVar[dict[int, dict[str, LibxcFunc]]] = {1: {'xc': LibxcFunc(name='LDA_XC_TETER93', kind='EXCHANGE_CORRELATION', family='LDA')}, 2: {'c': LibxcFunc(name='LDA_C_PZ', kind='CORRELATION', family='LDA'), 'x': LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA')}, 4: {'c': LibxcFunc(name='LDA_C_WIGNER', kind='CORRELATION', family='LDA'), 'x': LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA')}, 5: {'c': LibxcFunc(name='LDA_C_HL', kind='CORRELATION', family='LDA'), 'x': LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA')}, 7: {'c': LibxcFunc(name='LDA_C_PW', kind='CORRELATION', family='LDA'), 'x': LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA')}, 11: {'c': LibxcFunc(name='GGA_C_PBE', kind='CORRELATION', family='GGA'), 'x': LibxcFunc(name='GGA_X_PBE', kind='EXCHANGE', family='GGA')}, 14: {'c': LibxcFunc(name='GGA_C_PBE', kind='CORRELATION', family='GGA'), 'x': LibxcFunc(name='GGA_X_PBE_R', kind='EXCHANGE', family='GGA')}, 15: {'c': LibxcFunc(name='GGA_C_PBE', kind='CORRELATION', family='GGA'), 'x': LibxcFunc(name='GGA_X_RPBE', kind='EXCHANGE', family='GGA')}}[source]
classmethod aliases() list[str][source]

List of registered names.

as_dict() dict[source]

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

classmethod asxc(obj) Self[source]

Convert to XcFunc.

defined_aliases: ClassVar[dict[tuple[LibxcFunc, LibxcFunc], type_name]] = {(LibxcFunc(name='GGA_X_AM05', kind='EXCHANGE', family='GGA'), LibxcFunc(name='GGA_C_AM05', kind='CORRELATION', family='GGA')): ('GGA', 'AM05'), (LibxcFunc(name='GGA_X_B88', kind='EXCHANGE', family='GGA'), LibxcFunc(name='GGA_C_LYP', kind='CORRELATION', family='GGA')): ('GGA', 'BLYP'), (LibxcFunc(name='GGA_X_PBE', kind='EXCHANGE', family='GGA'), LibxcFunc(name='GGA_C_PBE', kind='CORRELATION', family='GGA')): ('GGA', 'PBE'), (LibxcFunc(name='GGA_X_PBE_R', kind='EXCHANGE', family='GGA'), LibxcFunc(name='GGA_C_PBE', kind='CORRELATION', family='GGA')): ('GGA', 'revPBE'), (LibxcFunc(name='GGA_X_PBE_SOL', kind='EXCHANGE', family='GGA'), LibxcFunc(name='GGA_C_PBE_SOL', kind='CORRELATION', family='GGA')): ('GGA', 'PBEsol'), (LibxcFunc(name='GGA_X_PW91', kind='EXCHANGE', family='GGA'), LibxcFunc(name='GGA_C_PW91', kind='CORRELATION', family='GGA')): ('GGA', 'PW91'), (LibxcFunc(name='GGA_X_RPBE', kind='EXCHANGE', family='GGA'), LibxcFunc(name='GGA_C_PBE', kind='CORRELATION', family='GGA')): ('GGA', 'RPBE'), (LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA'), LibxcFunc(name='LDA_C_GL', kind='CORRELATION', family='LDA')): ('LDA', 'GL'), (LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA'), LibxcFunc(name='LDA_C_HL', kind='CORRELATION', family='LDA')): ('LDA', 'HL'), (LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA'), LibxcFunc(name='LDA_C_PW', kind='CORRELATION', family='LDA')): ('LDA', 'PW'), (LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA'), LibxcFunc(name='LDA_C_PW_MOD', kind='CORRELATION', family='LDA')): ('LDA', 'PW_MOD'), (LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA'), LibxcFunc(name='LDA_C_PZ', kind='CORRELATION', family='LDA')): ('LDA', 'PZ'), (LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA'), LibxcFunc(name='LDA_C_VWN', kind='CORRELATION', family='LDA')): ('LDA', 'VWN'), (LibxcFunc(name='LDA_X', kind='EXCHANGE', family='LDA'), LibxcFunc(name='LDA_C_WIGNER', kind='CORRELATION', family='LDA')): ('LDA', 'W')}[source]
classmethod from_abinit_ixc(ixc: int) Self | None[source]

Build the object from Abinit ixc (integer).

classmethod from_dict(dct: dict) Self[source]

Deserialize from MSONable dict representation.

classmethod from_name(name: str) Self[source]

Build the object from one of the registered names.

classmethod from_type_name(typ: str | None, name: str) Self[source]

Build the object from (type, name).

name()[source]

The name of the functional. If the functional is not found in the aliases, the string has the form X_NAME+C_NAME.

type()[source]

The type of the functional.

class type_name(type: Literal['LDA', 'GGA'], name: str)[source]

Bases: NamedTuple

Type and name of the XcFunc.

Create new instance of type_name(type, name)

name: str[source]

Alias for field number 1

type: Literal['LDA', 'GGA'][source]

Alias for field number 0

xcf[source]

alias of LibxcFunc