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

  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

    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

    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

    Length of the bond.

get_bond_length(sp1: SpeciesLike, sp2: SpeciesLike, bond_order: float = 1) → float

  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

  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]

  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:

    mapping bond order to bond length in Angstrom.

  Return type:

    dict[float, float]

## pymatgen.core.composition module

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

class ChemicalPotential(*args, **kwargs)

  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

    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)

  Bases: `Hashable`, `Mapping`, `MSONable`, `Stringify`

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

  Key Features:

    - Supports both Element and Species as keys, with differentiation

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

  Highlights:

    - Input Flexibility: Accepts formulas as strings, dictionaries, or

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

  Examples

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

  - `amount_tolerance`

    Tolerance for distinguishing composition

    Type:

      float

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

    Tolerance for verifying charge balance.

    Type:

      float

  - `special_formulas`

    Custom formula mappings for specific compounds

    Type:

      dict

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

    Prior probabilities of oxidation states, used

    Type:

      dict or None

  for oxidation state guessing.
  Functionality:

    - Arithmetic Operations: Add, subtract, multiply, or divide compositions.

    For example:

          >>> comp1 = Composition("Fe2O3")
          >>> comp2 = Composition("FeO")
          >>> result = comp1 + comp2  # Produces "Fe3O4"

    - Representation:

        - formula: Full formula string with elements sorted by electronegativity.

        - reduced_formula: Simplified formula with minimal ratios.

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

    - Utilities:

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

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

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

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

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

    - Oxidation State Handling:

        - oxi_state_guesses: Suggests charge-balanced oxidation states.

        - charge_balanced: Checks if the composition is charge balanced.

        - add_charges_from_oxi_state_guesses: Assigns oxidation states based on guesses.

    - Validation:

        - valid: Ensures all elements/species are valid.

  Notes

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

  handled. For example:

    - Composition(“Fe2+”) differentiates Fe2+ from Fe3+.

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

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

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

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

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

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

     > Composition(Li = 2, O = 1)

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

  Parameters:

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

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

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

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

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

    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

    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

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

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

    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]

    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

    Average electronegativity of the composition.

  property charge: float | None

    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

    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: ClassVar[float] = 1e-08
  property chemical_system: str

    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]

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

  contains_element_type(category: str) → bool

    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

    A copy of the composition.

  property element_composition: Self

    The composition replacing any species by the corresponding element.

  property elements: list[Element | Species | DummySpecies]

    List of elements in Composition.

  property formula: str

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

  property fractional_composition: Self

    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

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

    Parameters:

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

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

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

    Parameters:

      - weight_dict (dict) – {symbol: weight_fraction} dict.

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

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

    Returns:

      Composition in molar fractions.

    Examples

        >>> Composition.from_weights({"Fe": 0.5, "Ni": 0.5})
        Composition('Fe0.512434 Ni0.487566')
        >>> Composition.from_weights({"Ti": 60, "Ni": 40})
        Composition('Ti0.647796 Ni0.352204')

  classmethod from_weights(*args, strict: bool = True, **kwargs) → Self

    Create a Composition from a weight-based formula.

    Parameters:

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

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

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

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

    Returns:

      Composition in molar fractions.

    Examples

        >>> Composition.from_weights("Fe50Ti50")
        Composition('Fe0.461538 Ti0.538462')
        >>> Composition.from_weights({"Fe": 0.5, "Ni": 0.5})
        Composition('Fe0.512434 Ni0.487566')

  get_atomic_fraction(el: SpeciesLike) → float

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

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

    Calculate a reduced composition and factor.

    Returns:

      Normalized Composition and multiplicative factor, i.e. “Li4Fe4P4O16” returns (Composition(“LiFePO4”), 4).

    Return type:

      tuple[Composition, float]

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

    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 for Lanthanides, Actinides and hydrogen. Note that polyanions will still be determined based on the true electronegativity of the elements.

    Returns:

      Normalized formula and multiplicative factor,

        i.e., “Li4Fe4P4O16” returns (LiFePO4, 4).

    Return type:

      tuple[str, float]

  get_wt_fraction(el: SpeciesLike) → float

    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

    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

    True if composition is an element.

  items() → ItemsView[Species | Element | DummySpecies, int | float]

    Returns Dict.items() for the Composition dict.

  property iupac_formula: str

    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

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

  oxi_prob: ClassVar[dict | None] = None
  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]]

    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]

    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

    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

    A normalized formula, i.e., “LiFePO4” instead of “Li4Fe4P4O16”.

  remove_charges() → Self

    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

    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'}
  property to_data_dict: dict[Literal['reduced_cell_composition', 'unit_cell_composition', 'reduced_cell_formula', 'elements', 'nelements'], Any]

    Returns: dict with the following keys:

    > - reduced_cell_composition

    > - unit_cell_composition

    > - reduced_cell_formula

    > - elements

    > - nelements.

  to_pretty_string() → str
    Returns:

      Same output as __str__() but without spaces.

    Return type:

      str

  property to_reduced_dict: dict[str, float]

    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]

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

  property total_electrons: float

    Total number of electrons in composition.

  property valid: bool

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

  property weight: float

    Total molecular weight of Composition.

exception CompositionError

  Bases: `Exception`

  Composition exceptions.

reduce_formula(sym_amt: Mapping[str, float], iupac_ordering: bool = False) → tuple[str, int]

  Helper function to reduce a symbol-amount mapping.

  Parameters:

    - sym_amt (dict[str, float]) – Symbol to amount mapping.

    - 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 for 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, int]

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

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

      Dictionary representation of GrainBoundary object.

  property bottom_grain: Structure

    The bottom grain (Structure) of the GB.

  property coincidents: list[Site]

    A list of coincident sites.

  copy() → Self

    Make a copy of the GrainBoundary.

  classmethod from_dict(dct: dict) → Self

    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

    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

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

  property sigma_from_site_prop: int

    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

    The top grain (Structure) of the GB.

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

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

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

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

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

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

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

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

    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]

    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)

    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 (NDArray) – 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

    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

    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

    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)

  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

    MSONable dict.

  copy() → Self

    Make a copy of the Interface.

  property film: Structure

    A Structure for just the film.

  property film_indices: list[int]

    Site indices of the film sites.

  property film_layers: int

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

  property film_sites: list[Site]

    The film sites of the interface.

  property film_termination: str

    Label for the film termination chemistry.

  classmethod from_dict(dct: dict) → Self
    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

    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

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

    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

    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

    The shift between the film and substrate in fractional coordinates.

  property substrate: Structure

    A Structure for just the substrate.

  property substrate_indices: list[int]

    Site indices for the substrate atoms.

  property substrate_layers: int

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

  property substrate_sites: list[Site]

    The site objects in the substrate.

  property substrate_termination: str

    Label for the substrate termination chemistry.

  property vacuum_over_film: float

    The vacuum space over the film in Cartesian units.

count_layers(struct: Structure, el: Element | None = None) → int

  Count the number of layers along the c-axis.

fix_pbc(structure: Structure, matrix: NDArray = None) → Structure

  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

  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

  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)

  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

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

  property anonymized_formula: str

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

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

      dict with composition, as well as charge.

  property charge: float

    Charge of the ion.

  property composition: Composition

    Composition of ion.

  property formula: str

    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

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

    Parameters:

      dct – {symbol: amount} dict.

  classmethod from_formula(formula: str) → Self

    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]

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

    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

    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

    Pretty string with proper superscripts.

  property to_reduced_dict: dict

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

  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

    a lattice parameter.

  property abc: Vector3D

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

  property alpha: float

    Angle alpha of lattice in degrees.

  property angles: Vector3D

    Lattice angles.

    Returns:

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

  as_dict(verbosity: int = 0) → dict

    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

    b lattice parameter.

  property beta: float

    Angle beta of lattice in degrees.

  property c: float

    c lattice parameter.

  copy() → Self

    Make a copy of this lattice.

  classmethod cubic(a: float, pbc: PbcLike = (True, True, True)) → Self

    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

    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

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

    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

    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

    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

    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

    Angle gamma of lattice in degrees.

  get_all_distances(frac_coords1: ArrayLike, frac_coords2: ArrayLike) → np.ndarray

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

    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

    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]

    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

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

  get_fractional_coords(cart_coords: ArrayLike) → np.ndarray

    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

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

  get_lll_reduced_lattice(delta: float = 0.75) → Self

    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

    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

    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

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

    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]

    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]

    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

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

    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

    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

    Inverse of lattice matrix.

  property is_3d_periodic: bool

    True if the Lattice is periodic in all directions.

  is_hexagonal(hex_angle_tol: float = 5, hex_length_tol: float = 0.01) → bool
    Parameters:

      - hex_angle_tol – Angle tolerance

      - hex_length_tol – Length tolerance.

    Returns:

      Whether lattice corresponds to hexagonal lattice.

  property is_orthogonal: bool

    Whether all angles are 90 degrees.

  property lengths: Vector3D

    Lattice lengths.

    Returns:

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

  property lll_inverse: ndarray

    Inverse of self.lll_mapping.

  property lll_mapping: ndarray

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

  property lll_matrix: ndarray

    The matrix for LLL reduction.

  property matrix: ndarray

    Copy of matrix representing the Lattice.

  property metric_tensor: ndarray

    The metric tensor of the lattice.

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

    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

    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

    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]

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

  property params_dict: dict[str, float]

    Dictionary of lattice parameters.

  property pbc: PbcLike

    Tuple defining the periodicity of the Lattice.

  property reciprocal_lattice: Self

    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

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

  classmethod rhombohedral(a: float, alpha: float, pbc: PbcLike = (True, True, True)) → Self

    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

    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

    Get the minimum Selling distance between two lattices.

  property selling_vector: ndarray

    The (1,6) array of Selling Scalars.

  classmethod tetragonal(a: float, c: float, pbc: PbcLike = (True, True, True)) → Self

    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

    Volume of the unit cell in Angstrom^3.

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

  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

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

  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(*values)

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

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

    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

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

  classmethod from_dict(dct: dict) → Self

    Deserialize from MSONable dict representation.

  property info_dict

    Dictionary with metadata. see libxc_docs.json.

  property is_c_kind: bool

    True if this is a correlation-only functional.

  property is_gga_family: bool

    True if this functional belongs to the GGA family.

  property is_hyb_gga_family: bool

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

  property is_hyb_mgga_family: bool

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

  property is_k_kind: bool

    True if this is a kinetic functional.

  property is_lda_family: bool

    True if this functional belongs to the LDA family.

  property is_mgga_family: bool

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

  property is_x_kind: bool

    True if this is an exchange-only functional.

  property is_xc_kind: bool

    True if this is a exchange+correlation functional.

  to_json() → str

    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)

  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

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

  elements

    the dictionary keys for the composition

  elec_neg

    the maximum pairwise electronegativity difference

  aos

    the constituent atomic orbitals for each element as a dictionary

  band_edges

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

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

      The maximum pairwise electronegativity difference.

  obtain_band_edges() → dict[str, Any]

    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)

  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]

    MSONable dict.

  as_xyzt_str() → str

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

    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

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

    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)

  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

    A 4x4 array representing the symmetry operation.

    Type:

      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) → NDArray

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

    Parameters:

      vector (3x1 array) – A vector.

  are_symmetrically_related(point_a: ArrayLike, point_b: ArrayLike, tol: float = 0.001) → bool

    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

  are_symmetrically_related_vectors(from_a: ArrayLike, to_a: ArrayLike, r_a: ArrayLike, from_b: ArrayLike, to_b: ArrayLike, r_b: ArrayLike, tol: float = 0.001) → tuple[bool, 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]

    MSONable dict.

  as_xyz_str() → str

    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

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

    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

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

      xyz_str (str) – “x, y, z”, “-x, -y, z”, “-2y+1/2, 3x+1/2, z-y+1/2”, etc.

    Returns:

      SymmOp

  property inverse: Self

    Inverse of transformation.

  static inversion(origin: ArrayLike = (0, 0, 0)) → SymmOp

    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) → NDArray

    Apply the operation on a point.

    Parameters:

      point – Cartesian coordinate.

    Returns:

      Coordinates of point after operation.

  operate_multi(points: ArrayLike) → NDArray

    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

    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

    A 3x3 numpy.array representing the rotation matrix.

  static rotoreflection(axis: ArrayLike, angle: float, origin: ArrayLike = (0, 0, 0)) → SymmOp

    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

    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

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

## pymatgen.core.periodic_table module

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

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

  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)

  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

    Oxidation state associated with Species.

    Type:

      int

  Z

    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

    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

    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

    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

    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

    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]

    MSONable dict representation.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      DummySpecies

  classmethod from_str(species_string: str) → Self

    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

    Oxidation state associated with DummySpecies.

  property symbol: str

    Symbol for DummySpecies.

class Element(*values)

  Bases: `ElementBase`

  Enum representing an element in the periodic table.

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

  Z

    Atomic number of the element.

    Type:

      int

  symbol

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

    Type:

      str

  long_name

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

    Type:

      str

  A

    Atomic mass number (sum of protons and neutrons).

    Type:

      int, optional

  atomic_radius_calculated

    Calculated atomic radius (Å).

    Type:

      float, optional

  van_der_waals_radius

    Van der Waals radius (Å).

    Type:

      float, optional

  mendeleev_no

    Mendeleev number based on crystal-structure maps.

    Type:

      int, optional

  electrical_resistivity

    Electrical resistivity (Ω·m).

    Type:

      float, optional

  velocity_of_sound

    Velocity of sound (m/s).

    Type:

      float, optional

  reflectivity

    Reflectivity (%).

    Type:

      float, optional

  refractive_index

    Refractive index.

    Type:

      float, optional

  poissons_ratio

    Poisson’s ratio.

    Type:

      float, optional

  molar_volume

    Molar volume (cm³/mol).

    Type:

      float, optional

  electronic_structure

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

    Type:

      str

  atomic_orbitals

    Orbital energies (Hartree units).

    Type:

      dict

  atomic_orbitals_eV

    Orbital energies in electron volts (eV).

    Type:

      dict

  thermal_conductivity

    Thermal conductivity (W/m·K).

    Type:

      float, optional

  boiling_point

    Boiling point (K).

    Type:

      float, optional

  melting_point

    Melting point (K).

    Type:

      float, optional

  critical_temperature

    Critical temperature (K).

    Type:

      float, optional

  superconduction_temperature

    Superconducting transition temperature (K).

    Type:

      float, optional

  liquid_range

    Temperature range for liquid phase (K).

    Type:

      float, optional

  bulk_modulus

    Bulk modulus (GPa).

    Type:

      float, optional

  youngs_modulus

    Young’s modulus (GPa).

    Type:

      float, optional

  brinell_hardness

    Brinell hardness (MPa).

    Type:

      float, optional

  rigidity_modulus

    Rigidity modulus (GPa).

    Type:

      float, optional

  mineral_hardness

    Mohs hardness.

    Type:

      float, optional

  vickers_hardness

    Vickers hardness (MPa).

    Type:

      float, optional

  density_of_solid

    Density in solid phase (g/cm³).

    Type:

      float, optional

  coefficient_of_linear_thermal_expansion

    Thermal expansion coefficient (K⁻¹).

    Type:

      float, optional

  ground_level

    Ground energy level of the element.

    Type:

      float, optional

  ionization_energies

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

    Type:

      list[Optional[float]]

  Examples

  Create an element instance and access its properties:

        >>> hydrogen = Element("H")
        >>> hydrogen.symbol
        'H'
        >>> hydrogen.Z
        1
        >>> hydrogen.electronic_structure
        '1s1'

  Access additional attributes such as atomic radius:

        >>> hydrogen.atomic_radius_calculated
        0.53

  Notes

  - This class supports handling of isotopes by incorporating named isotopes

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

  References

  - Atomic radius data: https://wikipedia.org/wiki/Atomic_radii_of_the_elements_(data_page)

  - Van der Waals radius: CRC Handbook of Chemistry and Physics, 91st Ed.

  - Mendeleev number: D. G. Pettifor, “A chemical scale for crystal-structure maps,”

  Solid State Communications, 1984.

  Ac = 'Ac'
  Ag = 'Ag'
  Al = 'Al'
  Am = 'Am'
  Ar = 'Ar'
  As = 'As'
  At = 'At'
  Au = 'Au'
  B = 'B'
  Ba = 'Ba'
  Be = 'Be'
  Bh = 'Bh'
  Bi = 'Bi'
  Bk = 'Bk'
  Br = 'Br'
  C = 'C'
  Ca = 'Ca'
  Cd = 'Cd'
  Ce = 'Ce'
  Cf = 'Cf'
  Cl = 'Cl'
  Cm = 'Cm'
  Cn = 'Cn'
  Co = 'Co'
  Cr = 'Cr'
  Cs = 'Cs'
  Cu = 'Cu'
  D = 'D'
  Db = 'Db'
  Ds = 'Ds'
  Dy = 'Dy'
  Er = 'Er'
  Es = 'Es'
  Eu = 'Eu'
  F = 'F'
  Fe = 'Fe'
  Fl = 'Fl'
  Fm = 'Fm'
  Fr = 'Fr'
  Ga = 'Ga'
  Gd = 'Gd'
  Ge = 'Ge'
  H = 'H'
  He = 'He'
  Hf = 'Hf'
  Hg = 'Hg'
  Ho = 'Ho'
  Hs = 'Hs'
  I = 'I'
  In = 'In'
  Ir = 'Ir'
  K = 'K'
  Kr = 'Kr'
  La = 'La'
  Li = 'Li'
  Lr = 'Lr'
  Lu = 'Lu'
  Lv = 'Lv'
  Mc = 'Mc'
  Md = 'Md'
  Mg = 'Mg'
  Mn = 'Mn'
  Mo = 'Mo'
  Mt = 'Mt'
  N = 'N'
  Na = 'Na'
  Nb = 'Nb'
  Nd = 'Nd'
  Ne = 'Ne'
  Nh = 'Nh'
  Ni = 'Ni'
  No = 'No'
  Np = 'Np'
  O = 'O'
  Og = 'Og'
  Os = 'Os'
  P = 'P'
  Pa = 'Pa'
  Pb = 'Pb'
  Pd = 'Pd'
  Pm = 'Pm'
  Po = 'Po'
  Pr = 'Pr'
  Pt = 'Pt'
  Pu = 'Pu'
  Ra = 'Ra'
  Rb = 'Rb'
  Re = 'Re'
  Rf = 'Rf'
  Rg = 'Rg'
  Rh = 'Rh'
  Rn = 'Rn'
  Ru = 'Ru'
  S = 'S'
  Sb = 'Sb'
  Sc = 'Sc'
  Se = 'Se'
  Sg = 'Sg'
  Si = 'Si'
  Sm = 'Sm'
  Sn = 'Sn'
  Sr = 'Sr'
  T = 'T'
  Ta = 'Ta'
  Tb = 'Tb'
  Tc = 'Tc'
  Te = 'Te'
  Th = 'Th'
  Ti = 'Ti'
  Tl = 'Tl'
  Tm = 'Tm'
  Ts = 'Ts'
  U = 'U'
  V = 'V'
  W = 'W'
  Xe = 'Xe'
  Y = 'Y'
  Yb = 'Yb'
  Zn = 'Zn'
  Zr = 'Zr'

class ElementBase(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)

  Bases: `Enum`

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

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

  Z

    Atomic number of the element.

    Type:

      int

  symbol

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

    Type:

      str

  long_name

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

    Type:

      str

  A

    Atomic mass number (sum of protons and neutrons).

    Type:

      int, optional

  atomic_radius_calculated

    Calculated atomic radius (Å).

    Type:

      float, optional

  van_der_waals_radius

    Van der Waals radius (Å).

    Type:

      float, optional

  mendeleev_no

    Mendeleev number based on crystal-structure maps.

    Type:

      int, optional

  electrical_resistivity

    Electrical resistivity (Ω·m).

    Type:

      float, optional

  velocity_of_sound

    Velocity of sound (m/s).

    Type:

      float, optional

  reflectivity

    Reflectivity (%).

    Type:

      float, optional

  refractive_index

    Refractive index.

    Type:

      float, optional

  poissons_ratio

    Poisson’s ratio.

    Type:

      float, optional

  molar_volume

    Molar volume (cm³/mol).

    Type:

      float, optional

  electronic_structure

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

    Type:

      str

  atomic_orbitals

    Orbital energies (Hartree units).

    Type:

      dict

  atomic_orbitals_eV

    Orbital energies in electron volts (eV).

    Type:

      dict

  thermal_conductivity

    Thermal conductivity (W/m·K).

    Type:

      float, optional

  boiling_point

    Boiling point (K).

    Type:

      float, optional

  melting_point

    Melting point (K).

    Type:

      float, optional

  critical_temperature

    Critical temperature (K).

    Type:

      float, optional

  superconduction_temperature

    Superconducting transition temperature (K).

    Type:

      float, optional

  liquid_range

    Temperature range for liquid phase (K).

    Type:

      float, optional

  bulk_modulus

    Bulk modulus (GPa).

    Type:

      float, optional

  youngs_modulus

    Young’s modulus (GPa).

    Type:

      float, optional

  brinell_hardness

    Brinell hardness (MPa).

    Type:

      float, optional

  rigidity_modulus

    Rigidity modulus (GPa).

    Type:

      float, optional

  mineral_hardness

    Mohs hardness.

    Type:

      float, optional

  vickers_hardness

    Vickers hardness (MPa).

    Type:

      float, optional

  density_of_solid

    Density in solid phase (g/cm³).

    Type:

      float, optional

  coefficient_of_linear_thermal_expansion

    Thermal expansion coefficient (K⁻¹).

    Type:

      float, optional

  ground_level

    Ground energy level of the element.

    Type:

      float, optional

  ionization_energies

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

    Type:

      list[Optional[float]]

  Examples

  Create an element instance and access its properties:

        >>> hydrogen = Element("H")
        >>> hydrogen.symbol
        'H'
        >>> hydrogen.Z
        1
        >>> hydrogen.electronic_structure
        '1s1'

  Access additional attributes such as atomic radius:

        >>> hydrogen.atomic_radius_calculated
        0.53

  Notes

  - This class supports handling of isotopes by incorporating named isotopes

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

  References

  - Atomic radius data: https://wikipedia.org/wiki/Atomic_radii_of_the_elements_(data_page)

  - Van der Waals radius: CRC Handbook of Chemistry and Physics, 91st Ed.

  - Mendeleev number: D. G. Pettifor, “A chemical scale for crystal-structure maps,”

  Solid State Communications, 1984.

  property X: float

    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]

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

  property atomic_mass: FloatWithUnit

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

  property atomic_mass_number: FloatWithUnit | None

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

  property atomic_orbitals_eV: dict[str, float]

    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

    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

    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

    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

    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

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

  property common_oxidation_states: tuple[int, ...]

    Tuple of common oxidation states.

  property data: dict[str, Any]

    Dict of data for element.

  property electron_affinity: float

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

  property electronic_structure: str

    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

    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

    Deserialize from MSONable dict representation.

  static from_name(name: str) → Element

    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

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

    Full electronic structure 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 full electronic structure for Fe is:

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

    Returns:

      A list of tuples representing each subshell, where each tuple contains:

      > - n (int): Principal quantum number.

      > - orbital_type (str): Orbital type (e.g., “s”, “p”, “d”, “f”).

      > - electron_count (int): Number of electrons in the subshell.

    Return type:

      list[tuple[int, str, int]]

  property ground_state_term_symbol: str

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

  property group: int

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

  property icsd_oxidation_states: tuple[int, ...]

    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]

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

  property ionization_energy: float | None

    First ionization energy of element.

  property is_actinoid: bool

    True if element is a actinoid.

  property is_alkali: bool

    True if element is an alkali metal.

  property is_alkaline: bool

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

  property is_chalcogen: bool

    True if element is a chalcogen.

  property is_halogen: bool

    True if element is a halogen.

  property is_lanthanoid: bool

    True if element is a lanthanoid.

  property is_metal: bool

    True if is a metal.

  property is_metalloid: bool

    True if element is a metalloid.

  property is_noble_gas: bool

    True if element is noble gas.

  property is_post_transition_metal: bool

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

  property is_quadrupolar: bool

    Check if this element can be quadrupolar.

  property is_radioactive: bool

    True if element is radioactive.

  property is_rare_earth: bool

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

  property is_transition_metal: bool

    True if element is a transition metal.

  static is_valid_symbol(symbol: str) → bool

    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

    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

    Maximum oxidation state for element.

  property min_oxidation_state: float

    Minimum oxidation state for element.

  property n_electrons: int

    Total number of electrons in the Element.

  property nmr_quadrupole_moment: dict[str, FloatWithUnit]

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

  property number: int

    Alternative attribute for atomic number Z.

  property oxidation_states: tuple[int, ...]

    Tuple of all known oxidation states.

  static print_periodic_table(filter_function: Callable | None = None) → None

    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

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

    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]

    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(*values)

  Bases: `Enum`

  Enum for element types.

  actinoid = 'actinoid'
  alkali = 'alkali'
  alkaline = 'alkaline'
  chalcogen = 'chalcogen'
  d_block = 'd-block'
  f_block = 'f-block'
  halogen = 'halogen'
  lanthanoid = 'lanthanoid'
  metal = 'metal'
  metalloid = 'metalloid'
  noble_gas = 'noble_gas'
  p_block = 'p-block'
  post_transition_metal = 'post_transition_metal'
  quadrupolar = 'quadrupolar'
  radioactive = 'radioactive'
  rare_earth_metal = 'rare_earth_metal'
  s_block = 's-block'
  transition_metal = 'transition_metal'

class Specie(symbol: SpeciesLike, oxidation_state: float | None = None, spin: float | None = None)

  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)

  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'
  as_dict() → dict

    JSON-able dictionary representation.

  property electronic_structure: str

    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

    Underlying element object.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      Species.

  classmethod from_str(species_string: str) → Self

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

    Full electronic structure 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 full electronic structure for Fe is:

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

    Returns:

      A list of tuples representing each subshell, where each tuple contains:

      > - n (int): Principal quantum number.

      > - orbital_type (str): Orbital type (e.g., “s”, “p”, “d”, “f”).

      > - electron_count (int): Number of electrons in the subshell.

    Return type:

      list[tuple[int, str, int]]

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

    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

    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

    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

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

  property n_electrons: int

    Total number of electrons in the Species.

  property oxi_state: float | None

    Oxidation state of Species.

  property spin: float | None

    Spin of Species.

  to_pretty_string() → str

    String without properties.

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

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

  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 (ArrayLike) – Coordinates of site, fractional coordinates by default. See `coords_are_cartesian` for more details.

    - lattice (Lattice) – Lattice associated with the site.

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

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

    - properties (dict) – Properties associated with the site, e.g. {“magmom”: 5}. Defaults to None.

    - label (str) – Label for the site. Defaults to None.

    - skip_checks (bool) – 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

    Fractional a coordinate.

  as_dict(verbosity: int = 0) → dict

    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

    Fractional b coordinate.

  property c: float

    Fractional c coordinate.

  property coords: ndarray

    Cartesian coordinates.

  distance(other: Self, jimage: ArrayLike | None = None) → float

    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]

    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]

    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

    Fractional coordinates.

  classmethod from_dict(dct: dict, lattice: Lattice | None = None) → Self

    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

    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

    Lattice associated with PeriodicSite.

  to_unit_cell(in_place: bool = False) → Self | None

    Move frac coords to within the unit cell.

  property x: float

    Cartesian x coordinate.

  property y: float

    Cartesian y coordinate.

  property z: float

    Cartesian z coordinate.

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

  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 (ArrayLike) – Cartesian coordinates of site.

    - properties (dict) – Properties associated with the site, e.g. {“magmom”: 5}. Defaults to None.

    - label (str) – Label for the site. Defaults to None.

    - skip_checks (bool) – 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

    JSON-serializable dict representation for Site.

  distance(other: Site) → float

    Get distance between two sites.

    Parameters:

      other – Other site.

    Returns:

      distance

    Return type:

      float

  distance_from_point(pt: Vector3D) → float

    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

    Create Site from dict representation.

  property is_ordered: bool

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

  property label: str

    Site label.

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

    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

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

  property species_string: str

    String representation of species on the site.

  property x: float

    Cartesian x coordinate.

  property y: float

    Cartesian y coordinate.

  property z: float

    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)

  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'
  YLABEL = 'y'
  copy() → Self
    Returns:

      Copy of Spectrum object.

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

    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

    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

    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

  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)

  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

    JSON-serializable dict representation of Molecule.

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

    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

    Center of mass of molecule.

  property charge: float

    Charge of molecule.

  copy() → Self

    Convenience method to get a copy of the molecule.

    Returns:

      IMolecule

  classmethod from_dict(dct: dict) → Self

    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

    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

    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

    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

    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

    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]

    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

    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]

    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]

    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]

    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

    Get a z-matrix representation of the molecule.

  property nelectrons: float

    Number of electrons in the molecule.

  property spin_multiplicity: float

    Spin multiplicity of molecule.

  to(filename: str = '', fmt: str = '') → str | None

    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)

  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

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

  as_dataframe() → pd.DataFrame

    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]

    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

    Overall charge of the structure.

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

    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

    The density in units of g/cm^3.

  property distance_matrix: ndarray

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

  property frac_coords

    Fractional coordinates as a Nx3 numpy array.

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

    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

    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

    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

    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.

        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.

      - 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

    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

    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

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

    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)

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

    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

    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

    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]

    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]

    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]

    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)

    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]

    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

    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

    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]

    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

    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]

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

    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

  get_symmetry_dataset(backend: Literal['moyopy'], **kwargs) → moyopy.MoyoDataset
  get_symmetry_dataset(backend: Literal['spglib'], **kwargs) → spglib.SpglibDataset

    Get a symmetry dataset from the structure using either moyopy or spglib backend.

    If using the spglib backend (default), please cite:

    Togo, A., Shinohara, K., & Tanaka, I. (2024). Spglib: a software library for crystal symmetry search. Science and Technology of Advanced Materials: Methods, 4(1), 2384822-2384836. https://doi.org/10.1080/27660400.2024.2384822

    Parameters:

      - backend ("moyopy" | "spglib") – Which symmetry analysis backend to use. Defaults to “spglib”.

      - return_raw_dataset (bool) – Whether to return the raw Dataset object from the backend. The default is False, which returns a dict with a common subset of the data present in both datasets. If you use the raw Dataset object, we do not guarantee that the format of the output is not going to change.

      - symprec (float) – Tolerance for symmetry determination. Defaults to 0.01 A.

      - **kwargs – Additional arguments passed to the respective backend’s constructor. For spglib, these are passed to SpacegroupAnalyzer (e.g. symprec, angle_tolerance). For moyopy, these are passed to MoyoDataset constructor.

    Returns:

      Symmetry dataset from the chosen backend.

    Return type:

      MoyoDataset | SpglibDataset

    Raises:

      - ImportError – If the requested backend is not installed.

      - ValueError – If an invalid backend is specified.

  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]

    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

    Whether the Lattice is periodic in all directions.

  property lattice: Lattice

    Lattice of the structure.

  matches(other: Self | Structure, anonymous: bool = False, **kwargs) → bool

    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

    The periodicity of the structure.

  property properties: dict

    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

    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

    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

    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

    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

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

  property volume: float

    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)

  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

    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

    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

    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

    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

    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]

    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

    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

    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

    Rotate specific sites by some angle around vector at anchor.

    Parameters:

      - indices (list) – Site indices on which to perform the rotation.

      - 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

    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

    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

    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)

  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

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

  classmethod from_dict(dct: dict) → Site

    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)

  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

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

  property coords: NDArray

    Cartesian coords.

  classmethod from_dict(dct: dict) → Self

    Get a PeriodicNeighbor from a dict.

    Parameters:

      dct – MSONable dict format.

    Returns:

      PeriodicNeighbor

class SiteCollection

  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.

  Init a SiteCollection.

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

    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

    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

    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

    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

    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

    Add spin states to structure by site.

    Parameters:

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

  property alphabetical_formula: str

    The formula as a string.

  property atomic_numbers: tuple[int, ...]

    Tuple of atomic numbers.

  property cart_coords: ndarray

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

  property charge: float

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

  property chemical_system: str

    The chemical system of the structure.

  property chemical_system_set: set[str]

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

  property composition: Composition

    The structure’s corresponding Composition object.

  abstractmethod copy() → Self

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

  property distance_matrix: ndarray

    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]

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

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

    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

    The formula as a string.

  from_ase_atoms(**kwargs) → Structure

    Convert ase.Atoms to pymatgen Structure.

    Parameters:

      kwargs – Passed to AseAtomsAdaptor.get_structure.

    Returns:

      Structure

  abstractmethod classmethod from_file(filename: str) → None

    Read in SiteCollection from a filename.

  abstractmethod classmethod from_str(input_string: str, fmt: Any) → None

    Read in SiteCollection from a string.

  get_angle(i: int, j: int, k: int) → float

    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

    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.

  abstractmethod get_distance(i: int, j: int) → float

    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]

    Iterate over species grouped by type.

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

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

  property is_ordered: bool

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

  is_valid(tol: float = 0.5) → bool

    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]

    Site labels as a list.

  property n_elems: int

    Number of types of atoms.

  property ntypesp: int

    Number of types of atoms.

  property num_sites: int

    Number of sites.

  property reduced_formula: str

    The reduced formula as a string.

  relabel_sites(ignore_uniq: bool = False) → Self

    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

    Removes oxidation states from a structure.

  remove_site_property(property_name: str) → Self

    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

    Remove spin states from structure.

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

    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]

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

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

    The sites in the Structure.

  property species: list[Element | Species]

    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]

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

  property symbol_set: tuple[str, ...]

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

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

    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

    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

    A more intuitive alias for .to().

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

    Specie -> Species rename, to maintain backwards compatibility.

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

    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)

  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

    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

    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

    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

    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

    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

    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

    Lattice associated with structure.

  make_supercell(scaling_matrix: ArrayLike, to_unit_cell: bool = True, in_place: bool = True) → Self

    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
    Merges sites (by adding occupancies) within tolerance and removes

      site properties in “sum/delete” modes.

    Parameters:

      - tol (float) – Tolerance for distance to merge sites.

      - mode ("sum" | "delete" | "average") – Only first letter is considered at this moment. - “delete”: delete duplicate sites. - “sum”: sum the occupancies for the sites. - “average”: delete the site but average the properties if it’s numerical.

    Returns:

      Structure with merged sites.

    Return type:

      Structure

  perturb(distance: float, min_distance: float | None = None, seed: int = 0) → Self

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

      - seed (int) – Seed for the random number generator. Defaults to 0.

    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]

    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

    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

    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

    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

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

    Parameters:

      - indices (list) – Site indices on which to perform the rotation.

      - 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

    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

    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

    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

    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

    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

  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:

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

  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

    Parameters for the SlabGenerator.

    Type:

      dict

  trans_matrix

    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

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

    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)

  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

    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

    MSONable dict.

  property center_of_mass: ndarray

    The center of mass of the Slab in fractional coordinates.

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

    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

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

      dct – dict.

    Returns:

      Created from dict.

    Return type:

      Slab

  get_orthogonal_c_slab() → Self

    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

    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]

    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

    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]

    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

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

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

  property surface_area: float

    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

    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

    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)

  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

    An oriented unit cell of the parent structure.

    Type:

      Structure

  parent

    Parent structure from which Slab was derived.

    Type:

      Structure

  lll_reduce

    Whether the slabs will be orthogonalized.

    Type:

      bool

  center_slab

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

    Type:

      bool

  slab_scale_factor

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

    Type:

      float

  miller_index

    Miller index of plane parallel to surface.

    Type:

      tuple

  min_slab_size

    Minimum size of layers containing atoms, in angstroms.

    Type:

      float

  min_vac_size

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

    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

    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]

    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

    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

  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]

  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

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

  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

  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

  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

  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

  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)

  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

    Shorthand for the determinant of the SquareTensor.

  get_scaled(scale_factor: float) → Self

    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

    Shorthand for matrix inverse on SquareTensor.

  is_rotation(tol: float = 0.001, include_improper: bool = True) → bool

    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

    Calculate matrices for polar decomposition.

  property principal_invariants: NDArray

    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

    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

    Shorthand for transpose on SquareTensor.

class Tensor(input_array: NDArray, vscale: NDArray | None = None, check_rank: int | None = None)

  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

    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

    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

    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

    Calculate the result of an einstein summation expression.

  fit_to_structure(structure: Structure, symprec: float = 0.1)

    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

    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

    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

    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]

    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

    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]

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

    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

    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

    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

    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

    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

    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

    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

    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

    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'
  property symmetrized: Self

    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

    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

    The tensor in Voigt notation.

  property voigt_symmetrized: Self

    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

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

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

    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

    Fit all tensors to a Structure.

    Parameters:

      - structure – Structure

      - symprec – symmetry precision.

    Returns:

      TensorCollection.

  classmethod from_dict(dct: dict) → Self

    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

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

      - structure – Structure

      - tol – tolerance.

    Returns:

      Whether all tensors are fitted to Structure.

  is_symmetric(tol: float = 1e-05) → bool
    Parameters:

      tol – tolerance.

    Returns:

      Whether all tensors are symmetric.

  is_voigt_symmetric(tol: float = 1e-06) → bool
    Parameters:

      tol – tolerance.

    Returns:

      Whether all tensors are voigt symmetric.

  property ranks: list

    Ranks for all tensors.

  rotate(matrix, tol: float = 0.001) → Self

    Rotates TensorCollection.

    Parameters:

      - matrix – Rotation matrix.

      - tol – tolerance.

    Returns:

      TensorCollection.

  round(*args, **kwargs) → Self

    Round all tensors.

    Parameters:

      - args – Passthrough to Tensor.round

      - kwargs – Passthrough to Tensor.round

    Returns:

      TensorCollection.

  property symmetrized: Self

    TensorCollection where all tensors are symmetrized.

  transform(symm_op: SymmOp) → Self

    Transforms TensorCollection with a symmetry operation.

    Parameters:

      symm_op – SymmetryOperation.

    Returns:

      TensorCollection.

  property voigt: list[NDArray]

    TensorCollection where all tensors are in Voigt form.

  property voigt_symmetrized: Self

    TensorCollection where all tensors are voigt symmetrized.

  zeroed(tol: float = 0.001) → Self
    Parameters:

      tol – Tolerance.

    Returns:

      TensorCollection where small values are set to 0.

class TensorMapping(tensors: Sequence[Tensor] = (), values: Sequence = (), tol: float = 1e-05)

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

    Items in mapping.

  values()

    Values in mapping.

get_uvec(vec: NDArray) → NDArray

  Get a unit vector parallel to input vector.

symmetry_reduce(tensors, structure: Structure, tol: float = 1e-08, **kwargs) → TensorMapping

  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)

  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.

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

    Return the trajectory as a MSONable dict.

  extend(trajectory: Self) → None

    Append a trajectory to the current one.

    The lattice, coords, and all other properties are combined.

    Parameters:

      trajectory – Trajectory to append.

  classmethod from_ase(trajectory: str | Path | AseTrajectory, constant_lattice: bool | None = None, store_frame_properties: bool = True, property_map: dict[str, str] | None = None, lattice_match_tol: float = 1e-06, additional_fields: Sequence[str] | None = ['temperature', 'velocities']) → Trajectory

    Convert an ASE trajectory to a pymatgen trajectory.

    Parameters:

      - trajectory (str, .Path, or ASE .Trajectory) – the ASE trajectory, or a file path to it if a str or .Path

      - constant_lattice (bool or None) – if a bool, whether the lattice is constant in the .Trajectory. If None, this is determined on the fly.

      - store_frame_properties (bool) – Whether to store pymatgen .Trajectory frame_properties as ASE calculator properties. Defaults to True

      - property_map (dict[str,str]) –

        A mapping between ASE calculator properties and pymatgen .Trajectory frame_properties keys. Ex.:

        > property_map = {“energy”: “e_0_energy”}

        would map e_0_energy in the pymatgen .Trajectory frame_properties to ASE’s get_potential_energy function. See ase.calculators.calculator.all_properties for a list of acceptable calculator properties.

      - lattice_match_tol (float = 1.0e-6) – tolerance to which lattices are matched if constant_lattice = None.

      - additional_fields (Sequence of str, defaults to ["temperature", "velocities"]) – Optional other fields to save in the pymatgen .Trajectory. Valid options are “temperature” and “velocities”.

    Returns:

      pymatgen .Trajectory

  classmethod from_file(filename: str | Path, constant_lattice: bool = True, **kwargs) → Self

    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

    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

    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

    Get molecule at specified index.

    Parameters:

      idx – Index of molecule.

    Returns:

      A pymatgen Molecule object.

  get_structure(idx: int) → Structure

    Get structure at specified index.

    Parameters:

      idx – Index of structure.

    Returns:

      A pymatgen Structure object.

  to_ase(property_map: dict[str, str] | None = None, ase_traj_file: str | Path | None = None) → Trajectory

    Convert a pymatgen .Trajectory to an ASE .Trajectory.

    Parameters:

      - trajectory (pymatgen .Trajectory) – trajectory to convert

      - property_map (dict[str,str]) –

        A mapping between ASE calculator properties and pymatgen .Trajectory frame_properties keys. Ex.:

        > property_map = {“energy”: “e_0_energy”}

        would map e_0_energy in the pymatgen .Trajectory frame_properties to ASE’s get_potential_energy function. See ase.calculators.calculator.all_properties for a list of acceptable calculator properties.

      - ase_traj_file (str, Path, or None (default)) – If not None, the name of the file to write the ASE trajectory to.

    Returns:

      ase .Trajectory

  to_displacements() → None

    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

    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

    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)

  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

    This ArrayWithUnit in base SI units, including derived units.

    Returns:

      ArrayWithUnit in base SI units

  conversions() → str

    Get a string showing the available conversions. Useful tool in interactive mode.

  property supported_units: dict

    Supported units for specific unit type.

  to(new_unit: str | Unit) → Self

    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

    The unit, e.g. “eV”.

  property unit_type: str | None

    The type of unit. Energy, Charge, etc.

Charge = functools.partial(<class 'pymatgen.core.units.FloatWithUnit'>, unit_type='charge')

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

  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)

  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

    This FloatWithUnit in base SI units, including derived units.

    Returns:

      FloatWithUnit in base SI units

  classmethod from_str(string: str) → Self

    Convert string to FloatWithUnit.

    Example usage:

      Memory.from_str(“1. MB”).

  property supported_units: tuple

    Supported units for specific unit type.

  to(new_unit: str | Unit) → Self

    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

    The unit, e.g. “eV”.

  property unit_type: str | None

    The type of unit. Energy, Charge, etc.

Length = functools.partial(<class 'pymatgen.core.units.FloatWithUnit'>, unit_type='length')

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

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

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

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

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

  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]

    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

    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

  Bases: `BaseException`

  Exception class for unit errors.

obj_with_unit(obj: Any, unit: str) → FloatWithUnit | ArrayWithUnit | dict[str, FloatWithUnit | ArrayWithUnit]

  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)

  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)

  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:

  > https://wiki.fysik.dtu.dk/gpaw/setups/pawxml.html

  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')}}
  classmethod aliases() → list[str]

    List of registered names.

  as_dict() → dict

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

  classmethod asxc(obj) → Self

    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')}
  classmethod from_abinit_ixc(ixc: int) → Self | None

    Build the object from Abinit ixc (integer).

  classmethod from_dict(dct: dict) → Self

    Deserialize from MSONable dict representation.

  classmethod from_name(name: str) → Self

    Build the object from one of the registered names.

  classmethod from_type_name(typ: str | None, name: str) → Self

    Build the object from (type, name).

  name()

    The name of the functional. If the functional is not found in the aliases, the string has the form X_NAME+C_NAME.

  type()

    The type of the functional.

  class type_name(type: Literal['LDA', 'GGA'], name: str)

    Bases: `NamedTuple`

    Type and name of the XcFunc.

    Create new instance of type_name(type, name)

    name: str

      Alias for field number 1

    type: Literal['LDA', 'GGA']

      Alias for field number 0

  xcf

    alias of `LibxcFunc`