pymatgen.core package — pymatgen 2026.3.9 documentation

# pymatgen.core package

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

## Subpackages

- pymatgen.core.elasticity package
  - Submodules
  - pymatgen.core.elasticity.elastic module
    - `ComplianceTensor`
    - `ElasticTensor`
      - `ElasticTensor.agne_diffusive_thermalcond()`
      - `ElasticTensor.cahill_thermalcond()`
      - `ElasticTensor.clarke_thermalcond()`
      - `ElasticTensor.compliance_tensor`
      - `ElasticTensor.debye_temperature()`
      - `ElasticTensor.directional_elastic_mod()`
      - `ElasticTensor.directional_poisson_ratio()`
      - `ElasticTensor.from_independent_strains()`
      - `ElasticTensor.from_pseudoinverse()`
      - `ElasticTensor.g_reuss`
      - `ElasticTensor.g_voigt`
      - `ElasticTensor.g_vrh`
      - `ElasticTensor.get_structure_property_dict()`
      - `ElasticTensor.green_kristoffel()`
      - `ElasticTensor.homogeneous_poisson`
      - `ElasticTensor.k_reuss`
      - `ElasticTensor.k_voigt`
      - `ElasticTensor.k_vrh`
      - `ElasticTensor.long_v()`
      - `ElasticTensor.property_dict`
      - `ElasticTensor.snyder_ac()`
      - `ElasticTensor.snyder_opt()`
      - `ElasticTensor.snyder_total()`
      - `ElasticTensor.trans_v()`
      - `ElasticTensor.universal_anisotropy`
      - `ElasticTensor.y_mod`
    - `ElasticTensorExpansion`
      - `ElasticTensorExpansion.calculate_stress()`
      - `ElasticTensorExpansion.energy_density()`
      - `ElasticTensorExpansion.from_diff_fit()`
      - `ElasticTensorExpansion.get_compliance_expansion()`
      - `ElasticTensorExpansion.get_effective_ecs()`
      - `ElasticTensorExpansion.get_ggt()`
      - `ElasticTensorExpansion.get_gruneisen_parameter()`
      - `ElasticTensorExpansion.get_heat_capacity()`
      - `ElasticTensorExpansion.get_stability_criteria()`
      - `ElasticTensorExpansion.get_strain_from_stress()`
      - `ElasticTensorExpansion.get_symmetric_wallace_tensor()`
      - `ElasticTensorExpansion.get_tgt()`
      - `ElasticTensorExpansion.get_wallace_tensor()`
      - `ElasticTensorExpansion.get_yield_stress()`
      - `ElasticTensorExpansion.omega()`
      - `ElasticTensorExpansion.order`
      - `ElasticTensorExpansion.thermal_expansion_coeff()`
    - `NthOrderElasticTensor`
      - `NthOrderElasticTensor.GPa_to_eV_A3`
      - `NthOrderElasticTensor.calculate_stress()`
      - `NthOrderElasticTensor.energy_density()`
      - `NthOrderElasticTensor.from_diff_fit()`
      - `NthOrderElasticTensor.order`
      - `NthOrderElasticTensor.symbol`
    - `diff_fit()`
    - `find_eq_stress()`
    - `generate_pseudo()`
    - `get_diff_coeff()`
    - `get_strain_state_dict()`
    - `get_symbol_list()`
    - `raise_if_unphysical()`
    - `subs()`
  - pymatgen.core.elasticity.strain module
    - `Deformation`
      - `Deformation.apply_to_structure()`
      - `Deformation.from_index_amount()`
      - `Deformation.get_perturbed_indices()`
      - `Deformation.green_lagrange_strain`
      - `Deformation.is_independent()`
      - `Deformation.symbol`
    - `DeformedStructureSet`
      - `DeformedStructureSet.def_structs`
      - `DeformedStructureSet.deformations`
    - `Strain`
      - `Strain.from_deformation()`
      - `Strain.from_index_amount()`
      - `Strain.get_deformation_matrix()`
      - `Strain.symbol`
      - `Strain.von_mises_strain`
    - `convert_strain_to_deformation()`
  - pymatgen.core.elasticity.stress module
    - `Stress`
      - `Stress.dev_principal_invariants`
      - `Stress.deviator_stress`
      - `Stress.mean_stress`
      - `Stress.piola_kirchoff_1()`
      - `Stress.piola_kirchoff_2()`
      - `Stress.symbol`
      - `Stress.von_mises`
- pymatgen.core.structure_prediction package
  - Submodules
  - pymatgen.core.structure_prediction.dopant_predictor module
    - `get_dopants_from_shannon_radii()`
    - `get_dopants_from_substitution_probabilities()`
  - pymatgen.core.structure_prediction.substitution_probability module
    - `SubstitutionPredictor`
      - `SubstitutionPredictor.composition_prediction()`
      - `SubstitutionPredictor.list_prediction()`
    - `SubstitutionProbability`
      - `SubstitutionProbability.as_dict()`
      - `SubstitutionProbability.cond_prob()`
      - `SubstitutionProbability.cond_prob_list()`
      - `SubstitutionProbability.from_dict()`
      - `SubstitutionProbability.get_lambda()`
      - `SubstitutionProbability.get_px()`
      - `SubstitutionProbability.pair_corr()`
      - `SubstitutionProbability.prob()`
  - pymatgen.core.structure_prediction.substitutor module
    - `Substitutor`
      - `Substitutor.as_dict()`
      - `Substitutor.charge_balanced_tol`
      - `Substitutor.from_dict()`
      - `Substitutor.get_allowed_species()`
      - `Substitutor.pred_from_comp()`
      - `Substitutor.pred_from_list()`
      - `Substitutor.pred_from_structures()`
  - pymatgen.core.structure_prediction.volume_predictor module
    - `DLSVolumePredictor`
      - `DLSVolumePredictor.get_predicted_structure()`
      - `DLSVolumePredictor.predict()`
    - `RLSVolumePredictor`
      - `RLSVolumePredictor.get_predicted_structure()`
      - `RLSVolumePredictor.predict()`

## Submodules

## pymatgen.core.adsorption module

This module provides classes used to enumerate surface sites and to find adsorption sites on slabs.

class AdsorbateSiteFinder(slab: Slab | Structure, selective_dynamics: bool = False, height: float = 0.9, mi_vec: ArrayLike | None = None)

  Bases: `object`

  This class finds adsorbate sites on slabs and generates adsorbate structures according to user-defined criteria.

  The algorithm for finding sites is essentially as follows:
    1. Determine “surface sites” by finding those within

         a height threshold along the miller index of the highest site

    2. Create a network of surface sites using the Delaunay

         triangulation of the surface sites

    3. Assign on-top, bridge, and hollow adsorption sites

         at the nodes, edges, and face centers of the Del. Triangulation

    4. Generate structures from a molecule positioned at

         these sites

  Create an AdsorbateSiteFinder object.

  Parameters:

    - slab (Slab) – slab object for which to find adsorbate sites

    - selective_dynamics (bool) – flag for whether to assign non-surface sites as fixed for selective dynamics

    - height (float) – height criteria for selection of surface sites

    - mi_vec (3-D array-like) – vector corresponding to the vector concurrent with the miller index, this enables use with slabs that have been reoriented, but the miller vector must be supplied manually

  add_adsorbate(molecule: Molecule, ads_coord, repeat=None, translate=True, reorient=True)

    Add an adsorbate at a particular coordinate. Adsorbate represented by a Molecule object and is translated to (0, 0, 0) if translate is True, or positioned relative to the input adsorbate coordinate if translate is False.

    Parameters:

      - molecule (Molecule) – molecule object representing the adsorbate

      - ads_coord (array) – coordinate of adsorbate position

      - repeat (3-tuple or list) – input for making a supercell of slab prior to placing the adsorbate

      - translate (bool) – flag on whether to translate the molecule so that its CoM is at the origin prior to adding it to the surface

      - reorient (bool) – flag on whether to reorient the molecule to have its z-axis concurrent with miller index

  adsorb_both_surfaces(molecule, repeat=None, min_lw=5.0, translate=True, reorient=True, find_args=None)

    Generate all adsorption structures for a given molecular adsorbate on both surfaces of a slab. This is useful for calculating surface energy where both surfaces need to be equivalent or if we want to calculate nonpolar systems.

    Parameters:

      - molecule (Molecule) – molecule corresponding to adsorbate

      - repeat (3-tuple or list) – repeat argument for supercell generation

      - min_lw (float) – minimum length and width of the slab, only used if repeat is None

      - translate (bool) – flag on whether or not to translate adsorbate to the adsorption site

      - reorient (bool) – flag on whether or not to reorient adsorbate along the miller index

      - find_args (dict) – dictionary of arguments to be passed to the call to self.find_adsorption_sites, e.g. {“distance”:2.0}

  classmethod assign_selective_dynamics(slab)

    Helper function to assign selective dynamics site_properties based on surface, subsurface site properties.

    Parameters:

      slab (Slab) – slab for which to assign selective dynamics

  assign_site_properties(slab: Slab, height=0.9)

    Assign site properties.

  classmethod ensemble_center(site_list, indices, cartesian=True)

    Find the center of an ensemble of sites selected from a list of sites. Helper method for the find_adsorption_sites algorithm.

    Parameters:

      - site_list (list[Site]) – sites from which to select

      - indices (list[int]) – indices of sites from which to select sites from site list

      - cartesian (bool) – whether to get average fractional or Cartesian coordinate

  find_adsorption_sites(distance=2.0, put_inside=True, symm_reduce=0.01, near_reduce=0.01, positions=('ontop', 'bridge', 'hollow'), no_obtuse_hollow=True)

    Find surface sites according to the above algorithm. Returns a list of corresponding Cartesian coordinates.

    Parameters:

      - distance (float) – distance from the coordinating ensemble of atoms along the miller index for the site (i.e. the distance from the slab itself)

      - put_inside (bool) – whether to put the site inside the cell

      - symm_reduce (float) – symm reduction threshold

      - near_reduce (float) – near reduction threshold

      - positions (list) –

        which positions to include in the site finding “ontop”: sites on top of surface sites “bridge”: sites at edges between surface sites in Delaunay

        > triangulation of surface sites in the miller plane

        ”hollow”: sites at centers of Delaunay triangulation faces “subsurface”: subsurface positions projected into miller plane

      - no_obtuse_hollow (bool) – flag to indicate whether to include obtuse triangular ensembles in hollow sites

  find_surface_sites_by_height(slab: Slab, height=0.9, xy_tol=0.05)

    Find surface sites by determining which sites are within a threshold value in height from the topmost site in a list of sites.

    Parameters:

      - slab (Slab) – slab for which to find surface sites

      - height (float) – threshold in angstroms of distance from topmost site in slab along the slab c-vector to include in surface site determination

      - xy_tol (float) – if supplied, will remove any sites which are within a certain distance in the miller plane.

    Returns:

      list of sites selected to be within a threshold of the highest

  classmethod from_bulk_and_miller(structure, miller_index, min_slab_size=8.0, min_vacuum_size=10.0, max_normal_search=None, center_slab=True, selective_dynamics=False, undercoord_threshold=0.09) → Self

    Construct the adsorbate site finder from a bulk structure and a miller index, which allows the surface sites to be determined from the difference in bulk and slab coordination, as opposed to the height threshold.

    Parameters:

      - structure (Structure) – structure from which slab input to the ASF is constructed

      - miller_index (3-tuple or list) – miller index to be used

      - min_slab_size (float) – min slab size for slab generation

      - min_vacuum_size (float) – min vacuum size for slab generation

      - max_normal_search (int) – max normal search for slab generation

      - center_slab (bool) – whether to center slab in slab generation

      - selective_dynamics (bool) – whether to assign surface sites to selective dynamics

      - undercoord_threshold (float) – threshold of “undercoordation” to use for the assignment of surface sites. Default is 0.1, for which surface sites will be designated if they are 10% less coordinated than their bulk counterpart

  generate_adsorption_structures(molecule, repeat=None, min_lw=5.0, translate=True, reorient=True, find_args=None)

    Generate all adsorption structures for a given molecular adsorbate. Can take repeat argument or minimum length/width of precursor slab as an input.

    Parameters:

      - molecule (Molecule) – molecule corresponding to adsorbate

      - repeat (3-tuple or list) – repeat argument for supercell generation

      - min_lw (float) – minimum length and width of the slab, only used if repeat is None

      - translate (bool) – flag on whether to translate the molecule so that its CoM is at the origin prior to adding it to the surface

      - reorient (bool) – flag on whether or not to reorient adsorbate along the miller index

      - find_args (dict) – dictionary of arguments to be passed to the call to self.find_adsorption_sites, e.g. {“distance”:2.0}

  generate_substitution_structures(atom, target_species=None, sub_both_sides=False, range_tol=0.01, dist_from_surf=0)

    Perform substitution-type doping on the surface and returns all possible configurations where one dopant is substituted per surface. Can substitute one surface or both.

    Parameters:

      - atom (str) – atom corresponding to substitutional dopant

      - sub_both_sides (bool) – If true, substitute an equivalent site on the other surface

      - target_species (list) – Specific species to substitute

      - range_tol (float) – Find viable substitution sites at a specific distance from the surface +- this tolerance

      - dist_from_surf (float) – Distance from the surface to find viable substitution sites, defaults to 0 to substitute at the surface

  get_extended_surface_mesh(repeat=(5, 5, 1))

    Get an extended surface mesh for to use for adsorption site finding by constructing supercell of surface sites.

    Parameters:

      repeat (3-tuple) – repeat for getting extended surface mesh

  near_reduce(coords_set, threshold=0.0001)

    Prune coordinate set for coordinates that are within threshold.

    Parameters:

      - coords_set (Nx3 array-like) – list or array of coordinates

      - threshold (float) – threshold value for distance

  subsurface_sites()

    Convenience method to return list of subsurface sites.

  property surface_sites

    Convenience method to return a list of surface sites.

  symm_reduce(coords_set, threshold=1e-06)

    Reduce the set of adsorbate sites by finding removing symmetrically equivalent duplicates.

    Parameters:

      - coords_set – coordinate set in Cartesian coordinates

      - threshold – tolerance for distance equivalence, used as input to in_coord_list_pbc for dupl. checking

get_mi_vec(slab)

  Convenience function which returns the unit vector aligned with the miller index.

get_rot(slab: Slab) → SymmOp

  Get the transformation to rotate the z axis into the miller index.

plot_slab(slab: Slab, ax: Axes, scale=0.8, repeat=5, window=1.5, draw_unit_cell=True, decay=0.2, adsorption_sites=True, inverse=False)

  Help visualize the slab in a 2-D plot, for convenient viewing of output of AdsorbateSiteFinder.

  Parameters:

    - slab (slab) – Slab object to be visualized

    - ax (axes) – matplotlib axes with which to visualize

    - scale (float) – radius scaling for sites

    - repeat (int) – number of repeating unit cells to visualize

    - window (float) – window for setting the axes limits, is essentially a fraction of the unit cell limits

    - draw_unit_cell (bool) – flag indicating whether or not to draw cell

    - adsorption_sites (bool) – whether to plot adsorption sites

    - decay (float) – how the alpha-value decays along the z-axis

    - inverse (bool) – invert z axis to plot opposite surface

put_coord_inside(lattice, cart_coordinate)

  Convert a Cartesian coordinate such that it is inside the unit cell.

reorient_z(structure)

  Reorient a structure such that the z axis is concurrent with the normal to the A-B plane.

## pymatgen.core.bond_valence module

This module implements classes to perform bond valence analyses.

class BVAnalyzer(symm_tol=0.1, max_radius=4, max_permutations=100000, distance_scale_factor=1.015, charge_neutrality_tolerance=1e-05, forbidden_species=None)

  Bases: `object`

  This class implements a maximum a posteriori (MAP) estimation method to determine oxidation states in a structure. The algorithm is as follows: 1) The bond valence sum of all symmetrically distinct sites in a structure is calculated using the element-based parameters in M. O’Keefe, & N. Brese, JACS, 1991, 113(9), 3226-3229. doi:10.1021/ja00009a002. 2) The posterior probabilities of all oxidation states is then calculated using: P(oxi_state/BV) = K * P(BV/oxi_state) * P(oxi_state), where K is a constant factor for each element. P(BV/oxi_state) is calculated as a Gaussian with mean and std deviation determined from an analysis of the ICSD. The posterior P(oxi_state) is determined from a frequency analysis of the ICSD. 3) The oxidation states are then ranked in order of decreasing probability and the oxidation state combination that result in a charge neutral cell is selected.

  Initialize the BV analyzer, with useful defaults.

  Parameters:

    - symm_tol – Symmetry tolerance used to determine which sites are symmetrically equivalent. Set to 0 to turn off symmetry.

    - max_radius – Maximum radius in Angstrom used to find nearest neighbors.

    - max_permutations – The maximum number of permutations of oxidation states to test.

    - distance_scale_factor – A scale factor to be applied. This is useful for scaling distances, esp in the case of calculation-relaxed structures which may tend to under (GGA) or over bind (LDA). The default of 1.015 works for GGA. For experimental structure, set this to 1.

    - charge_neutrality_tolerance – Tolerance on the charge neutrality when unordered structures are at stake.

    - forbidden_species – List of species that are forbidden (example : [“O-”] cannot be used) It is used when e.g. someone knows that some oxidation state cannot occur for some atom in a structure or list of structures.

  CHARGE_NEUTRALITY_TOLERANCE = 1e-05
  get_oxi_state_decorated_structure(structure: Structure) → Structure

    Get an oxidation state decorated structure. This currently works only for ordered structures only.

    Parameters:

      structure – Structure to analyze

    Returns:

      modified with oxidation state decorations.

    Return type:

      Structure

    Raises:

      ValueError if the valences cannot be determined. –

  get_valences(structure: Structure)

    Get a list of valences for each site in the structure.

    Parameters:

      structure – Structure to analyze

    Returns:

      A list of valences for each site in the structure (for an ordered structure), e.g. [1, 1, -2] or a list of lists with the valences for each fractional element of each site in the structure (for an unordered structure), e.g. [[2, 4], [3], [-2], [-2], [-2]]

    Raises:

      A ValueError if the valences cannot be determined. –

add_oxidation_state_by_site_fraction(structure: Structure, oxidation_states: list[list[int]]) → Structure

  Add oxidation states to a structure by fractional site.

  Parameters:

    - structure (Structure) – Structure to which oxidation states are added.

    - oxidation_states (list[list[int]]) – List of list of oxidation states for each site fraction for each site. e.g. [[2, 4], [3], [-2], [-2], [-2]]

calculate_bv_sum(site, nn_list, scale_factor=1.0)

  Calculate the BV sum of a site.

  Parameters:

    - site (PeriodicSite) – The central site to calculate the bond valence

    - nn_list ([Neighbor]) – A list of namedtuple Neighbors having “distance” and “site” attributes

    - scale_factor (float) – A scale factor to be applied. This is useful for scaling distance, esp in the case of calculation-relaxed structures which may tend to under (GGA) or over bind (LDA).

calculate_bv_sum_unordered(site, nn_list, scale_factor=1)

  Calculate the BV sum of a site for unordered structures.

  Parameters:

    - site (PeriodicSite) – The central site to calculate the bond valence

    - nn_list ([Neighbor]) – A list of namedtuple Neighbors having “distance” and “site” attributes

    - scale_factor (float) – A scale factor to be applied. This is useful for scaling distance, esp in the case of calculation-relaxed structures which may tend to under (GGA) or over bind (LDA).

get_z_ordered_elmap(comp)

  Arbitrary ordered element map on the elements/species of a composition of a given site in an unordered structure. Returns a list of tuples ( element_or_specie: occupation) in the arbitrary order.

  The arbitrary order is based on the Z of the element and the smallest fractional occupations first. Example : {“Ni3+”: 0.2, “Ni4+”: 0.2, “Cr3+”: 0.15, “Zn2+”: 0.34, “Cr4+”: 0.11} will yield the species in the following order : Cr4+, Cr3+, Ni3+, Ni4+, Zn2+ … or Cr4+, Cr3+, Ni4+, Ni3+, Zn2+

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

  Initializes the object with two site instances.

  This constructor method assigns the provided site1 and site2 parameters to the instance attributes, enabling interaction with two separate Site objects.

  Parameters:

    - site1 – The first site object.

    - site2 – The second site object.

  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_data_dict() → dict[Literal['reduced_cell_composition', 'unit_cell_composition', 'reduced_cell_formula', 'elements', 'nelements'], Any]
    Returns:

      - reduced_cell_composition

      - unit_cell_composition

      - reduced_cell_formula

      - elements

      - nelements.

    Return type:

      dict with the following keys

  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]

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

      element symbols mapped to reduced amount e.g. {“Fe”: 2.0, “O”: 3.0}.

    Return type:

      dict[str, float]

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

      weight fractions of each component, e.g. {“Ti”: 0.90, “V”: 0.06, “Al”: 0.04}.

    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

    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

    Deprecated.

  to_pretty_string() → str
    Returns:

      Same output as __str__() but without spaces.

    Return type:

      str

  property to_reduced_dict

    Deprecated.

  property to_weight_dict: dict[str, float]

    Deprecated.

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

    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.energy_models module

This module implements a EnergyModel abstract class and some basic implementations. Basically, an EnergyModel is any model that returns an “energy” for any given structure.

class EnergyModel

  Bases: `MSONable`, `ABC`

  Abstract structure filter class.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      EnergyModel

  abstractmethod get_energy(structure) → float
    Parameters:

      structure – Structure.

    Returns:

      Energy value

class EwaldElectrostaticModel(real_space_cut=None, recip_space_cut=None, eta=None, acc_factor=8.0)

  Bases: `EnergyModel`

  Wrapper around EwaldSum to calculate the electrostatic energy.

  Initialize the model. Args have the same definitions as in pymatgen.core.ewald.EwaldSummation.

  Parameters:

    - real_space_cut (float) – Real space cutoff radius dictating how many terms are used in the real space sum. Defaults to None, which means determine automatically using the formula given in gulp 3.1 documentation.

    - recip_space_cut (float) – Reciprocal space cutoff radius. Defaults to None, which means determine automatically using the formula given in gulp 3.1 documentation.

    - eta (float) – Screening parameter. Defaults to None, which means determine automatically.

    - acc_factor (float) – No. of significant figures each sum is converged to.

  as_dict()

    MSONable dict.

  get_energy(structure: Structure)
    Parameters:

      structure – Structure.

    Returns:

      Energy value

class IsingModel(j, max_radius)

  Bases: `EnergyModel`

  A very simple Ising model, with r^2 decay.

  Parameters:

    - j (float) – The interaction parameter. E = J * spin1 * spin2.

    - max_radius (float) – max_radius for the interaction.

  as_dict()

    MSONable dict.

  get_energy(structure: Structure)
    Parameters:

      structure – Structure.

    Returns:

      Energy value

class NsitesModel

  Bases: `EnergyModel`

  Sets the energy to the number of sites. More sites => higher “energy”. Used to rank structures from smallest number of sites to largest number of sites after enumeration.

  as_dict()

    MSONable dict.

  get_energy(structure: Structure)
    Parameters:

      structure – Structure.

    Returns:

      Energy value

class SymmetryModel(symprec: float = 0.1, angle_tolerance=5)

  Bases: `EnergyModel`

  Sets the energy to the negative of the spacegroup number. Higher symmetry => lower “energy”.

  Args have same meaning as in pymatgen.symmetry.SpacegroupAnalyzer.

  Parameters:

    - symprec (float) – Symmetry tolerance. Defaults to 0.1.

    - angle_tolerance (float) – Tolerance for angles. Defaults to 5 degrees.

  as_dict()

    MSONable dict.

  get_energy(structure: Structure)
    Parameters:

      structure – Structure.

    Returns:

      Energy value

## pymatgen.core.entries module

Entries are containers for calculated information, which is used in many analyses. This module contains entry related tools and implements the base Entry class, which is the basic entity that can be used to store calculated information. Other Entry classes such as ComputedEntry and PDEntry inherit from this class. This module implements equivalents of the basic ComputedEntry objects, which is the basic entity that can be used to perform many analyses. ComputedEntries contain calculated information, typically from VASP or other electronic structure codes. For example, ComputedEntries can be used as inputs for phase diagram analysis. Also implements functions to perform various useful operations on entries, such as grouping entries by structure.

class CompositionEnergyAdjustment(adj_per_atom: float, n_atoms: float, uncertainty_per_atom: float = nan, name: str = '', cls: dict | None = None, description: str = 'Composition-based energy adjustment')

  Bases: `EnergyAdjustment`

  An energy adjustment applied to a ComputedEntry based on the atomic composition. Used in various DFT energy correction schemes.

  Parameters:

    - adj_per_atom (float) – energy adjustment to apply per atom, in eV/atom

    - n_atoms (float) – number of atoms.

    - uncertainty_per_atom (float) – uncertainty in energy adjustment to apply per atom, in eV/atom. (Default: np.nan)

    - name (str) – human-readable name of the energy adjustment. (Default: “”)

    - cls (dict) – Serialized Compatibility class used to generate the energy adjustment. (Default: None)

    - description (str) – human-readable explanation of the energy adjustment.

  property explain: str

    An explanation of how the energy adjustment is calculated.

  normalize(factor: float) → None

    Normalize energy adjustment (in place), dividing value/uncertainty by a factor.

    Parameters:

      factor – factor to divide by.

  property uncertainty: float

    The value of the energy adjustment in eV.

  property value: float

    The value of the energy adjustment in eV.

class ComputedEntry(composition: Composition | str | dict[str, float], energy: float, correction: float = 0.0, energy_adjustments: list | None = None, parameters: dict | None = None, data: dict | None = None, entry_id: str | None = None)

  Bases: `Entry`

  Lightweight Entry object for computed data. Contains facilities for applying corrections to the energy attribute and for storing calculation parameters.

  Initialize a ComputedEntry.

  Parameters:

    - composition (Composition) – Composition of the entry. For flexibility, this can take the form of all the typical input taken by a Composition, including a {symbol: amt} dict, a string formula, and others.

    - energy (float) – Energy of the entry. Usually the final calculated energy from VASP or other electronic structure codes.

    - correction (float) – Manually set an energy correction, will ignore energy_adjustments if specified.

    - energy_adjustments – An optional list of EnergyAdjustment to be applied to the energy. This is used to modify the energy for certain analyses. Defaults to None.

    - parameters – An optional dict of parameters associated with the entry. Defaults to None.

    - data – An optional dict of any additional data associated with the entry. Defaults to None.

    - entry_id – An optional id to uniquely identify the entry.

  as_dict() → dict

    MSONable dict.

  copy() → ComputedEntry

    Get a copy of the ComputedEntry.

  property correction: float

    Returns: float: the total energy correction / adjustment applied to the entry in eV.

  property correction_per_atom: float

    Returns: float: the total energy correction / adjustment applied to the entry in eV/atom.

  property correction_uncertainty: float

    Returns: float: the uncertainty of the energy adjustments applied to the entry in eV.

  property correction_uncertainty_per_atom: float

    Returns: float: the uncertainty of the energy adjustments applied to the entry in eV/atom.

  property energy: float

    The corrected energy of the entry.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      ComputedEntry

  normalize(mode: Literal['formula_unit', 'atom'] = 'formula_unit') → ComputedEntry

    Normalize the entry’s composition and energy.

    Parameters:

      mode ("formula_unit" | "atom") – “formula_unit” (the default) normalizes to composition.reduced_formula. “atom” normalizes such that the composition amounts sum to 1.

  property uncorrected_energy: float

    Returns: float: the uncorrected energy of the entry.

  property uncorrected_energy_per_atom: float

    Returns: float: the uncorrected energy of the entry, normalized by atoms in eV/atom.

class ComputedStructureEntry(structure: Structure, energy: float, correction: float = 0.0, composition: Composition | str | dict[str, float] | None = None, energy_adjustments: list | None = None, parameters: dict | None = None, data: dict | None = None, entry_id: str | None = None)

  Bases: `ComputedEntry`

  A heavier version of ComputedEntry which contains a structure as well. The structure is needed for some analyses.

  Initialize a ComputedStructureEntry.

  Parameters:

    - structure (Structure) – The actual structure of an entry.

    - energy (float) – Energy of the entry. Usually the final calculated energy from VASP or other electronic structure codes.

    - correction (float, optional) – A correction to the energy. This is mutually exclusive with energy_adjustments, i.e. pass either or neither but not both. Defaults to 0.

    - composition (Composition) – Composition of the entry. For flexibility, this can take the form of all the typical input taken by a Composition, including a {symbol: amt} dict, a string formula, and others.

    - energy_adjustments – An optional list of EnergyAdjustment to be applied to the energy. This is used to modify the energy for certain analyses. Defaults to None.

    - parameters – An optional dict of parameters associated with the entry. Defaults to None.

    - data – An optional dict of any additional data associated with the entry. Defaults to None.

    - entry_id – An optional id to uniquely identify the entry.

  as_dict() → dict

    MSONable dict.

  copy() → ComputedStructureEntry

    Get a copy of the ComputedStructureEntry.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      ComputedStructureEntry

  normalize(mode: Literal['formula_unit', 'atom'] = 'formula_unit') → ComputedStructureEntry

    Normalize the entry’s composition and energy. The structure remains unchanged.

    Parameters:

      mode ("formula_unit" | "atom") – “formula_unit” (the default) normalizes to composition.reduced_formula. “atom” normalizes such that the composition amounts sum to 1.

  property structure: Structure

    The structure of the entry.

class ConstantEnergyAdjustment(value: float, uncertainty: float = nan, name: str = 'Constant energy adjustment', cls: dict | None = None, description: str = 'Constant energy adjustment')

  Bases: `EnergyAdjustment`

  A constant energy adjustment applied to a ComputedEntry. Useful in energy referencing schemes such as the Aqueous energy referencing scheme.

  Parameters:

    - value (float) – the energy adjustment in eV

    - uncertainty (float) – uncertainty of the energy adjustment in eV. (Default: np.nan)

    - name (str) – human-readable name of the energy adjustment. (Default: Constant energy adjustment)

    - cls (dict) – Serialized Compatibility class used to generate the energy adjustment. (Default: None)

    - description (str) – human-readable explanation of the energy adjustment.

  property explain: str

    An explanation of how the energy adjustment is calculated.

  normalize(factor: float) → None

    Normalize energy adjustment (in place), dividing value/uncertainty by a factor.

    Parameters:

      factor (float) – factor to divide by.

class EnergyAdjustment(value: float, uncertainty: float = nan, name: str = 'Manual adjustment', cls: dict | None = None, description: str = '')

  Bases: `MSONable`

  Lightweight class to contain information about an energy adjustment or energy correction.

  Parameters:

    - value (float) – value of the energy adjustment in eV

    - uncertainty (float) – uncertainty of the energy adjustment in eV. Default: np.nan

    - name (str) – human-readable name of the energy adjustment. (Default: Manual adjustment)

    - cls (dict) – Serialized Compatibility class used to generate the energy adjustment. Defaults to {}.

    - description (str) – human-readable explanation of the energy adjustment.

  abstract property explain: str

    Return an explanation of how the energy adjustment is calculated.

  abstractmethod normalize(factor: float) → None

    Scale the value of the current energy adjustment by factor in-place.

    This method is utilized in ComputedEntry.normalize() to scale the energies to a formula unit basis (e.g. E_Fe6O9 = 3 x E_Fe2O3).

  property uncertainty: float

    The uncertainty in the value of the energy adjustment in eV.

  property value: float

    The value of the energy correction in eV.

class Entry(composition: Composition | str | dict[str, float], energy: float)

  Bases: `MSONable`, `ABC`

  A lightweight object containing the energy associated with a specific chemical composition. This base class is not intended to be instantiated directly. Note that classes which inherit from Entry must define a .energy property.

  Initialize an Entry.

  Parameters:

    - composition (Composition) – Composition of the entry. For flexibility, this can take the form of all the typical input taken by a Composition, including a {symbol: amt} dict, a string formula, and others.

    - energy (float) – Energy of the entry.

  as_dict() → dict

    MSONable dict.

  property composition: Composition

    The composition of the entry.

  property elements: list[Element | Species | DummySpecies]

    The set of elements in the entry.

  abstract property energy: float

    The energy of the entry.

  property energy_per_atom: float

    The energy per atom of the entry.

  property formula: str

    The formula of the entry.

  property is_element: bool

    Whether composition of entry is an element.

  normalize(mode: Literal['formula_unit', 'atom'] = 'formula_unit') → Entry

    Normalize the entry’s composition and energy.

    Parameters:

      mode ("formula_unit" | "atom") – “formula_unit” (the default) normalizes to composition.reduced_formula. “atom” normalizes such that the composition amounts sum to 1.

  property reduced_formula: str

    The reduced formula of the entry.

class EntrySet(entries: Iterable[PDEntry | ComputedEntry | ComputedStructureEntry])

  Bases: `MutableSet`, `MSONable`

  A convenient container for manipulating entries. Allows for generating subsets, dumping into files, etc.

  Parameters:

    entries – All the entries.

  add(element)

    Add an entry.

    Parameters:

      element – Entry

  as_dict() → dict[Literal['entries'], list[Entry]]

    Get MSONable dict.

  property chemsys: set

    Returns: set representing the chemical system, e.g. {“Li”, “Fe”, “P”, “O”}.

  discard(element)

    Discard an entry.

    Parameters:

      element – Entry

  classmethod from_csv(filename: str) → Self

    Imports PDEntries from a csv.

    Parameters:

      filename – Filename to import from.

    Returns:

      List of Elements, List of PDEntries

  get_subset_in_chemsys(chemsys: list[str])

    Get an EntrySet containing only the set of entries belonging to a particular chemical system (in this definition, it includes all sub systems). For example, if the entries are from the Li-Fe-P-O system, and chemsys=[“Li”, “O”], only the Li, O, and Li-O entries are returned.

    Parameters:

      chemsys – Chemical system specified as list of elements. e.g. [“Li”, “O”]

    Returns:

      EntrySet

  property ground_states: set

    A set containing only the entries that are ground states, i.e., the lowest energy per atom entry at each composition.

  is_ground_state(entry) → bool

    Boolean indicating whether a given Entry is a ground state.

  remove_non_ground_states()

    Removes all non-ground state entries, i.e., only keep the lowest energy per atom entry at each composition.

  to_csv(filename: str, latexify_names: bool = False) → None

    Exports PDEntries to a csv.

    Parameters:

      - filename – Filename to write to.

      - entries – PDEntries to export.

      - latexify_names – Format entry names to be LaTex compatible, e.g. Li_{2}O

class ManualEnergyAdjustment(value: float)

  Bases: `ConstantEnergyAdjustment`

  A manual energy adjustment applied to a ComputedEntry.

  Parameters:

    value (float) – the energy adjustment in eV.

class TemperatureEnergyAdjustment(adj_per_deg: float, temp: float, n_atoms: float, uncertainty_per_deg: float = nan, name: str = '', cls: dict | None = None, description: str = 'Temperature-based energy adjustment')

  Bases: `EnergyAdjustment`

  An energy adjustment applied to a ComputedEntry based on the temperature. Used, for example, to add entropy to DFT energies.

  Parameters:

    - adj_per_deg (float) – energy adjustment to apply per degree K, in eV/atom

    - temp (float) – temperature in Kelvin

    - n_atoms (float) – number of atoms

    - uncertainty_per_deg (float) – uncertainty in energy adjustment to apply per degree K, in eV/atom. (Default: np.nan)

    - name (str) – human-readable name of the energy adjustment. (Default: “”)

    - cls (dict) – Serialized Compatibility class used to generate the energy adjustment. (Default: None)

    - description (str) – human-readable explanation of the energy adjustment.

  property explain: str

    An explanation of how the energy adjustment is calculated.

  normalize(factor: float) → None

    Normalize energy adjustment (in place), dividing value/uncertainty by a factor.

    Parameters:

      factor – factor to divide by.

  property uncertainty: float

    The value of the energy adjustment in eV.

  property value: float

    The value of the energy correction in eV.

group_entries_by_composition(entries, sort_by_e_per_atom=True)
  Given a sequence of Entry-like objects, group them by composition and

    optionally sort by energy above hull.

  Parameters:

    - entries (list) – Sequence of Entry-like objects.

    - sort_by_e_per_atom (bool) – Whether to sort the grouped entries by energy per atom (lowest energy first). Default True.

  Returns:

    Sequence of sequence of entries by composition. e.g, [[ entry1, entry2], [entry3, entry4, entry5]]

group_entries_by_structure(entries, species_to_remove=None, ltol=0.2, stol=0.4, angle_tol=5, primitive_cell=True, scale=True, comparator=None, ncpus=None)

  Given a sequence of ComputedStructureEntries, use structure fitter to group them by structural similarity.

  Parameters:

    - entries – Sequence of ComputedStructureEntries.

    - species_to_remove – Sometimes you want to compare a host framework (e.g., in Li-ion battery analysis). This allows you to specify species to remove before structural comparison.

    - ltol (float) – Fractional length tolerance. Default is 0.2.

    - stol (float) – Site tolerance in Angstrom. Default is 0.4 Angstrom.

    - angle_tol (float) – Angle tolerance in degrees. Default is 5 degrees.

    - primitive_cell (bool) – If true: input structures will be reduced to primitive cells prior to matching. Defaults to True.

    - scale – Input structures are scaled to equivalent volume if true; For exact matching, set to False.

    - comparator – A comparator object implementing an equals method that declares equivalency of sites. Default is SpeciesComparator, which implies rigid species mapping.

    - ncpus – Number of cpus to use. Use of multiple cpus can greatly improve fitting speed. Default of None means serial processing.

  Returns:

    Sequence of sequence of entries by structural similarity. e.g, [[ entry1, entry2], [entry3, entry4, entry5]]

## pymatgen.core.ewald module

This module provides classes for calculating the Ewald sum of a structure.

class EwaldMinimizer(matrix, m_list, num_to_return=1, algo=0)

  Bases: `object`

  This class determines the manipulations that will minimize an Ewald matrix, given a list of possible manipulations. This class does not perform the manipulations on a structure, but will return the list of manipulations that should be done on one to produce the minimal structure. It returns the manipulations for the n lowest energy orderings. This class should be used to perform fractional species substitution or fractional species removal to produce a new structure. These manipulations create large numbers of candidate structures, and this class can be used to pick out those with the lowest Ewald sum.

  An alternative (possibly more intuitive) interface to this class is the order disordered structure transformation.

  Author - Will Richards

  Parameters:

    - matrix – A matrix of the Ewald sum interaction energies. This is stored in the class as a diagonally symmetric array and so self._matrix will not be the same as the input matrix.

    - m_list – list of manipulations. each item is of the form (multiplication fraction, number_of_indices, indices, species) These are sorted such that the first manipulation contains the most permutations. this is actually evaluated last in the recursion since I’m using pop.

    - num_to_return – The minimizer will find the number_returned lowest energy structures. This is likely to return a number of duplicate

    - algo – Algorithm to use for minimization. structures so it may be necessary to overestimate and then remove the duplicates later. (duplicate checking in this process is extremely expensive).

  ALGO_BEST_FIRST = 2
  ALGO_COMPLETE = 1
  ALGO_FAST = 0
  ALGO_TIME_LIMIT = 3
  add_m_list(matrix_sum, m_list)

    Add an m_list to the output_lists and updates the current minimum if the list is full.

  best_case(matrix, m_list, indices_left)

    Compute a best case given a matrix and manipulation list.

    Parameters:

      - matrix – the current matrix (with some permutations already performed)

      - m_list – [(multiplication fraction, number_of_indices, indices, species)] describing the manipulation

      - indices_left – Set of indices which haven’t had a permutation performed on them.

  property best_m_list

    The best manipulation list found.

  classmethod get_next_index(matrix, manipulation, indices_left)

    Get an index that should have the most negative effect on the matrix sum.

  minimize_matrix()

    Get the permutations that produce the lowest Ewald sum calls recursive function to iterate through permutations.

  property minimized_sum

    The minimized Ewald sum.

  property output_lists

    Output lists.

class EwaldSummation(structure, real_space_cut=None, recip_space_cut=None, eta=None, acc_factor=12.0, w=0.7071067811865475, compute_forces=False)

  Bases: `MSONable`

  Calculates the electrostatic energy of a periodic array of charges using the Ewald technique.

  Ref:

    Ewald summation techniques in perspective: a survey Abdulnour Y. Toukmaji and John A. Board Jr. DOI: 10.1016/0010-4655(96)00016-1 URL: http://www.ee.duke.edu/~ayt/ewaldpaper/ewaldpaper.html

  This matrix can be used to do fast calculations of Ewald sums after species removal.

  E = E_recip + E_real + E_point

  Atomic units used in the code, then converted to eV.

  Initialize and calculate the Ewald sum. Default convergence parameters have been specified, but you can override them if you wish.

  Parameters:

    - structure (Structure) – Input structure that must have proper Species on all sites, i.e. Element with oxidation state. Use Structure.add_oxidation_state… for example.

    - real_space_cut (float) – Real space cutoff radius dictating how many terms are used in the real space sum. Defaults to None, which means determine automatically using the formula given in gulp 3.1 documentation.

    - recip_space_cut (float) – Reciprocal space cutoff radius. Defaults to None, which means determine automatically using the formula given in gulp 3.1 documentation.

    - eta (float) – The screening parameter. Defaults to None, which means determine automatically.

    - acc_factor (float) – No. of significant figures each sum is converged to.

    - w (float) – Weight parameter, w, has been included that represents the relative computational expense of calculating a term in real and reciprocal space. Default of 0.7 reproduces result similar to GULP 4.2. This has little effect on the total energy, but may influence speed of computation in large systems. Note that this parameter is used only when the cutoffs are set to None.

    - compute_forces (bool) – Whether to compute forces. False by default since it is usually not needed.

  CONV_FACT = 14.399645468667815
  as_dict(verbosity: int = 0) → dict

    JSON-serialization dict representation of EwaldSummation.

    Parameters:

      verbosity (int) – Verbosity level. Default of 0 only includes the matrix representation. Set to 1 for more details.

  compute_partial_energy(removed_indices)

    Get total Ewald energy for certain sites being removed, i.e. zeroed out.

  compute_sub_structure(sub_structure, tol: float = 0.001)

    Get total Ewald energy for an sub structure in the same lattice. The sub_structure must be a subset of the original structure, with possible different charges.

    Parameters:

      - sub_structure (Structure) – Substructure to compute Ewald sum for.

      - tol (float) – Tolerance for site matching in fractional coordinates.

    Returns:

      Ewald sum of substructure.

  property eta

    Eta value used in Ewald summation.

  property forces

    The forces on each site as a Nx3 matrix. Each row corresponds to a site.

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

    Create an EwaldSummation instance from JSON-serialized dictionary.

    Parameters:

      - dct (dict) – Dictionary representation

      - fmt (str, optional) – Unused. Defaults to None.

      - **kwargs – Additional keyword arguments.

    Returns:

      class instance

    Return type:

      EwaldSummation

  get_site_energy(site_index)

    Compute the energy for a single site in the structure.

    Parameters:

      site_index (int) – Index of site

    Returns:

      Energy of that site

    Return type:

      float

  property point_energy

    The point energy.

  property point_energy_matrix

    The point space matrix. A diagonal matrix with the point terms for each site in the diagonal elements.

  property real_space_energy

    The real space energy.

  property real_space_energy_matrix

    The real space energy matrix. Each matrix element (i, j) corresponds to the interaction energy between site i and site j in real space.

  property reciprocal_space_energy

    The reciprocal space energy.

  property reciprocal_space_energy_matrix

    The reciprocal space energy matrix. Each matrix element (i, j) corresponds to the interaction energy between site i and site j in reciprocal space.

  property total_energy

    The total energy.

  property total_energy_matrix

    The total energy matrix. Each matrix element (i, j) corresponds to the total interaction energy between site i and site j.

    Note that this does not include the charged-cell energy, which is only important when the simulation cell is not charge balanced.

compute_average_oxidation_state(site)

  Calculates the average oxidation state of a site.

  Parameters:

    site – Site to compute average oxidation state

  Returns:

    Average oxidation state of site.

## pymatgen.core.graphs module

Module for graph representations of crystals and molecules.

class ConnectedSite(site: PeriodicSite, jimage: tuple[int, int, int], index: Any, weight: float, dist: float)

  Bases: `NamedTuple`

  A connected site with its periodic image information.

  Parameters:

    - site – The periodic site.

    - jimage – The periodic image tuple.

    - index – The site index.

    - weight – The connection weight.

    - dist – The distance.

  Create new instance of ConnectedSite(site, jimage, index, weight, dist)

  dist: float

    Alias for field number 4

  index: Any

    Alias for field number 2

  jimage: tuple[int, int, int]

    Alias for field number 1

  site: PeriodicSite

    Alias for field number 0

  weight: float

    Alias for field number 3

exception MolGraphSplitError

  Bases: `Exception`

  Raised when a molecule graph is failed to split into two disconnected subgraphs.

class MoleculeGraph(molecule, graph_data=None)

  Bases: `MSONable`

  This is a class for annotating a Molecule with bond information, stored in the form of a graph. A “bond” does not necessarily have to be a chemical bond, but can store any kind of information that connects two Sites.

  If constructing this class manually, use the from_empty_graph method or from_local_env_strategy method (using an algorithm provided by the local_env module, such as O’Keeffe).

  This class that contains connection information: relationships between sites represented by a Graph structure, and an associated structure object.

  This class uses the NetworkX package to store and operate on the graph itself, but contains a lot of helper methods to make associating a graph with a given molecule easier.

  Use cases for this include storing bonding information, NMR J-couplings, Heisenberg exchange parameters, etc.

  Parameters:

    - molecule – Molecule object

    - graph_data – dict containing graph information in dict format (not intended to be constructed manually, see as_dict method for format)

  add_edge(from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None)

    Add edge to graph.

    Since physically a ‘bond’ (or other connection between sites) doesn’t have a direction, from_index, from_jimage can be swapped with to_index, to_jimage.

    However, images will always be shifted so that from_index < to_index and from_jimage becomes (0, 0, 0).

    Parameters:

      - from_index – index of site connecting from

      - to_index – index of site connecting to

      - weight (float) – e.g. bond length

      - warn_duplicates (bool) – if True, will warn if trying to add duplicate edges (duplicate edges will not be added in either case)

      - edge_properties (dict) – any other information to store on graph edges, similar to Structure’s site_properties

  alter_edge(from_index, to_index, new_weight=None, new_edge_properties=None)

    Alters either the weight or the edge_properties of an edge in the MoleculeGraph.

    Parameters:

      - from_index – int

      - to_index – int

      - new_weight – alter_edge does not require that weight be altered. As such, by default, this is None. If weight is to be changed, it should be a float.

      - new_edge_properties – alter_edge does not require that edge_properties be altered. As such, by default, this is None. If any edge properties are to be changed, it should be a dictionary of edge properties to be changed.

  as_dict()

    As in pymatgen.core.Molecule except with using to_dict_of_dicts from NetworkX to store graph information.

  break_edge(from_index, to_index, allow_reverse=False)

    Remove an edge from the MoleculeGraph.

    Parameters:

      - from_index – int

      - to_index – int

      - allow_reverse – If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing that, will attempt to break (to_index, from_index).

  build_unique_fragments()

    Find all possible fragment combinations of the MoleculeGraphs (in other words, all connected induced subgraphs).

  diff(other, strict=True)

    Compares two MoleculeGraphs. Returns dict with keys ‘self’, ‘other’, ‘both’ with edges that are present in only one MoleculeGraph (‘self’ and ‘other’), and edges that are present in both.

    The Jaccard distance is a simple measure of the dissimilarity between two MoleculeGraphs (ignoring edge weights), and is defined by 1 - (size of the intersection / size of the union) of the sets of edges. This is returned with key ‘dist’.

    Important note: all node indices are in terms of the MoleculeGraph this method is called from, not the ‘other’ MoleculeGraph: there is no guarantee the node indices will be the same if the underlying Molecules are ordered differently.

    Parameters:

      - other – MoleculeGraph

      - strict – if False, will compare bonds from different Molecules, with node indices replaced by Species strings, will not count number of occurrences of bonds

  draw_graph_to_file(filename='graph', diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False, image_labels=False, color_scheme='VESTA', keep_dot=False, algo='fdp')

    Draws graph using GraphViz.

    The networkx graph object itself can also be drawn with networkx’s in-built graph drawing methods, but note that this might give misleading results for multigraphs (edges are super-imposed on each other).

    If visualization is difficult to interpret, hide_image_edges can help, especially in larger graphs.

    Parameters:

      - filename – filename to output, will detect filetype from extension (any graphviz filetype supported, such as pdf or png)

      - diff (StructureGraph) – an additional graph to compare with, will color edges red that do not exist in diff and edges green that are in diff graph but not in the reference graph

      - hide_unconnected_nodes – if True, hide unconnected nodes

      - hide_image_edges – if True, do not draw edges that go through periodic boundaries

      - edge_colors (bool) – if True, use node colors to color edges

      - node_labels (bool) – if True, label nodes with species and site index

      - weight_labels (bool) – if True, label edges with weights

      - image_labels (bool) – if True, label edges with their periodic images (usually only used for debugging, edges to periodic images always appear as dashed lines)

      - color_scheme (str) – “VESTA” or “JMOL”

      - keep_dot (bool) – keep GraphViz .dot file for later visualization

      - algo – any graphviz algo, “neato” (for simple graphs) or “fdp” (for more crowded graphs) usually give good outputs

  property edge_weight_name

    Name of the edge weight property of graph.

  property edge_weight_unit

    Units of the edge weight property of graph.

  find_rings(including=None) → list[list[tuple[int, int]]]

    Find ring structures in the MoleculeGraph.

    Parameters:

      - including (list[int]) – list of site indices. If including is not None, then find_rings

      - default (will only return those rings including the specified sites. By)

      - parameter (this)

      - None (is)

      - returned. (and all rings will be)

    Returns:

      Each entry will be a ring (cycle, in graph theory terms)

        including the index found in the Molecule. If there is no cycle including an index, the value will be an empty list.

    Return type:

      list[list[tuple[int, int]]]

  classmethod from_dict(dct: dict) → Self

    As in pymatgen.core.Molecule except restoring graphs using from_dict_of_dicts from NetworkX to restore graph information.

  classmethod from_edges(molecule: Molecule, edges: dict[tuple[int, int], None | dict]) → Self

    Constructor for MoleculeGraph, using pre-existing or pre-defined edges with optional edge parameters.

    Parameters:

      - molecule – Molecule object

      - edges – dict representing the bonds of the functional group (format: {(u, v): props}, where props is a dictionary of properties, including weight. Props should be None if no additional properties are to be specified.

    Returns:

      A MoleculeGraph

  classmethod from_empty_graph(molecule, name='bonds', edge_weight_name=None, edge_weight_units=None) → Self

    Constructor for MoleculeGraph, returns a MoleculeGraph object with an empty graph (no edges, only nodes defined that correspond to Sites in Molecule).

    Parameters:

      - molecule (Molecule) – Molecule to create graph from.

      - name (str) – name of graph, e.g. “bonds”

      - edge_weight_name (str) – name of edge weights, e.g. “bond_length” or “exchange_constant”

      - edge_weight_units (str) – name of edge weight units

      - "eV" (e.g. "Å" or)

    Returns:

      MoleculeGraph

  classmethod from_local_env_strategy(molecule, strategy) → Self

    Constructor for MoleculeGraph, using a strategy from pymatgen.core.local_env.

    > molecule: Molecule object strategy: an instance of a

    > > pymatgen.core.local_env.NearNeighbors object

    Returns:

      mg, a MoleculeGraph

  get_connected_sites(n)

    Get a named tuple of neighbors of site n: periodic_site, jimage, index, weight. Index is the index of the corresponding site in the original structure, weight can be None if not defined.

    Parameters:

      - n – index of Site in Molecule

      - jimage – lattice vector of site.

    Returns:

      list of ConnectedSite tuples, sorted by closest first.

  get_coordination_of_site(n) → int

    Get the number of neighbors of site n. In graph terms, simply returns degree of node corresponding to site n.

    Parameters:

      n – index of site

    Returns:

      the number of neighbors of site n.

    Return type:

      int

  get_disconnected_fragments(return_index_map: bool = False)

    Determine if the MoleculeGraph is connected. If it is not, separate the MoleculeGraph into different MoleculeGraphs, where each resulting MoleculeGraph is a disconnected subgraph of the original. Currently, this function naively assigns the charge of the total molecule to a single submolecule. A later effort will be to actually accurately assign charge.

    Parameters:

      return_index_map (bool) – If True, return a dictionary that maps the new indices to the original indices. Defaults to False.

    NOTE: This function does not modify the original MoleculeGraph. It creates a copy, modifies that, and returns two or more new MoleculeGraph objects.

    Returns:

      Each MoleculeGraph is a disconnected subgraph of the original MoleculeGraph.

    Return type:

      list[MoleculeGraph]

  insert_node(idx, species, coords, validate_proximity=False, site_properties=None, edges=None)

    A wrapper around Molecule.insert(), which also incorporates the new site into the MoleculeGraph.

    Parameters:

      - idx – Index at which to insert the new site

      - species – Species for the new site

      - coords – 3x1 array representing coordinates of the new site

      - validate_proximity – For Molecule.insert(); if True (default False), distance will be checked to ensure that site can be safely added.

      - site_properties – Site properties for Molecule

      - edges – List of dicts representing edges to be added to the MoleculeGraph. These edges must include the index of the new site i, and all indices used for these edges should reflect the MoleculeGraph AFTER the insertion, NOT before. Each dict should at least have a “to_index” and “from_index” key, and can also have a “weight” and a “properties” key.

  isomorphic_to(other: MoleculeGraph) → bool

    Checks if the graphs of two MoleculeGraphs are isomorphic to one another. In order to prevent problems with misdirected edges, both graphs are converted into undirected nx.Graph objects.

    Parameters:

      other – MoleculeGraph object to be compared.

    Returns:

      bool

  property name

    Name of graph.

  remove_nodes(indices: list[int]) → None

    A wrapper for Molecule.remove_sites().

    Parameters:

      indices – indices in the current Molecule (and graph) to be removed.

  replace_group(index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None)

    Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group in self.molecule with a functional group. This method also amends self.graph to incorporate the new functional group.

    TODO: Figure out how to replace into a ring structure.

    Parameters:

      - index – Index of atom to substitute.

      - func_grp – Substituent molecule. There are three 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_grp 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. 3. A MoleculeGraph object.

      - strategy – Class from pymatgen.core.local_env.

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

      - graph_dict – Dictionary representing the bonds of the functional group (format: {(u, v): props}, where props is a dictionary of properties, including weight. If None, then the algorithm will attempt to automatically determine bonds using one of a list of strategies defined in pymatgen.core.local_env.

      - strategy_params – dictionary of keyword arguments for strategy. If None, default parameters will be used.

  set_node_attributes()

    Replicates molecule site properties (specie, coords, etc.) in the MoleculeGraph.

  sort(key: Callable[[Molecule], float] | None = None, reverse: bool = False) → None

    Same as Molecule.sort(). Also remaps nodes in graph.

    Parameters:

      - key (callable, optional) – Sort key. Defaults to None.

      - reverse (bool, optional) – Reverse sort order. Defaults to False.

  split_molecule_subgraphs(bonds, allow_reverse=False, alterations=None)

    Split MoleculeGraph into two or more MoleculeGraphs by breaking a set of bonds. This function uses MoleculeGraph.break_edge repeatedly to create disjoint graphs (two or more separate molecules). This function does not only alter the graph information, but also changes the underlying Molecules. If the bonds parameter does not include sufficient bonds to separate two molecule fragments, then this function will fail. Currently, this function naively assigns the charge of the total molecule to a single submolecule. A later effort will be to actually accurately assign charge. NOTE: This function does not modify the original MoleculeGraph. It creates a copy, modifies that, and returns two or more new MoleculeGraph objects.

    Parameters:

      - bonds – list of tuples (from_index, to_index) representing bonds to be broken to split the MoleculeGraph.

      - alterations – a dict {(from_index, to_index): alt}, where alt is a dictionary including weight and/or edge properties to be changed following the split.

      - allow_reverse – If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing that, will attempt to break (to_index, from_index).

    Returns:

      list of MoleculeGraphs.

  substitute_group(index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None)

    Builds off of Molecule.substitute to replace an atom in self.molecule with a functional group. This method also amends self.graph to incorporate the new functional group.

    NOTE: using a MoleculeGraph will generally produce a different graph compared with using a Molecule or str (when not using graph_dict).

    Parameters:

      - index – Index of atom to substitute.

      - func_grp –

        Substituent molecule. There are three 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_grp 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.

        3. A MoleculeGraph object.

      - strategy – Class from pymatgen.core.local_env.

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

      - graph_dict – Dictionary representing the bonds of the functional group (format: {(u, v): props}, where props is a dictionary of properties, including weight. If None, then the algorithm will attempt to automatically determine bonds using one of a list of strategies defined in pymatgen.core.local_env.

      - strategy_params – dictionary of keyword arguments for strategy. If None, default parameters will be used.

  classmethod with_edges(*args, **kwargs)

    Deprecated method. Use from_edges instead.

  classmethod with_empty_graph(*args, **kwargs)

    Deprecated method. Use from_empty_graph instead.

  classmethod with_local_env_strategy(*args, **kwargs)

    Deprecated method. Use from_local_env_strategy instead.

class StructureGraph(structure: Structure, graph_data: dict | None = None)

  Bases: `MSONable`

  This is a class for annotating a Structure with bond information, stored in the form of a graph. A “bond” does not necessarily have to be a chemical bond, but can store any kind of information that connects two Sites.

  If constructing this class manually, use the from_empty_graph method or from_local_env_strategy method (using an algorithm provided by the local_env module, such as O’Keeffe). This class that contains connection information: relationships between sites represented by a Graph structure, and an associated structure object.

  StructureGraph uses the NetworkX package to store and operate on the graph itself, but contains a lot of helper methods to make associating a graph with a given crystallographic structure easier. Use cases for this include storing bonding information, NMR J-couplings, Heisenberg exchange parameters, etc. For periodic graphs, class stores information on the graph edges of what lattice image the edge belongs to.

  Parameters:

    - structure (Structure) – Structure object to be analyzed.

    - graph_data (dict) – Dictionary containing graph information. Not intended to be constructed manually see as_dict method for format.

  add_edge(from_index: int, to_index: int, from_jimage: tuple[int, int, int] = (0, 0, 0), to_jimage: tuple[int, int, int] | None = None, weight: float | None = None, warn_duplicates: bool = True, edge_properties: dict | None = None) → None

    Add edge to graph.

    Since physically a ‘bond’ (or other connection between sites) doesn’t have a direction, from_index, from_jimage can be swapped with to_index, to_jimage.

    However, images will always be shifted so that from_index < to_index and from_jimage becomes (0, 0, 0).

    Parameters:

      - from_index – index of site connecting from

      - to_index – index of site connecting to

      - from_jimage (tuple of ints) – lattice vector of periodic image, e.g. (1, 0, 0) for periodic image in +x direction

      - to_jimage (tuple of ints) – lattice vector of image

      - weight (float) – e.g. bond length

      - warn_duplicates (bool) – if True, will warn if trying to add duplicate edges (duplicate edges will not be added in either case)

      - edge_properties (dict) – any other information to store on graph edges, similar to Structure’s site_properties

  alter_edge(from_index: int, to_index: int, to_jimage: tuple | None = None, new_weight: float | None = None, new_edge_properties: dict | None = None)

    Alters either the weight or the edge_properties of an edge in the StructureGraph.

    Parameters:

      - from_index – int

      - to_index – int

      - to_jimage – tuple

      - new_weight – alter_edge does not require that weight be altered. As such, by default, this is None. If weight is to be changed, it should be a float.

      - new_edge_properties – alter_edge does not require that edge_properties be altered. As such, by default, this is None. If any edge properties are to be changed, it should be a dictionary of edge properties to be changed.

  as_dict() → dict

    As in pymatgen.core.Structure except with using to_dict_of_dicts from NetworkX to store graph information.

  break_edge(from_index: int, to_index: int, to_jimage: tuple | None = None, allow_reverse: bool = False) → None

    Remove an edge from the StructureGraph. If no image is given, this method will fail.

    Parameters:

      - from_index – int

      - to_index – int

      - to_jimage – tuple

      - allow_reverse – If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing that, will attempt to break (to_index, from_index).

  diff(other: StructureGraph, strict: bool = True) → dict

    Compares two StructureGraphs. Returns dict with keys ‘self’, ‘other’, ‘both’ with edges that are present in only one StructureGraph (‘self’ and ‘other’), and edges that are present in both.

    The Jaccard distance is a simple measure of the dissimilarity between two StructureGraphs (ignoring edge weights), and is defined by 1 - (size of the intersection / size of the union) of the sets of edges. This is returned with key ‘dist’.

    Important note: all node indices are in terms of the StructureGraph this method is called from, not the ‘other’ StructureGraph: there is no guarantee the node indices will be the same if the underlying Structures are ordered differently.

    Parameters:

      - other – StructureGraph

      - strict – if False, will compare bonds from different Structures, with node indices replaced by Species strings, will not count number of occurrences of bonds

  draw_graph_to_file(filename: str = 'graph', diff: StructureGraph = None, hide_unconnected_nodes: bool = False, hide_image_edges: bool = True, edge_colors: bool = False, node_labels: bool = False, weight_labels: bool = False, image_labels: bool = False, color_scheme: str = 'VESTA', keep_dot: bool = False, algo: str = 'fdp')

    Draws graph using GraphViz.

    The networkx graph object itself can also be drawn with networkx’s in-built graph drawing methods, but note that this might give misleading results for multigraphs (edges are super-imposed on each other).

    If visualization is difficult to interpret, hide_image_edges can help, especially in larger graphs.

    Parameters:

      - filename – filename to output, will detect filetype from extension (any graphviz filetype supported, such as pdf or png)

      - diff (StructureGraph) – an additional graph to compare with, will color edges red that do not exist in diff and edges green that are in diff graph but not in the reference graph

      - hide_unconnected_nodes – if True, hide unconnected nodes

      - hide_image_edges – if True, do not draw edges that go through periodic boundaries

      - edge_colors (bool) – if True, use node colors to color edges

      - node_labels (bool) – if True, label nodes with species and site index

      - weight_labels (bool) – if True, label edges with weights

      - image_labels (bool) – if True, label edges with their periodic images (usually only used for debugging, edges to periodic images always appear as dashed lines)

      - color_scheme (str) – “VESTA” or “JMOL”

      - keep_dot (bool) – keep GraphViz .dot file for later visualization

      - algo – any graphviz algo, “neato” (for simple graphs) or “fdp” (for more crowded graphs) usually give good outputs

  property edge_weight_name: str

    Name of the edge weight property of graph.

  property edge_weight_unit

    Units of the edge weight property of graph.

  classmethod from_dict(dct: dict) → Self

    As in pymatgen.core.Structure except restoring graphs using from_dict_of_dicts from NetworkX to restore graph information.

  classmethod from_edges(structure: Structure, edges: dict) → Self

    Constructor for MoleculeGraph, using pre-existing or pre-defined edges with optional edge parameters.

    Parameters:

      - structure – Structure object

      - edges – dict representing the bonds of the functional group (format: {(from_index, to_index, from_image, to_image): props}, where props is a dictionary of properties, including weight. Props should be None if no additional properties are to be specified.

    Returns:

      sg, a StructureGraph

  classmethod from_empty_graph(structure: Structure, name: str = 'bonds', edge_weight_name: str | None = None, edge_weight_units: str | None = None) → Self

    Constructor for an empty StructureGraph, i.e. no edges, containing only nodes corresponding to sites in Structure.

    Parameters:

      - structure – A pymatgen Structure object.

      - name – Name of the graph, e.g. “bonds”.

      - edge_weight_name – Name of the edge weights, e.g. “bond_length” or “exchange_constant”.

      - edge_weight_units – Name of the edge weight units, e.g. “Å” or “eV”.

    Returns:

      an empty graph with no edges, only nodes defined

        that correspond to sites in Structure.

    Return type:

      StructureGraph

  classmethod from_local_env_strategy(structure: Structure, strategy: NearNeighbors, weights: bool = False, edge_properties: bool = False) → Self

    Constructor for StructureGraph, using a strategy from pymatgen.core.local_env.

    Parameters:

      - structure – Structure object

      - strategy – an instance of a pymatgen.core.local_env.NearNeighbors object

      - weights (bool) – if True, use weights from local_env class (consult relevant class for their meaning)

      - edge_properties (bool) – if True, edge_properties from neighbors will be used

  get_connected_sites(n: int, jimage: tuple[int, int, int] = (0, 0, 0)) → list[ConnectedSite]

    Get a named tuple of neighbors of site n: periodic_site, jimage, index, weight. Index is the index of the corresponding site in the original structure, weight can be None if not defined.

    Parameters:

      - n – index of Site in Structure

      - jimage – lattice vector of site

    Returns:

      list of ConnectedSite tuples, sorted by closest first.

  get_coordination_of_site(n: int) → int

    Get the number of neighbors of site n. In graph terms, simply returns degree of node corresponding to site n.

    Parameters:

      n – index of site

    Returns:

      number of neighbors of site n.

    Return type:

      int

  get_subgraphs_as_molecules(use_weights: bool = False) → list[Molecule]

    Retrieve subgraphs as molecules, useful for extracting molecules from periodic crystals.

    Will only return unique molecules, not any duplicates present in the crystal (a duplicate defined as an isomorphic subgraph).

    Parameters:

      use_weights (bool) – If True, only treat subgraphs as isomorphic if edges have the same weights. Typically, this means molecules will need to have the same bond lengths to be defined as duplicates, otherwise bond lengths can differ. This is a fairly robust approach, but will treat e.g. enantiomers as being duplicates.

    Returns:

      list of unique Molecules in Structure

  insert_node(idx: int, species: Species, coords: ArrayLike, coords_are_cartesian: bool = False, validate_proximity: bool = False, site_properties: dict | None = None, edges: list | dict | None = None) → None

    A wrapper around Molecule.insert(), which also incorporates the new site into the MoleculeGraph.

    Parameters:

      - idx – Index at which to insert the new site

      - species – Species for the new site

      - coords – 3x1 array representing coordinates of the new site

      - coords_are_cartesian – Whether coordinates are cartesian. Defaults to False.

      - validate_proximity – For Molecule.insert(); if True (default False), distance will be checked to ensure that site can be safely added.

      - site_properties – Site properties for Molecule

      - edges – List of dicts representing edges to be added to the

      - i (MoleculeGraph. These edges must include the index of the new site)

    :param : :param and all indices used for these edges should reflect the: :param MoleculeGraph AFTER the insertion: :param NOT before. Each dict should at: :param least have a “to_index” and “from_index” key: :param and can also have a: :param “weight” and a “properties” key.:

  property name: str

    Name of graph.

  remove_nodes(indices: Sequence[int | None]) → None

    A wrapper for Molecule.remove_sites().

    Parameters:

      indices – list of indices in the current Molecule (and graph) to be removed.

  set_node_attributes() → None

    Get each node a “specie” and a “coords” attribute, updated with the current species and coordinates.

  sort(key=None, reverse: bool = False) → None

    Same as Structure.sort(). Also remaps nodes in graph.

    Parameters:

      - key – key to sort by

      - reverse – reverse sort order

  substitute_group(index: int, func_grp: Molecule | str, strategy: Any, bond_order: int = 1, graph_dict: dict | None = None, strategy_params: dict | None = None)

    Builds off of Structure.substitute to replace an atom in self.structure with a functional group. This method also amends self.graph to incorporate the new functional group.

    NOTE: Care must be taken to ensure that the functional group that is substituted will not place atoms to close to each other, or violate the dimensions of the Lattice.

    Parameters:

      - index – Index of atom to substitute.

      - func_grp –

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

      - strategy – Class from pymatgen.core.local_env.

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

      - graph_dict – Dictionary representing the bonds of the functional group (format: {(u, v): props}, where props is a dictionary of properties, including weight. If None, then the algorithm will attempt to automatically determine bonds using one of a list of strategies defined in pymatgen.core.local_env.

      - strategy_params – dictionary of keyword arguments for strategy. If None, default parameters will be used.

  property types_and_weights_of_connections: dict

    Extract a dictionary summarizing the types and weights of edges in the graph.

    Returns:

      A dictionary with keys specifying the species involved in a connection in alphabetical order (e.g. string ‘Fe-O’) and values which are a list of weights for those connections (e.g. bond lengths).

  types_of_coordination_environments(anonymous: bool = False) → list[str]

    Extract information on the different co-ordination environments present in the graph.

    Parameters:

      anonymous – if anonymous, will replace specie names with A, B, C, etc.

    Returns:

      List of coordination environments, e.g. {‘Mo-S(6)’, ‘S-Mo(3)’}

  property weight_statistics: dict

    Extract a statistical summary of edge weights present in the graph.

    Returns:

      A dict with an ‘all_weights’ list, ‘minimum’, ‘maximum’, ‘median’, ‘mean’, ‘std_dev’

  classmethod with_edges(*args, **kwargs)

    Deprecated method. Use from_edges instead.

  classmethod with_empty_graph(*args, **kwargs)

    Deprecated method. Use from_empty_graph instead.

  classmethod with_local_env_strategy(*args, **kwargs)

    Deprecated method. Use from_local_env_strategy instead.

## 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[NDArray] | NDArray, rotation_axis: tuple[int, ...], rotation_angle: float, gb_plane: tuple[int, int, int], join_plane: tuple[int, int, int], 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[PeriodicSite]

    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: tuple[int, int, int], c2_b2_a2_ratio: tuple[float, float, float]) → 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: tuple[int, int, int] | tuple[int, int, int, int], angle: float, normal: bool = False, trans_cry: NDArray | None = None, lat_type: str = 'c', ratio: list[int] | None = None, surface: tuple[int, int, int] | tuple[int, int, int, int] | 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: tuple[int, int, int], normal: bool, trans_cry: NDArray, max_search: int = 20, quick_gen: bool = False) → NDArray

    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: tuple[float, float, float]) → tuple[int, ...]

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

    Parameters:

      vec (tuple[float, float, float]) – 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[PeriodicSite]

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

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

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

      dict with element symbol and reduced amount e.g.

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

  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[str, float]) → 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[str, float]

    Deprecated.

## 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: tuple[bool, bool, bool] = (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: tuple[float, float, float]

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

  property alpha: float

    Angle alpha of lattice in degrees.

  property angles: tuple[float, float, float]

    Lattice angles.

    Returns:

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

  as_dict(verbosity: Literal[0, 1] = 0) → dict

    MSONable dict representation of the Lattice.

    Parameters:

      verbosity (0 | 1) – 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: tuple[bool, bool, bool] = (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: tuple[int, ...]) → float

    Get the distance between the hkl plane and the origin.

    Parameters:

      miller_index (tuple[int, ...]) – 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) → NDArray[np.float64]

    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[Self, NDArray[np.float64] | None, NDArray[np.int64]]]

    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, NDArray[np.float64] | None, NDArray[np.int64]] | 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, NDArray[np.float_], NDArray[np.float_]]

  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: tuple[bool, bool, bool] = (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) → NDArray[np.float64]

    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[np.float64]]]

    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) → NDArray[np.float64]

    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, NDArray[np.int_]]

    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, NDArray[np.int_]]

  get_frac_coords_from_lll(lll_frac_coords: ArrayLike) → NDArray[np.float64]

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

  get_fractional_coords(cart_coords: ArrayLike) → NDArray[np.float64]

    Get the fractional coordinates given Cartesian coordinates.

    Parameters:

      cart_coords (3x1 array) – Cartesian coords.

    Returns:

      Fractional coordinates.

  get_lll_frac_coords(frac_coords: ArrayLike) → NDArray[np.float64]

    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) → tuple[int, int, int]

    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 minimizes 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[NDArray, float, int, NDArray]] | tuple[NDArray] | 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_points_in_sphere_old(frac_points: ArrayLike, center: ArrayLike, r: float, zip_results=True) → list[tuple[NDArray[np.float64], float, int, NDArray[np.float64]]] | tuple[list[NDArray[np.float64]], list[float], list[int], list[NDArray[np.float64]]]

    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[NDArray[np.float64], float, int, NDArray[np.float64]]] | list[NDArray[np.float64]]

    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) → NDArray[np.float64]

    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[np.float64]]]

    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: tuple[bool, bool, bool] = (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[np.float64]

    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: tuple[float, float, float]

    Lattice lengths.

    Returns:

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

  property lll_inverse: NDArray[np.float64]

    Inverse of self.lll_mapping.

  property lll_mapping: NDArray[np.float64]

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

  property lll_matrix: NDArray[np.float64]

    The matrix for LLL reduction.

  property matrix: NDArray[np.float64]

    Copy of matrix representing the Lattice.

  property metric_tensor: NDArray[np.float64]

    The metric tensor of the lattice.

  classmethod monoclinic(a: float, b: float, c: float, beta: float, pbc: tuple[bool, bool, bool] = (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) → NDArray[np.float64]

    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: tuple[bool, bool, bool] = (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: tuple[bool, bool, bool]

    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: tuple[bool, bool, bool] = (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[np.float64]

    The (1,6) array of Selling Scalars.

  classmethod tetragonal(a: float, c: float, pbc: tuple[bool, bool, bool] = (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[np.int_], nx: int, ny: int, nz: int) → list[NDArray[np.int_]]

  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: tuple[int, ...], round_dp: int = 4, verbose: bool = True) → tuple[int, ...]

  Attempt to convert a vector of floats to whole numbers.

  Parameters:

    - miller_index (tuple[int, ...]) – 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:

    tuple[int, …]

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

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

  Parameters:

    - all_coords – (list of Cartesian coordinates) all available points

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

    - r – (float) cutoff radius

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

    - numerical_tol – (float) numerical tolerance

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

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

  Returns:

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

## pymatgen.core.libxcfunc module

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

class LibxcFunc(value)

  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.local_env module

This module provides classes to perform analyses of the local environments (e.g., finding near neighbors) of single sites in molecules and structures.

class BrunnerNNReal(tol: float = 0.0001, cutoff=8.0)

  Bases: `NearNeighbors`

  Determine coordination number using Brunner’s algorithm which counts the atoms that are within the largest gap in differences in real space interatomic distances. This algorithm uses Brunner’s method of largest gap in interatomic distances.

  Parameters:

    - tol (float) – tolerance parameter for bond determination (default: 1E-4).

    - cutoff (float) – cutoff radius in Angstrom to look for near-neighbor atoms. Defaults to 8.0.

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near-neighbor sites.

    Returns:

      tuples, each one

        of which represents a coordinated site, its image location, and its weight.

    Return type:

      siw (list of tuples (Site, array, float))

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class BrunnerNNReciprocal(tol: float = 0.0001, cutoff=8.0)

  Bases: `NearNeighbors`

  Determine coordination number using Brunner’s algorithm which counts the atoms that are within the largest gap in differences in real space interatomic distances. This algorithm uses Brunner’s method of largest reciprocal gap in interatomic distances.

  Parameters:

    - tol (float) – tolerance parameter for bond determination (default: 1E-4).

    - cutoff (float) – cutoff radius in Angstrom to look for near-neighbor atoms. Defaults to 8.0.

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near-neighbor sites.

    Returns:

      tuples, each one of which represents a

        coordinated site, its image location, and its weight.

    Return type:

      list[tuples[Site, array, float]]

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class BrunnerNNRelative(tol: float = 0.0001, cutoff=8.0)

  Bases: `NearNeighbors`

  Determine coordination number using Brunner’s algorithm which counts the atoms that are within the largest gap in differences in real space interatomic distances. This algorithm uses Brunner’s method of of largest relative gap in interatomic distances.

  Parameters:

    - tol (float) – tolerance parameter for bond determination (default: 1E-4).

    - cutoff (float) – cutoff radius in Angstrom to look for near-neighbor atoms. Defaults to 8.0.

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near-neighbor sites.

    Returns:

      tuples, each one

        of which represents a coordinated site, its image location, and its weight.

    Return type:

      siw (list of tuples (Site, array, float))

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class BrunnerNN_real(tol: float = 0.0001, cutoff=8.0)

  Bases: `BrunnerNNReal`

  Deprecated alias for BrunnerNNReal.

  Parameters:

    - tol (float) – tolerance parameter for bond determination (default: 1E-4).

    - cutoff (float) – cutoff radius in Angstrom to look for near-neighbor atoms. Defaults to 8.0.

class BrunnerNN_reciprocal(tol: float = 0.0001, cutoff=8.0)

  Bases: `BrunnerNNReciprocal`

  Deprecated alias for BrunnerNNReciprocal.

  Parameters:

    - tol (float) – tolerance parameter for bond determination (default: 1E-4).

    - cutoff (float) – cutoff radius in Angstrom to look for near-neighbor atoms. Defaults to 8.0.

class BrunnerNN_relative(tol: float = 0.0001, cutoff=8.0)

  Bases: `BrunnerNNRelative`

  Deprecated alias for BrunnerNNRelative.

  Parameters:

    - tol (float) – tolerance parameter for bond determination (default: 1E-4).

    - cutoff (float) – cutoff radius in Angstrom to look for near-neighbor atoms. Defaults to 8.0.

class CovalentBondNN(tol: float = 0.2, order=True)

  Bases: `NearNeighbors`

  Determine near-neighbor sites and bond orders using built-in pymatgen.Molecule CovalentBond functionality.

  NOTE: This strategy is only appropriate for molecules, and not for structures.

  Parameters:

    - tol (float) – Tolerance for covalent bond checking.

    - order (bool) – If True (default), this class will compute bond orders. If False, bond lengths will be computed.

  property extend_structure_molecules: bool

    Do Molecules need to be converted to Structures to use this NearNeighbors class? Note: this property is not defined for classes for which molecules_allowed is False.

    Type:

      Boolean property

  get_bonded_structure(structure: Structure, decorate: bool = False) → MoleculeGraph

    Obtain a MoleculeGraph object using this NearNeighbor class.

    Parameters:

      - structure – Molecule object.

      - decorate (bool) – whether to annotate site properties

      - by (with order parameters using neighbors determined)

      - class (this NearNeighbor)

    Returns:

      object from pymatgen.core.graphs

    Return type:

      MoleculeGraph

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites and weights (orders) of bonds for a given atom.

    Parameters:

      - structure – input Molecule.

      - n – index of site for which to determine near neighbors.

    Returns:

      [dict] representing a neighboring site and the type of bond present between site n and the neighboring site.

  get_nn_shell_info(structure: Structure, site_idx, shell)

    Get a certain nearest neighbor shell for a certain site.

    Determines all non-backtracking paths through the neighbor network computed by get_nn_info. The weight is determined by multiplying the weight of the neighbor at each hop through the network. For example, a 2nd-nearest-neighbor that has a weight of 1 from its 1st-nearest-neighbor and weight 0.5 from the original site will be assigned a weight of 0.5.

    As this calculation may involve computing the nearest neighbors of atoms multiple times, the calculation starts by computing all of the neighbor info and then calling _get_nn_shell_info. If you are likely to call this method for more than one site, consider calling get_all_nn first and then calling this protected method yourself.

    Parameters:

      - structure (Molecule) – Input structure

      - site_idx (int) – index of site for which to determine neighbor information.

      - shell (int) – Which neighbor shell to retrieve (1 == 1st NN shell)

    Returns:

      list of dictionaries. Each entry in the list is information about

        a certain neighbor in the structure, in the same format as get_nn_info.

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class Critic2NN

  Bases: `NearNeighbors`

  Performs a topological analysis using critic2 to obtain neighbor information, using a sum of atomic charge densities. If an actual charge density is available (e.g. from a VASP CHGCAR), see Critic2Caller directly instead.

  Init for Critic2NN.

  property extend_structure_molecules: bool

    Do Molecules need to be converted to Structures to use this NearNeighbors class? Note: this property is not defined for classes for which molecules_allowed is False.

    Type:

      Boolean property

  get_bonded_structure(structure: Structure, decorate: bool = False) → StructureGraph
    Parameters:

      - structure (Structure) – Input structure

      - decorate (bool, optional) – Whether to decorate the structure. Defaults to False.

    Returns:

      Bonded structure

    Return type:

      StructureGraph

  get_nn_info(structure: Structure, n: int) → list[dict]

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near-neighbor sites.

    Returns:

      tuples, each one

        of which represents a coordinated site, its image location, and its weight.

    Return type:

      siw (list of tuples (Site, array, float))

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class CrystalNN(weighted_cn=False, cation_anion=False, distance_cutoffs=(0.5, 1), x_diff_weight=3.0, porous_adjustment=True, search_cutoff=7, fingerprint_length=None)

  Bases: `NearNeighbors`

  This is a custom near-neighbor method intended for use in all kinds of periodic structures (metals, minerals, porous structures, etc). It is based on a Voronoi algorithm and uses the solid angle weights to determine the probability of various coordination environments. The algorithm can also modify probability using smooth distance cutoffs as well as Pauling electronegativity differences. The output can either be the most probable coordination environment or a weighted list of coordination environments. Please note that the default weights have been benchmarked for inorganic crystal structures. For MOFs or molecular crystals, weights and cutoffs likely will need to be adapted. A starting point could be: CrystalNN(x_diff_weight = 1.5, search_cutoff = 4.5).

  Initialize CrystalNN with desired parameters. Default parameters assume “chemical bond” type behavior is desired. For geometric neighbor finding (e.g., structural framework), set (i) distance_cutoffs=None, (ii) x_diff_weight=0 and (optionally) (iii) porous_adjustment=False which will disregard the atomic identities and perform best for a purely geometric match.

  Parameters:

    - weighted_cn (bool) – if set to True, will return fractional weights for each potential near neighbor.

    - cation_anion (bool) – if set True, will restrict bonding targets to sites with opposite or zero charge. Requires an oxidation states on all sites in the structure.

    - distance_cutoffs ([float, float]) –

      - if not None, penalizes neighbor

      distances greater than sum of covalent radii plus distance_cutoffs[0]. Distances greater than covalent radii sum plus distance_cutoffs[1] are enforced to have zero weight.

    - x_diff_weight (float) –

      - if multiple types of neighbor elements are

      possible, this sets preferences for targets with higher electronegativity difference.

    - porous_adjustment (bool) –

      - if True, readjusts Voronoi weights to

      better describe layered / porous structures

    - search_cutoff (float) – cutoff in Angstroms for initial neighbor search; this will be adjusted if needed internally

    - fingerprint_length (int) – if a fixed_length CN “fingerprint” is desired from get_nn_data(), set this parameter

  class NNData(all_nninfo: list, cn_weights: dict, cn_nninfo: dict)

    Bases: `NamedTuple`

    Data structure for neighbor information.

    Parameters:

      - all_nninfo – All neighbor information.

      - cn_weights – Coordination number weights.

      - cn_nninfo – Coordination number neighbor information.

    Create new instance of NNData(all_nninfo, cn_weights, cn_nninfo)

    all_nninfo: list

      Alias for field number 0

    cn_nninfo: dict

      Alias for field number 2

    cn_weights: dict

      Alias for field number 1

  get_cn(structure: Structure, n: int, **kwargs) → float

    Get coordination number, CN, of site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine CN.

      - use_weights (bool) – flag indicating whether (True) to use weights for computing the coordination number or not (False, default: each coordinated site has equal weight).

      - on_disorder ('take_majority_strict' | 'take_majority_drop' | 'take_max_species' | 'error') – What to do when encountering a disordered structure. ‘error’ will raise ValueError. ‘take_majority_strict’ will use the majority specie on each site and raise ValueError if no majority exists. ‘take_max_species’ will use the first max specie on each site. For {{Fe: 0.4, O: 0.4, C: 0.2}}, ‘error’ and ‘take_majority_strict’ will raise ValueError, while ‘take_majority_drop’ ignores this site altogether and ‘take_max_species’ will use Fe as the site specie.

      - **kwargs – Additional keyword arguments.

    Returns:

      coordination number.

    Return type:

      float

  get_cn_dict(structure: Structure, n: int, use_weights: bool = False, **kwargs)

    Get coordination number, CN, of each element bonded to site with index n in structure.

    Parameters:

      - structure (Structure) – input structure

      - n (int) – index of site for which to determine CN.

      - use_weights (bool) – flag indicating whether (True) to use weights for computing the coordination number or not (False, default: each coordinated site has equal weight).

      - **kwargs – Additional keyword arguments.

    Returns:

      coordination number and list of coordinated sites

    Return type:

      dict[int, list[dict]]

  get_nn_data(structure: Structure, n: int, length=None)

    The main logic of the method to compute near neighbor.

    Parameters:

      - structure – (Structure) enclosing structure object

      - n – (int) index of target site to get NN info for

      - length – (int) if set, will return a fixed range of CN numbers

    Returns:

      - all near neighbor sites with weights

      - a dict of CN -> weight

      - a dict of CN -> associated near neighbor sites

    Return type:

      a namedtuple (NNData) object that contains

  get_nn_info(structure: Structure, n: int) → list[dict]

    Get all near-neighbor information.

    Parameters:

      - structure – (Structure) pymatgen Structure

      - n – (int) index of target site

    Returns:

      each dictionary provides information

        about a single near neighbor, where key ‘site’ gives access to the corresponding Site object, ‘image’ gives the image location, and ‘weight’ provides the weight that a given near-neighbor site contributes to the coordination number (1 or smaller), ‘site_index’ gives index of the corresponding site in the original structure.

    Return type:

      siw (list[dict])

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

  static transform_to_length(nn_data, length)

    Given NNData, transforms data to the specified fingerprint length.

    Parameters:

      - nn_data – (NNData)

      - length – (int) desired length of NNData.

class CutOffDictNN(cut_off_dict: dict | None = None)

  Bases: `NearNeighbors`

  A basic NN class using a dictionary of fixed cut-off distances. Only pairs of elements listed in the cut-off dictionary are considered during construction of the neighbor lists.

  Omit passing a dictionary for a Null/Empty NN class.

  Parameters:

    - cut_off_dict (dict[str, float]) – a dictionary

    - distances (of cut-off) – 2.0} for

    - { (e.g.) – 2.0} for

    - Angstroms. (a maximum Fe-O bond length of 2)

    - listed (Bonds will only be created between pairs)

    - dictionary. (in the cut-off)

    - decorated (If your structure is oxidation state)

  :param : :param the cut-off distances will have to explicitly include: :param the oxidation state: 2.0}. :type the oxidation state: ‘Fe2+’, ‘O2-’ :param e.g. {: 2.0}. :type e.g. {: ‘Fe2+’, ‘O2-’

  property extend_structure_molecules: bool

    Do Molecules need to be converted to Structures to use this NearNeighbors class? Note: this property is not defined for classes for which molecules_allowed is False.

    Type:

      Boolean property

  classmethod from_preset(preset) → Self

    Initialize a CutOffDictNN according to a preset set of cutoffs.

    Parameters:

      preset (str) – A preset name. The list of supported presets are: - “vesta_2019”: The distance cutoffs used by the VESTA visualisation program.

    Returns:

      A CutOffDictNN using the preset cut-off dictionary.

  get_nn_info(structure: Structure, n: int) → list[dict]

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near-neighbor sites.

    Returns:

      tuples, each one of which

        represents a coordinated site, its image location, and its weight.

    Return type:

      siw (list of tuples (Site, array, float))

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class EconNN(tol: float = 0.2, cutoff: float = 10.0, cation_anion: bool = False, use_fictive_radius: bool = False)

  Bases: `NearNeighbors`

  Determines the average effective coordination number for each cation in a given structure using Hoppe’s algorithm.

  This method follows the procedure outlined in:

  Hoppe, Rudolf. “Effective coordination numbers (ECoN) and mean fictive ionic radii (MEFIR).” Zeitschrift für Kristallographie-Crystalline Materials 150.1-4 (1979): 23-52.

  Parameters:

    - tol – Tolerance parameter for bond determination.

    - cutoff – Cutoff radius in Angstrom to look for near-neighbor atoms.

    - cation_anion – If set to True, will restrict bonding targets to sites with opposite or zero charge. Requires an oxidation states on all sites in the structure.

    - use_fictive_radius – Whether to use the fictive radius in the EcoN calculation. If False, the bond distance will be used.

  property extend_structure_molecules: bool

    Do Molecules need to be converted to Structures to use this NearNeighbors class? Note: this property is not defined for classes for which molecules_allowed is False.

    Type:

      Boolean property

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near-neighbor sites.

    Returns:

      tuples, each one

        of which represents a coordinated site, its image location, and its weight.

    Return type:

      siw (list of tuples (Site, array, float))

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class IsayevNN(tol: float = 0.25, targets: Element | list[Element] | None = None, cutoff: float = 13.0, allow_pathological: bool = False, extra_nn_info: bool = True, compute_adj_neighbors: bool = True)

  Bases: `VoronoiNN`

  Uses the algorithm defined in 10.1038/ncomms15679.

  Sites are considered neighbors if (i) they share a Voronoi facet and (ii) the bond distance is less than the sum of the Cordero covalent radii + 0.25 Å.

  Parameters:

    - tol – Tolerance in Å for bond distances that are considered coordinated.

    - targets – Target element(s).

    - cutoff – Cutoff radius in Angstrom to look for near-neighbor atoms.

    - allow_pathological – Whether to allow infinite vertices in Voronoi coordination.

    - extra_nn_info – Add all polyhedron info to get_nn_info.

    - compute_adj_neighbors – Whether to compute which neighbors are adjacent. Turn off for faster performance.

  get_all_nn_info(structure: Structure) → list[list[dict[str, Any]]]
    Parameters:

      structure (Structure) – input structure.

    Returns:

      List of near neighbor information for each site. See get_nn_info for the format of the data for each site.

  get_nn_info(structure: Structure, n: int) → list[dict[str, Any]]

    Get all near-neighbor site information.

    Gets the associated image locations and weights of the site with index n in structure using Voronoi decomposition and distance cutoff.

    Parameters:

      - structure – Input structure.

      - n – Index of site for which to determine near-neighbor sites.

    Returns:

      List of dicts containing the near-neighbor information. Each dict has the keys:

      - ”site”: The near-neighbor site.

      - ”image”: The periodic image of the near-neighbor site.

      - ”weight”: The face weight of the Voronoi decomposition.

      - ”site_index”: The index of the near-neighbor site in the original structure.

class JmolNN(tol: float = 0.45, min_bond_distance: float = 0.4, el_radius_updates: dict[SpeciesLike, float] | None = None)

  Bases: `NearNeighbors`

  Determine near-neighbor sites and coordination number using an emulation of Jmol’s default autoBond() algorithm. This version of the algorithm does not take into account any information regarding known charge states.

  Parameters:

    - tol (float) – tolerance parameter for bond determination Defaults to 0.56.

    - min_bond_distance (float) – minimum bond distance for consideration Defaults to 0.4.

    - el_radius_updates (dict) – symbol->float to override default atomic radii table values.

  property extend_structure_molecules: bool

    Do Molecules need to be converted to Structures to use this NearNeighbors class? Note: this property is not defined for classes for which molecules_allowed is False.

    Type:

      Boolean property

  get_max_bond_distance(el1_sym, el2_sym)

    Use Jmol algorithm to determine bond length from atomic parameters.

    Parameters:

      - el1_sym (str) – symbol of atom 1

      - el2_sym (str) – symbol of atom 2.

    Returns:

      max bond length

    Return type:

      float

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n using the bond identification algorithm underlying Jmol.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near neighbors.

    Returns:

      tuples, each one

        of which represents a neighbor site, its image location, and its weight.

    Return type:

      siw (list of tuples (Site, array, float))

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class LocalStructOrderParams(types: list[str], parameters: list[dict[str, float] | None] | None = None, cutoff: float = -10.0)

  Bases: `object`

  This class permits the calculation of various types of local structure order parameters.

  Parameters:

    - types (list[str]) –

      the types of order parameters to be calculated. Note that multiple mentions of the same type may occur. Currently available types recognize following environments:

      > ”cn”: simple coordination number—normalized

      >   if desired;

      > ”sgl_bd”: single bonds; “bent”: bent (angular) coordinations

      > > (Zimmermann & Jain, in progress, 2017);

      > ”T”: T-shape coordinations; “see_saw_rect”: see saw-like coordinations; “tet”: tetrahedra

      > > (Zimmermann et al., submitted, 2017);

      > ”oct”: octahedra

      >   (Zimmermann et al., submitted, 2017);

      > ”bcc”: body-centered cubic environments (Peters,

      >   10. Chem. Phys., 131, 244103, 2009);

      > ”tri_plan”: trigonal planar environments; “sq_plan”: square planar environments; “pent_plan”: pentagonal planar environments; “tri_pyr”: trigonal pyramids (coordinated atom is in

      > > the center of the basal plane);

      > ”sq_pyr”: square pyramids; “pent_pyr”: pentagonal pyramids; “hex_pyr”: hexagonal pyramids; “tri_bipyr”: trigonal bipyramids; “sq_bipyr”: square bipyramids; “pent_bipyr”: pentagonal bipyramids; “hex_bipyr”: hexagonal bipyramids; “cuboct”: cuboctahedra; “q2”: motif-unspecific bond orientational order

      > > parameter (BOOP) of weight l=2 (Steinhardt et al., Phys. Rev. B, 28, 784-805, 1983);

      > ”q4”: BOOP of weight l=4; “q6”: BOOP of weight l=6. “reg_tri”: regular triangle with varying height

      > > to basal plane;

      > ”sq”: square coordination (cf., “reg_tri”); “oct_legacy”: original Peters-style OP recognizing

      > > octahedral coordination environments (Zimmermann et al., J. Am. Chem. Soc., 137, 13352-13361, 2015) that can, however, produce small negative values sometimes.

      > ”sq_pyr_legacy”: square pyramids (legacy);

    - parameters (list[dict]) –

      float-type parameters associated with the definitions of the different order parameters (length of list = number of OPs). If an entry is None, default values are used that are read from the op_params.yaml file. With few exceptions, 9 different parameters are used across all OPs:

      > ”norm”: normalizing constant (used in “cn”

      >   (default value: 1)).

      > ”TA”: target angle (TA) in fraction of 180 degrees

      >   (“bent” (1), “tet” (0.6081734479693927), “tri_plan” (0.66666666667), “pent_plan” (0.6), “sq_pyr_legacy” (0.5)).

      > ”IGW_TA”: inverse Gaussian width (IGW) for penalizing

      >   angles away from the target angle in inverse fractions of 180 degrees to (“bent” and “tet” (15), “tri_plan” (13.5), “pent_plan” (18), “sq_pyr_legacy” (30)).

      > ”IGW_EP”: IGW for penalizing angles away from the

      >   equatorial plane (EP) at 90 degrees (“T”, “see_saw_rect”, “oct”, “sq_plan”, “tri_pyr”, “sq_pyr”, “pent_pyr”, “hex_pyr”, “tri_bipyr”, “sq_bipyr”, “pent_bipyr”, “hex_bipyr”, and “oct_legacy” (18)).

      > ”fac_AA”: factor applied to azimuth angle (AA) in cosine

      >   term (“T”, “tri_plan”, and “sq_plan” (1), “tet”, “tri_pyr”, and “tri_bipyr” (1.5), “oct”, “sq_pyr”, “sq_bipyr”, and “oct_legacy” (2), “pent_pyr” and “pent_bipyr” (2.5), “hex_pyr” and “hex_bipyr” (3)).

      > ”exp_cos_AA”: exponent applied to cosine term of AA

      >   (“T”, “tet”, “oct”, “tri_plan”, “sq_plan”, “tri_pyr”, “sq_pyr”, “pent_pyr”, “hex_pyr”, “tri_bipyr”, “sq_bipyr”, “pent_bipyr”, “hex_bipyr”, and “oct_legacy” (2)).

      > ”min_SPP”: smallest angle (in radians) to consider

      >   a neighbor to be at South pole position (“see_saw_rect”, “oct”, “bcc”, “sq_plan”, “tri_bipyr”, “sq_bipyr”, “pent_bipyr”, “hex_bipyr”, “cuboct”, and “oct_legacy” (2.792526803190927)).

      > ”IGW_SPP”: IGW for penalizing angles away from South

      >   pole position (“see_saw_rect”, “oct”, “bcc”, “sq_plan”, “tri_bipyr”, “sq_bipyr”, “pent_bipyr”, “hex_bipyr”, “cuboct”, and “oct_legacy” (15)).

      > ”w_SPP”: weight for South pole position relative to

      >   equatorial positions (“see_saw_rect” and “sq_plan” (1), “cuboct” (1.8), “tri_bipyr” (2), “oct”, “sq_bipyr”, and “oct_legacy” (3), “pent_bipyr” (4), “hex_bipyr” (5), “bcc” (6)).

    - cutoff (float) – Cutoff radius to determine which nearest neighbors are supposed to contribute to the order parameters. If the value is negative the neighboring sites found by distance and cutoff radius are further pruned using the get_nn method from the VoronoiNN class.

  compute_trigonometric_terms(thetas, phis)

    Compute trigonometric terms that are required to calculate bond orientational order parameters using internal variables.

    Parameters:

      - thetas ([float]) – polar angles of all neighbors in radians.

      - phis ([float]) – azimuth angles of all neighbors in radians. The list of azimuth angles of all neighbors in radians. The list of azimuth angles is expected to have the same size as the list of polar angles; otherwise, a ValueError is raised. Also, the two lists of angles have to be coherent in order. That is, it is expected that the order in the list of azimuth angles corresponds to a distinct sequence of neighbors. And, this sequence has to equal the sequence of neighbors in the list of polar angles.

  get_order_parameters(structure: Structure, n: int, indices_neighs: list[int] | None = None, tol: float = 0.0, target_spec: Species | None = None)

    Compute all order parameters of site n.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site in input structure, for which OPs are to be calculated. Note that we do not use the sites iterator here, but directly access sites via struct[index].

      - indices_neighs (list[int]) – list of indices of those neighbors in Structure object structure that are to be considered for OP computation. This optional argument overwrites the way neighbors are to be determined as defined in the constructor (i.e., Voronoi coordination finder via negative cutoff radius vs constant cutoff radius if cutoff was positive). We do not use information about the underlying structure lattice if the neighbor indices are explicitly provided. This has two important consequences. First, the input Structure object can, in fact, be a simple list of Site objects. Second, no nearest images of neighbors are determined when providing an index list. Note furthermore that this neighbor determination type ignores the optional target_spec argument.

      - tol (float) – threshold of weight (= solid angle / maximal solid angle) to determine if a particular pair is considered neighbors; this is relevant only in the case when Voronoi polyhedra are used to determine coordination

      - target_spec (Species) – target species to be considered when calculating the order parameters of site n; None includes all species of input structure.

    Returns:

      representing order parameters. Should it not be possible to compute a given OP for a conceptual reason, the corresponding entry is None instead of a float. For Steinhardt et al.’s bond orientational OPs and the other geometric OPs (“tet”, “oct”, “bcc”, etc.), this can happen if there is a single neighbor around site n in the structure because that does not permit calculation of angles between multiple neighbors.

    Return type:

      [floats]

  get_parameters(index: int) → dict[str | int, float] | None

    Get parameters associated with calculation of the order parameter that was defined at the index provided.

    Attention: the parameters do not need to equal those originally inputted because of processing out of efficiency reasons.

    Parameters:

      index (int) – index of order parameter for which to return associated params.

    Returns:

      parameters of a given OP.

    Return type:

      dict[str, float]

  get_q2(thetas=None, phis=None)

    Calculates the value of the bond orientational order parameter of weight l=2. If the function is called with non-empty lists of polar and azimuthal angles the corresponding trigonometric terms are computed afresh. Otherwise, it is expected that the compute_trigonometric_terms function has been just called.

    Parameters:

      - thetas ([float]) – polar angles of all neighbors in radians.

      - phis ([float]) – azimuth angles of all neighbors in radians.

    Returns:

      bond orientational order parameter of weight l=2

        corresponding to the input angles thetas and phis.

    Return type:

      float

  get_q4(thetas=None, phis=None)

    Calculates the value of the bond orientational order parameter of weight l=4. If the function is called with non-empty lists of polar and azimuthal angles the corresponding trigonometric terms are computed afresh. Otherwise, it is expected that the compute_trigonometric_terms function has been just called.

    Parameters:

      - thetas ([float]) – polar angles of all neighbors in radians.

      - phis ([float]) – azimuth angles of all neighbors in radians.

    Returns:

      bond orientational order parameter of weight l=4

        corresponding to the input angles thetas and phis.

    Return type:

      float

  get_q6(thetas=None, phis=None)

    Calculates the value of the bond orientational order parameter of weight l=6. If the function is called with non-empty lists of polar and azimuthal angles the corresponding trigonometric terms are computed afresh. Otherwise, it is expected that the compute_trigonometric_terms function has been just called.

    Parameters:

      - thetas ([float]) – polar angles of all neighbors in radians.

      - phis ([float]) – azimuth angles of all neighbors in radians.

    Returns:

      bond orientational order parameter of weight l=6

        corresponding to the input angles thetas and phis.

    Return type:

      float

  get_type(index)

    Get type of order parameter at the index provided and represented by a short string.

    Parameters:

      index (int) – index of order parameter for which type is to be returned.

    Returns:

      OP type.

    Return type:

      str

  property last_nneigh

    Number of neighbors encountered during the most recent order parameter calculation. A value of -1 indicates that no such calculation has yet been performed for this instance.

  property num_ops: int

    Number of different order parameters that are targeted to be calculated.

class MinimumDistanceNN(tol: float = 0.1, cutoff=10, get_all_sites=False)

  Bases: `NearNeighbors`

  Determine near-neighbor sites and coordination number using the nearest neighbor(s) at distance, d_min, plus all neighbors within a distance (1 + tol) * d_min, where tol is a (relative) distance tolerance parameter.

  Parameters:

    - tol (float) – tolerance parameter for neighbor identification (default: 0.1).

    - cutoff (float) – cutoff radius in Angstrom to look for trial near-neighbor sites (default: 10).

    - get_all_sites (bool) – If this is set to True then the neighbor sites are only determined by the cutoff radius, tol is ignored.

  property extend_structure_molecules: bool

    Do Molecules need to be converted to Structures to use this NearNeighbors class? Note: this property is not defined for classes for which molecules_allowed is False.

    Type:

      Boolean property

  get_nn_info(structure: Structure, n: int) → list[dict[str, Any]]

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n using the closest neighbor distance-based method.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near neighbors.

    Returns:

      dicts with (Site, array, float) each one of which represents a

        neighbor site, its image location, and its weight.

    Return type:

      siw (list[dict])

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class MinimumOKeeffeNN(tol: float = 0.1, cutoff=10)

  Bases: `NearNeighbors`

  Determine near-neighbor sites and coordination number using the neighbor(s) at closest relative distance, d_min_OKeffee, plus some relative tolerance, where bond valence parameters from O’Keeffe’s bond valence method (J. Am. Chem. Soc. 1991, 3226-3229) are used to calculate relative distances.

  Parameters:

    - tol (float) – tolerance parameter for neighbor identification (default: 0.1).

    - cutoff (float) – cutoff radius in Angstrom to look for trial near-neighbor sites (default: 10).

  property extend_structure_molecules: bool

    Do Molecules need to be converted to Structures to use this NearNeighbors class? Note: this property is not defined for classes for which molecules_allowed is False.

    Type:

      Boolean property

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n using the closest relative neighbor distance-based method with O’Keeffe parameters.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near neighbors.

    Returns:

      tuples, each one

        of which represents a neighbor site, its image location, and its weight.

    Return type:

      siw (list of tuples (Site, array, float))

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class MinimumVIRENN(tol: float = 0.1, cutoff=10)

  Bases: `NearNeighbors`

  Determine near-neighbor sites and coordination number using the neighbor(s) at closest relative distance, d_min_VIRE, plus some relative tolerance, where atom radii from the ValenceIonicRadiusEvaluator (VIRE) are used to calculate relative distances.

  Parameters:

    - tol (float) – tolerance parameter for neighbor identification (default: 0.1).

    - cutoff (float) – cutoff radius in Angstrom to look for trial near-neighbor sites (default: 10).

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n using the closest relative neighbor distance-based method with VIRE atomic/ionic radii.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near neighbors.

    Returns:

      tuples, each one

        of which represents a neighbor site, its image location, and its weight.

    Return type:

      siw (list of tuples (Site, array, float))

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class NearNeighbors

  Bases: `object`

  Base class to determine near neighbors that typically include nearest neighbors and others that are within some tolerable distance.

  property extend_structure_molecules: bool

    Do Molecules need to be converted to Structures to use this NearNeighbors class? Note: this property is not defined for classes for which molecules_allowed is False.

    Type:

      Boolean property

  get_all_nn_info(structure: Structure)

    Get a listing of all neighbors for all sites in a structure.

    Parameters:

      structure (Structure) – Input structure

    Returns:

      List of NN site information for each site in the structure. Each

        entry has the same format as get_nn_info

  get_bonded_structure(structure: Structure, decorate: bool = False, weights: bool = True, edge_properties: bool = False, on_disorder: on_disorder_options = 'take_majority_strict') → StructureGraph | MoleculeGraph

    Obtain a StructureGraph object using this NearNeighbor class. Requires pip install networkx.

    NOTE: The StructureGraph will not contain sites or bonds that are equivalent under lattice vector translations. For more details please see the following discussion: https://github.com/materialsproject/pymatgen/issues/3888

    Parameters:

      - structure – Structure object.

      - decorate (bool) – whether to annotate site properties with order parameters using neighbors determined by this NearNeighbor class

      - weights (bool) – whether to include edge weights from NearNeighbor class in StructureGraph

      - edge_properties (bool) – whether to include further edge properties from NearNeighbor class in StructureGraph

      - on_disorder ('take_majority_strict' | 'take_majority_drop' | 'take_max_species' | 'error') – What to do when encountering a disordered structure. ‘error’ will raise ValueError. ‘take_majority_strict’ will use the majority specie on each site and raise ValueError if no majority exists. ‘take_max_species’ will use the first max specie on each site. For {{Fe: 0.4, O: 0.4, C: 0.2}}, ‘error’ and ‘take_majority_strict’ will raise ValueError, while ‘take_majority_drop’ ignores this site altogether and ‘take_max_species’ will use Fe as the site specie.

    Returns:

      object from pymatgen.core.graphs

    Return type:

      StructureGraph

  get_cn(structure: Structure, n: int, use_weights: Literal[False] = False, on_disorder: Literal['take_majority_strict', 'take_majority_drop', 'take_max_species', 'error'] = 'take_majority_strict') → int
  get_cn(structure: Structure, n: int, use_weights: Literal[True] = True, on_disorder: Literal['take_majority_strict', 'take_majority_drop', 'take_max_species', 'error'] = 'take_majority_strict') → float

    Get coordination number, CN, of site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine CN.

      - use_weights (bool) – flag indicating whether (True) to use weights for computing the coordination number or not (False, default: each coordinated site has equal weight).

      - on_disorder ('take_majority_strict' | 'take_majority_drop' | 'take_max_species' | 'error') – What to do when encountering a disordered structure. ‘error’ will raise ValueError. ‘take_majority_strict’ will use the majority specie on each site and raise ValueError if no majority exists. ‘take_max_species’ will use the first max specie on each site. For {{Fe: 0.4, O: 0.4, C: 0.2}}, ‘error’ and ‘take_majority_strict’ will raise ValueError, while ‘take_majority_drop’ ignores this site altogether and ‘take_max_species’ will use Fe as the site specie.

    Returns:

      coordination number (float if weighted)

    Return type:

      int | float

  get_cn_dict(structure: Structure, n: int, use_weights: bool = False)

    Get coordination number, CN, of each element bonded to site with index n in structure.

    Parameters:

      - structure (Structure) – input structure

      - n (int) – index of site for which to determine CN.

      - use_weights (bool) – flag indicating whether (True) to use weights for computing the coordination number or not (False, default: each coordinated site has equal weight).

    Returns:

      coordination number of each element bonded to site with index n in structure.

    Return type:

      dict[str, float]

  get_local_order_parameters(structure: Structure, n: int)

    Calculate those local structure order parameters for the given site whose ideal CN corresponds to the underlying motif (e.g., CN=4, then calculate the square planar, tetrahedral, see-saw-like, rectangular see-saw-like order parameters).

    Parameters:

      - structure – Structure object

      - n (int) – site index.

    Returns:

      A dict of order parameters (values) and the

        underlying motif type (keys; for example, tetrahedral).

    Return type:

      dict[str, float]

  get_nn(structure: Structure, n: int)

    Get near neighbors of site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site in structure for which to determine neighbors.

    Returns:

      near neighbors.

    Return type:

      sites (list of Site objects)

  get_nn_images(structure: Structure, n: int)

    Get image location of all near neighbors of site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine the image location of near neighbors.

    Returns:

      image locations of

        near neighbors.

    Return type:

      images (list of 3D integer array)

  get_nn_info(structure: Structure, n: int) → list[dict]

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near-neighbor information.

    Returns:

      each dictionary provides information

        about a single near neighbor, where key ‘site’ gives access to the corresponding Site object, ‘image’ gives the image location, and ‘weight’ provides the weight that a given near-neighbor site contributes to the coordination number (1 or smaller), ‘site_index’ gives index of the corresponding site in the original structure.

    Return type:

      siw (list[dict])

  get_nn_shell_info(structure: Structure, site_idx, shell)

    Get a certain nearest neighbor shell for a certain site.

    Determines all non-backtracking paths through the neighbor network computed by get_nn_info. The weight is determined by multiplying the weight of the neighbor at each hop through the network. For example, a 2nd-nearest-neighbor that has a weight of 1 from its 1st-nearest-neighbor and weight 0.5 from the original site will be assigned a weight of 0.5.

    As this calculation may involve computing the nearest neighbors of atoms multiple times, the calculation starts by computing all of the neighbor info and then calling _get_nn_shell_info. If you are likely to call this method for more than one site, consider calling get_all_nn first and then calling this protected method yourself.

    Parameters:

      - structure (Structure) – Input structure

      - site_idx (int) – index of site for which to determine neighbor information.

      - shell (int) – Which neighbor shell to retrieve (1 == 1st NN shell)

    Returns:

      list of dictionaries. Each entry in the list is information about

        a certain neighbor in the structure, in the same format as get_nn_info.

  get_weights_of_nn_sites(structure: Structure, n: int)

    Get weight associated with each near neighbor of site with index n in structure.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine the weights.

    Returns:

      near-neighbor weights.

    Return type:

      weights (list of floats)

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class OpenBabelNN(order=True)

  Bases: `NearNeighbors`

  Determine near-neighbor sites and bond orders using OpenBabel API.

  NOTE: This strategy is only appropriate for molecules, and not for structures.

  Parameters:

    - order (bool) – True if bond order should be returned as a weight, False

    - weight. (if bond length should be used as a)

  property extend_structure_molecules: bool

    Do Molecules need to be converted to Structures to use this NearNeighbors class? Note: this property is not defined for classes for which molecules_allowed is False.

    Type:

      Boolean property

  get_bonded_structure(structure: Structure, decorate: bool = False) → StructureGraph

    Obtain a MoleculeGraph object using this NearNeighbor class. Requires the optional dependency networkx (pip install networkx).

    Parameters:

      - structure – Molecule object.

      - decorate (bool) – whether to annotate site properties

      - by (with order parameters using neighbors determined)

      - class (this NearNeighbor)

    Returns:

      object from pymatgen.core.graphs

    Return type:

      MoleculeGraph

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites and weights (orders) of bonds for a given atom.

    Parameters:

      - structure – Molecule object.

      - n – index of site for which to determine near neighbors.

    Returns:

      representing a neighboring site and the type of bond present between site n and the neighboring site.

    Return type:

      dict

  get_nn_shell_info(structure: Structure, site_idx, shell)

    Get a certain nearest neighbor shell for a certain site.

    Determines all non-backtracking paths through the neighbor network computed by get_nn_info. The weight is determined by multiplying the weight of the neighbor at each hop through the network. For example, a 2nd-nearest-neighbor that has a weight of 1 from its 1st-nearest-neighbor and weight 0.5 from the original site will be assigned a weight of 0.5.

    As this calculation may involve computing the nearest neighbors of atoms multiple times, the calculation starts by computing all of the neighbor info and then calling _get_nn_shell_info. If you are likely to call this method for more than one site, consider calling get_all_nn first and then calling this protected method yourself.

    Parameters:

      - structure (Molecule) – Input structure

      - site_idx (int) – index of site for which to determine neighbor information.

      - shell (int) – Which neighbor shell to retrieve (1 == 1st NN shell)

    Returns:

      list of dictionaries. Each entry in the list is information about

        a certain neighbor in the structure, in the same format as get_nn_info.

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

class ValenceIonicRadiusEvaluator(structure: Structure)

  Bases: `object`

  Computes site valences and ionic radii for a structure using bond valence analyzer.

  Parameters:

    structure – pymatgen Structure.

  property radii

    List of ionic radii of elements in the order of sites.

  property structure

    Oxidation state decorated structure.

  property valences

    List of oxidation states of elements in the order of sites.

class VoronoiNN(tol=0, targets=None, cutoff=13.0, allow_pathological=False, weight='solid_angle', extra_nn_info=True, compute_adj_neighbors=True)

  Bases: `NearNeighbors`

  Uses a Voronoi algorithm to determine near neighbors for each site in a structure.

  Parameters:

    - tol (float) – tolerance parameter for near-neighbor finding. Faces that are smaller than tol fraction of the largest face are not included in the tessellation. (default: 0).

    - targets (Element or list of Elements) – target element(s).

    - cutoff (float) – cutoff radius in Angstrom to look for near-neighbor atoms. Defaults to 13.0.

    - allow_pathological (bool) – whether to allow infinite vertices in determination of Voronoi coordination.

    - weight (string) – Statistic used to weigh neighbors (see the statistics available in get_voronoi_polyhedra)

    - extra_nn_info (bool) – Add all polyhedron info to get_nn_info

    - compute_adj_neighbors (bool) – Whether to compute which neighbors are adjacent. Turn off for faster performance.

  get_all_nn_info(structure: Structure)
    Parameters:

      structure (Structure) – input structure.

    Returns:

      All nn info for all sites.

  get_all_voronoi_polyhedra(structure: Structure)

    Get the Voronoi polyhedra for all site in a simulation cell.

    Parameters:

      structure (Structure) – Structure to be evaluated

    Returns:

      A dict of sites sharing a common Voronoi facet with the site n mapped to a directory containing statistics about the facet:

      > - solid_angle - Solid angle subtended by face

      > - angle_normalized - Solid angle normalized such that the

      >     faces with the largest

      > - area - Area of the facet

      > - face_dist - Distance between site n and the facet

      > - volume - Volume of Voronoi cell for this face

      > - n_verts - Number of vertices on the facet

  get_nn_info(structure: Structure, n: int)

    Get all near-neighbor sites as well as the associated image locations and weights of the site with index n in structure using Voronoi decomposition.

    Parameters:

      - structure (Structure) – input structure.

      - n (int) – index of site for which to determine near-neighbor sites.

    Returns:

      tuples, each one

        of which represents a coordinated site, its image location, and its weight.

    Return type:

      siw (list of tuples (Site, array, float))

  get_voronoi_polyhedra(structure: Structure, n: int)

    Get a weighted polyhedra around a site.

    See ref: A Proposed Rigorous Definition of Coordination Number, M. O’Keeffe, Acta Cryst. (1979). A35, 772-775

    Parameters:

      - structure (Structure) – structure for which to evaluate the coordination environment.

      - n (int) – site index.

    Returns:

      A dict of sites sharing a common Voronoi facet with the site n mapped to a directory containing statistics about the facet:

      > - solid_angle - Solid angle subtended by face

      > - angle_normalized - Solid angle normalized such that the

      >     faces with the largest

      > - area - Area of the facet

      > - face_dist - Distance between site n and the facet

      > - volume - Volume of Voronoi cell for this face

      > - n_verts - Number of vertices on the facet

  property molecules_allowed: bool

    can this NearNeighbors class be used with Molecule objects?

    Type:

      Boolean property

  property structures_allowed: bool

    can this NearNeighbors class be used with Structure objects?

    Type:

      Boolean property

get_neighbors_of_site_with_index(struct, n, approach='min_dist', delta=0.1, cutoff=10)

  Get the neighbors of a given site using a specific neighbor-finding method.

  Parameters:

    - struct (Structure) – input structure.

    - n (int) – index of site in Structure object for which motif type is to be determined.

    - approach (str) – type of neighbor-finding approach, where “min_dist” will use the MinimumDistanceNN class, “voronoi” the VoronoiNN class, “min_OKeeffe” the MinimumOKeeffe class, and “min_VIRE” the MinimumVIRENN class.

    - delta (float) – tolerance involved in neighbor finding.

    - cutoff (float) – radius to find tentative neighbors.

  Returns:

    neighbor sites.

get_okeeffe_distance_prediction(el1, el2)

  Get an estimate of the bond valence parameter (bond length) using the derived parameters from ‘Atoms Sizes and Bond Lengths in Molecules and Crystals’ (O’Keeffe & Brese, 1991). The estimate is based on two experimental parameters: r and c. The value for r is based off radius, while c is (usually) the Allred-Rochow electronegativity. Values used are not generated from pymatgen, and are found in ‘okeeffe_params.json’.

  Parameters:

    - el1 (Element) – First element.

    - el2 (Element) – Second element.

  Returns:

    a float value of the predicted bond length

get_okeeffe_params(el_symbol)

  Get the elemental parameters related to atom size and electronegativity which are used for estimating bond-valence parameters (bond length) of pairs of atoms on the basis of data provided in ‘Atoms Sizes and Bond Lengths in Molecules and Crystals’ (O’Keeffe & Brese, 1991).

  Parameters:

    el_symbol (str) – element symbol.

  Returns:

    atom-size (‘r’) and electronegativity-related (‘c’) parameter.

  Return type:

    dict

gramschmidt(vin, uin)

  Get that part of the first input vector that is orthogonal to the second input vector. The output vector is not normalized.

  Parameters:

    - vin (numpy array) – first input vector

    - uin (numpy array) – second input vector

metal_edge_extender(mol_graph, cutoff: float = 2.5, metals: list | tuple | None = ('Li', 'Mg', 'Ca', 'Zn', 'B', 'Al'), coordinators: list | tuple = ('O', 'N', 'F', 'S', 'Cl'))

  Identify and add missed coordinate bond edges for metals.

  Parameters:

    - mol_graph – pymatgen.core.graphs.MoleculeGraph object

    - cutoff – cutoff in Angstrom. Metal-coordinator sites that are closer together than this value will be considered coordination bonds. If the MoleculeGraph contains a metal, but no coordination bonds are found with the chosen cutoff, the cutoff will be increased by 1 Angstrom and another attempt will be made to identify coordination bonds.

    - metals – Species considered metals for the purpose of identifying missed coordinate bond edges. The set {“Li”, “Mg”, “Ca”, “Zn”, “B”, “Al”} (default) corresponds to the settings used in the LIBE dataset. Alternatively, set to None to cause any Species classified as a metal by Specie.is_metal to be considered a metal.

    - coordinators – Possible coordinating species to consider when identifying missed coordinate bonds. The default set {“O”, “N”, “F”, “S”, “Cl”} was used in the LIBE dataset.

  Returns:

    pymatgen.core.graphs.MoleculeGraph object with additional

      metal bonds (if any found) added

  Return type:

    mol_graph

oxygen_edge_extender(mol_graph: MoleculeGraph) → MoleculeGraph

  Identify and add missed O-C or O-H bonds. This is particularly important when oxygen is forming three bonds, e.g. in H3O+ or XOH2+. See https://github.com/materialsproject/pymatgen/pull/2903 for details.

  Parameters:

    mol_graph (MoleculeGraph) – molecule graph to extend

  Returns:

    object with additional O-C or O-H bonds added (if any found)

  Return type:

    MoleculeGraph

site_is_of_motif_type(struct, n, approach='min_dist', delta=0.1, cutoff=10, thresh=None)

  Get the motif type of the site with index n in structure struct; currently featuring “tetrahedral”, “octahedral”, “bcc”, and “cp” (close-packed: fcc and hcp) as well as “square pyramidal” and “trigonal bipyramidal”. If the site is not recognized, “unrecognized” is returned. If a site should be assigned to two different motifs, “multiple assignments” is returned.

  Parameters:

    - struct (Structure) – input structure.

    - n (int) – index of site in Structure object for which motif type is to be determined.

    - approach (str) – type of neighbor-finding approach, where “min_dist” will use the MinimumDistanceNN class, “voronoi” the VoronoiNN class, “min_OKeeffe” the MinimumOKeeffe class, and “min_VIRE” the MinimumVIRENN class.

    - delta (float) – tolerance involved in neighbor finding.

    - cutoff (float) – radius to find tentative neighbors.

    - thresh (dict) – thresholds for motif criteria (currently, required keys and their default values are “qtet”: 0.5, “qoct”: 0.5, “qbcc”: 0.5, “q6”: 0.4).

  Returns:

    motif type

  Return type:

    str

solid_angle(center, coords)

  Helper method to calculate the solid angle of a set of coords from the center.

  Parameters:

    - center (3x1 array) – Center to measure solid angle from.

    - coords (Nx3 array) – List of coords to determine solid angle.

  Returns:

    The solid angle.

vol_tetra(vt1, vt2, vt3, vt4)

  Calculate the volume of a tetrahedron, given the four vertices of vt1, vt2, vt3 and vt4.

  Parameters:

    - vt1 (array-like) – coordinates of vertex 1.

    - vt2 (array-like) – coordinates of vertex 2.

    - vt3 (array-like) – coordinates of vertex 3.

    - vt4 (array-like) – coordinates of vertex 4.

  Returns:

    volume of the tetrahedron.

  Return type:

    float

## 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.molecule_matcher module

This module provides classes to perform fitting of molecule with arbitrary atom orders. This module is supposed to perform exact comparisons without the atom order correspondence prerequisite, while molecule_structure_comparator is supposed to do rough comparisons with the atom order correspondence prerequisite.

The implementation is based on an excellent python package called rmsd that you can find at https://github.com/charnley/rmsd.

class AbstractMolAtomMapper

  Bases: `MSONable`, `ABC`

  Abstract molecular atom order mapping class. A mapping will be able to find the uniform atom order of two molecules that can pair the geometrically equivalent atoms.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      AbstractMolAtomMapper

  abstractmethod get_molecule_hash(mol)

    Defines a hash for molecules. This allows molecules to be grouped efficiently for comparison.

    Parameters:

      mol – The molecule. OpenBabel OBMol or pymatgen Molecule object

    Returns:

      A hashable object. Examples can be string formulas, etc.

  abstractmethod uniform_labels(mol1, mol2)

    Pair the geometrically equivalent atoms of the molecules.

    Parameters:

      - mol1 – First molecule. OpenBabel OBMol or pymatgen Molecule object.

      - mol2 – Second molecule. OpenBabel OBMol or pymatgen Molecule object.

    Returns:

      if uniform atom order is found. list1 and list2

        are for mol1 and mol2, respectively. Their length equal to the number of atoms. They represents the uniform atom order of the two molecules. The value of each element is the original atom index in mol1 or mol2 of the current atom in uniform atom order. (None, None) if uniform atom is not available.

    Return type:

      tuple[list1, list2]

class BruteForceOrderMatcher(target: Molecule)

  Bases: `KabschMatcher`

  Finding the best match between molecules by selecting molecule order with the smallest RMSD from all the possible order combinations.

  Notes

  When aligning molecules, the atoms of the two molecules must have same number of atoms from the same species.

  Constructor of the matcher object.

  Parameters:

    target – a Molecule object used as a target during the alignment

  fit(p: Molecule, ignore_warning=False, break_on_tol: float | None = None)

    Order, rotate and transform p molecule according to the best match.

    A ValueError will be raised when the total number of possible combinations become unfeasible (more than a million combinations).

    The break_on_tol option can be used for efficiency, to stop searching over permutations if the RMSD becomes smaller than break_on_tol.

    Parameters:

      - p – a Molecule object what will be matched with the target one.

      - ignore_warning – ignoring error when the number of combination is too large.

      - break_on_tol – return the first match with an RMSD value less than this tolerance.

    Returns:

      Rotated and translated of the p Molecule object rmsd: Root-mean-square-deviation between p_prime and the target

    Return type:

      p_prime

  match(mol: Molecule, ignore_warning: bool = False, break_on_tol: float | None = None) → tuple[ndarray, ndarray, ndarray, float]

    Similar as KabschMatcher.match but this method also finds the order of atoms which belongs to the best match.

    A ValueError will be raised when the total number of possible combinations become unfeasible (more than a million combination).

    The break_on_tol option can be used for efficiency, to stop searching over permutations if the RMSD becomes smaller than break_on_tol.

    Parameters:

      - mol – a Molecule object what will be matched with the target one.

      - ignore_warning – ignoring error when the number of combination is too large.

      - break_on_tol – return the first match with an RMSD value less than this tolerance.

    Returns:

      The indices of atoms U: 3x3 rotation matrix V: Translation vector rmsd: Root mean squared deviation between P and Q

    Return type:

      inds

  static permutations(atoms)

    Generate all the possible permutations of atom order. To achieve better performance all the cases where the atoms are different has been ignored.

class GeneticOrderMatcher(target: Molecule, threshold: float)

  Bases: `KabschMatcher`

  This method was inspired by genetic algorithms and tries to match molecules based on their already matched fragments.

  It uses the fact that when two molecule is matching their sub-structures have to match as well. The main idea here is that in each iteration (generation) we can check the match of all possible fragments and ignore those which are not feasible.

  Although in the worst case this method has N! complexity (same as the brute force one), in practice it performs much faster because many of the combination can be eliminated during the fragment matching.

  Notes

  This method very robust and returns with all the possible orders.

  There is a well known weakness/corner case: The case when there is a outlier with large deviation with a small index might be ignored. This happens due to the nature of the average function used to calculate the RMSD for the fragments.

  When aligning molecules, the atoms of the two molecules must have the same number of atoms from the same species.

  Constructor of the matcher object.

  Parameters:

    - target – a Molecule object used as a target during the alignment

    - threshold – value used to match fragments and prune configuration

  fit(p: Molecule)

    Order, rotate and transform all of the matched p molecule according to the given threshold.

    Parameters:

      p – a Molecule object what will be matched with the target one.

    Returns:

      possible matches where the elements are:

        p_prime: Rotated and translated of the p Molecule object rmsd: Root-mean-square-deviation between p_prime and the target

    Return type:

      list[tuple[Molecule, float]]

  match(p: Molecule)

    Similar as KabschMatcher.match but this method also finds all of the possible atomic orders according to the threshold.

    Parameters:

      p – a Molecule object what will be matched with the target one.

    Returns:

      inds: The indices of atoms U: 3x3 rotation matrix V: Translation vector rmsd: Root mean squared deviation between P and Q

    Return type:

      Array of the possible matches where the elements are

  permutations(p: Molecule)

    Generate all of possible permutations of atom order according the threshold.

    Parameters:

      p – a Molecule object what will be matched with the target one.

    Returns:

      Array of index arrays

class HungarianOrderMatcher(target: Molecule)

  Bases: `KabschMatcher`

  Pre-align the molecules based on their principal inertia axis and then re-orders the input atom list using the Hungarian method.

  Notes

  This method cannot guarantee the best match but is very fast.

  When aligning molecules, the atoms of the two molecules must have same number of atoms from the same species.

  Constructor of the matcher object.

  Parameters:

    target – a Molecule object used as a target during the alignment

  fit(p: Molecule)

    Order, rotate and transform p molecule according to the best match.

    Parameters:

      p – a Molecule object what will be matched with the target one.

    Returns:

      Rotated and translated of the p Molecule object rmsd: Root-mean-square-deviation between p_prime and the target

    Return type:

      p_prime

  static get_principal_axis(coords, weights)

    Get the molecule’s principal axis.

    Parameters:

      - coords – coordinates of atoms

      - weights – the weight use for calculating the inertia tensor

    Returns:

      Array of dim 3 containing the principal axis

  match(p: Molecule)

    Similar as KabschMatcher.match but this method also finds the order of atoms which belongs to the best match.

    Parameters:

      p – a Molecule object what will be matched with the target one.

    Returns:

      The indices of atoms U: 3x3 rotation matrix V: Translation vector rmsd: Root mean squared deviation between P and Q

    Return type:

      inds

  static permutations(p_atoms, p_centroid, p_weights, q_atoms, q_centroid, q_weights)

    Generate two possible permutations of atom order. This method uses the principle component of the inertia tensor to pre-align the molecules and hungarian method to determine the order. There are always two possible permutation depending on the way to pre-aligning the molecules.

    Parameters:

      - p_atoms – atom numbers

      - p_centroid – array of atom positions

      - p_weights – array of atom weights

      - q_atoms – atom numbers

      - q_centroid – array of atom positions

      - q_weights – array of atom weights

    Yields:

      perm_inds – array of atoms’ order

  static rotation_matrix_vectors(v1, v2)

    Get the rotation matrix that rotates v1 onto v2 using Rodrigues’ rotation formula.

    See more: https://math.stackexchange.com/a/476311

    Parameters:

      - v1 – initial vector

      - v2 – target vector

    Returns:

      3x3 rotation matrix

class InchiMolAtomMapper(angle_tolerance=10.0)

  Bases: `AbstractMolAtomMapper`

  Pair atoms by inchi labels.

  Parameters:

    angle_tolerance (float) – Angle threshold to assume linear molecule. In degrees.

  as_dict()

    Get MSONable dict.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict Representation.

    Returns:

      InchiMolAtomMapper

  get_molecule_hash(mol)

    Return inchi as molecular hash.

  uniform_labels(mol1, mol2)
    Parameters:

      - mol1 (Molecule) – Molecule 1

      - mol2 (Molecule) – Molecule 2.

    Returns:

      Labels

class IsomorphismMolAtomMapper

  Bases: `AbstractMolAtomMapper`

  Pair atoms by isomorphism permutations in the OpenBabel::OBAlign class.

  as_dict()

    Get MSONable dict.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      IsomorphismMolAtomMapper

  get_molecule_hash(mol)

    Return inchi as molecular hash.

  uniform_labels(mol1, mol2)

    Pair the geometrically equivalent atoms of the molecules. Calculate RMSD on all possible isomorphism mappings and return mapping with the least RMSD.

    Parameters:

      - mol1 – First molecule. OpenBabel OBMol or pymatgen Molecule object.

      - mol2 – Second molecule. OpenBabel OBMol or pymatgen Molecule object.

    Returns:

      if uniform atom order is found. list1 and list2

        are for mol1 and mol2, respectively. Their length equal to the number of atoms. They represents the uniform atom order of the two molecules. The value of each element is the original atom index in mol1 or mol2 of the current atom in uniform atom order. (None, None) if uniform atom is not available.

    Return type:

      tuple[list1, list2]

class KabschMatcher(target: Molecule)

  Bases: `MSONable`

  Molecule matcher using Kabsch algorithm.

  The Kabsch algorithm capable aligning two molecules by finding the parameters (translation, rotation) which minimize the root-mean-square-deviation (RMSD) of two molecules which are topologically (atom types, geometry) similar two each other.

  Notes

  When aligning molecules, the atoms of the two molecules must be in the same order for the results to be sensible.

  Constructor of the matcher object.

  Parameters:

    target – a Molecule object used as a target during the alignment

  fit(p: Molecule)

    Rotate and transform p molecule according to the best match.

    Parameters:

      p – a Molecule object what will be matched with the target one.

    Returns:

      Rotated and translated of the p Molecule object rmsd: Root-mean-square-deviation between p_prime and the target

    Return type:

      p_prime

  static kabsch(P: ndarray, Q: ndarray)

    The Kabsch algorithm is a method for calculating the optimal rotation matrix that minimizes the root mean squared deviation (RMSD) between two paired sets of points P and Q, centered around the their centroid.

    For more info see: - https://wikipedia.org/wiki/Kabsch_algorithm and - https://cnx.org/contents/HV-RsdwL@23/Molecular-Distance-Measures

    Parameters:

      - P – Nx3 matrix, where N is the number of points.

      - Q – Nx3 matrix, where N is the number of points.

    Returns:

      3x3 rotation matrix

    Return type:

      U

  match(p: Molecule)

    Using the Kabsch algorithm the alignment of two molecules (P, Q) happens in three steps: - translate the P and Q into their centroid - compute of the optimal rotation matrix (U) using Kabsch algorithm - compute the translation (V) and rmsd.

    The function returns the rotation matrix (U), translation vector (V), and RMSD between Q and P’, where P’ is:

    > P’ = P * U + V

    Parameters:

      p – a Molecule object what will be matched with the target one.

    Returns:

      Rotation matrix (D,D) V: Translation vector (D) RMSD : Root mean squared deviation between P and Q

    Return type:

      U

class MoleculeMatcher(tolerance: float = 0.01, mapper=None)

  Bases: `MSONable`

  Match molecules and identify whether molecules are the same.

  Parameters:

    - tolerance (float) – RMSD difference threshold whether two molecules are different

    - mapper (AbstractMolAtomMapper) – MolAtomMapper object that is able to map the atoms of two molecule to uniform order.

  as_dict()

    Get MSONable dict.

  fit(mol1, mol2)

    Fit two molecules.

    Parameters:

      - mol1 – First molecule. OpenBabel OBMol or pymatgen Molecule object

      - mol2 – Second molecule. OpenBabel OBMol or pymatgen Molecule object

    Returns:

      True if two molecules are the same.

    Return type:

      bool

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      MoleculeMatcher

  get_rmsd(mol1, mol2)

    Get RMSD between two molecule with arbitrary atom order.

    Returns:

      RMSD if topology of the two molecules are the same Infinite if the topology is different

  group_molecules(mol_list)

    Group molecules by structural equality.

    Parameters:

      mol_list – List of OpenBabel OBMol or pymatgen objects

    Returns:

      A list of lists of matched molecules Assumption: if s1=s2 and s2=s3, then s1=s3 This may not be true for small tolerances.

## pymatgen.core.molecule_structure_comparator module

This module provides classes to comparison the structures of the two molecule. As long as the two molecule have the same bond connection tables, the molecules are deemed to be same. The atom in the two molecule must be paired accordingly. This module is supposed to perform rough comparisons with the atom order correspondence prerequisite, while molecule_matcher is supposed to do exact comparisons without the atom order correspondence prerequisite.

class CovalentRadius

  Bases: `object`

  Covalent radius of the elements.

  Beatriz C. et al. Dalton Trans. 2008, 2832-2838. https://doi.org/10.1039/b801115j

  radius: ClassVar = {'Ac': 2.15, 'Ag': 1.45, 'Al': 1.21, 'Am': 1.8, 'Ar': 1.06, 'As': 1.19, 'At': 1.5, 'Au': 1.36, 'B': 0.84, 'Ba': 2.15, 'Be': 0.96, 'Bi': 1.48, 'Br': 1.2, 'C': 0.73, 'Ca': 1.76, 'Cd': 1.44, 'Ce': 2.04, 'Cl': 1.02, 'Cm': 1.69, 'Co': 1.38, 'Cr': 1.39, 'Cs': 2.44, 'Cu': 1.32, 'Dy': 1.92, 'Er': 1.89, 'Eu': 1.98, 'F': 0.57, 'Fe': 1.42, 'Fr': 2.6, 'Ga': 1.22, 'Gd': 1.96, 'Ge': 1.2, 'H': 0.31, 'He': 0.28, 'Hf': 1.75, 'Hg': 1.32, 'Ho': 1.92, 'I': 1.39, 'In': 1.42, 'Ir': 1.41, 'K': 2.03, 'Kr': 1.16, 'La': 2.07, 'Li': 1.28, 'Lu': 1.87, 'Mg': 1.41, 'Mn': 1.5, 'Mo': 1.54, 'N': 0.71, 'Na': 1.66, 'Nb': 1.64, 'Nd': 2.01, 'Ne': 0.58, 'Ni': 1.24, 'Np': 1.9, 'O': 0.66, 'Os': 1.44, 'P': 1.07, 'Pa': 2, 'Pb': 1.46, 'Pd': 1.39, 'Pm': 1.99, 'Po': 1.4, 'Pr': 2.03, 'Pt': 1.36, 'Pu': 1.87, 'Ra': 2.21, 'Rb': 2.2, 'Re': 1.51, 'Rh': 1.42, 'Rn': 1.5, 'Ru': 1.46, 'S': 1.05, 'Sb': 1.39, 'Sc': 1.7, 'Se': 1.2, 'Si': 1.11, 'Sm': 1.98, 'Sn': 1.39, 'Sr': 1.95, 'Ta': 1.7, 'Tb': 1.94, 'Tc': 1.47, 'Te': 1.38, 'Th': 2.06, 'Ti': 1.6, 'Tl': 1.45, 'Tm': 1.9, 'U': 1.96, 'V': 1.53, 'W': 1.62, 'Xe': 1.4, 'Y': 1.9, 'Yb': 1.87, 'Zn': 1.22, 'Zr': 1.75}

class MoleculeStructureComparator(bond_length_cap=0.3, covalent_radius={'Ac': 2.15, 'Ag': 1.45, 'Al': 1.21, 'Am': 1.8, 'Ar': 1.06, 'As': 1.19, 'At': 1.5, 'Au': 1.36, 'B': 0.84, 'Ba': 2.15, 'Be': 0.96, 'Bi': 1.48, 'Br': 1.2, 'C': 0.73, 'Ca': 1.76, 'Cd': 1.44, 'Ce': 2.04, 'Cl': 1.02, 'Cm': 1.69, 'Co': 1.38, 'Cr': 1.39, 'Cs': 2.44, 'Cu': 1.32, 'Dy': 1.92, 'Er': 1.89, 'Eu': 1.98, 'F': 0.57, 'Fe': 1.42, 'Fr': 2.6, 'Ga': 1.22, 'Gd': 1.96, 'Ge': 1.2, 'H': 0.31, 'He': 0.28, 'Hf': 1.75, 'Hg': 1.32, 'Ho': 1.92, 'I': 1.39, 'In': 1.42, 'Ir': 1.41, 'K': 2.03, 'Kr': 1.16, 'La': 2.07, 'Li': 1.28, 'Lu': 1.87, 'Mg': 1.41, 'Mn': 1.5, 'Mo': 1.54, 'N': 0.71, 'Na': 1.66, 'Nb': 1.64, 'Nd': 2.01, 'Ne': 0.58, 'Ni': 1.24, 'Np': 1.9, 'O': 0.66, 'Os': 1.44, 'P': 1.07, 'Pa': 2, 'Pb': 1.46, 'Pd': 1.39, 'Pm': 1.99, 'Po': 1.4, 'Pr': 2.03, 'Pt': 1.36, 'Pu': 1.87, 'Ra': 2.21, 'Rb': 2.2, 'Re': 1.51, 'Rh': 1.42, 'Rn': 1.5, 'Ru': 1.46, 'S': 1.05, 'Sb': 1.39, 'Sc': 1.7, 'Se': 1.2, 'Si': 1.11, 'Sm': 1.98, 'Sn': 1.39, 'Sr': 1.95, 'Ta': 1.7, 'Tb': 1.94, 'Tc': 1.47, 'Te': 1.38, 'Th': 2.06, 'Ti': 1.6, 'Tl': 1.45, 'Tm': 1.9, 'U': 1.96, 'V': 1.53, 'W': 1.62, 'Xe': 1.4, 'Y': 1.9, 'Yb': 1.87, 'Zn': 1.22, 'Zr': 1.75}, priority_bonds=(), priority_cap=0.8, ignore_ionic_bond=True, bond_13_cap=0.05)

  Bases: `MSONable`

  Check whether the connection tables of the two molecules are the same. The atom in the two molecule must be paired accordingly.

  Parameters:

    - bond_length_cap – The ratio of the elongation of the bond to be acknowledged. If the distance between two atoms is less than ( empirical covalent bond length) X (1 + bond_length_cap), the bond between the two atoms will be acknowledged.

    - covalent_radius – The covalent radius of the atoms. dict (element symbol -> radius)

    - priority_bonds – The bonds that are known to be existed in the initial molecule. Such bonds will be acknowledged in a loose criteria. The index should start from 0.

    - priority_cap – The ratio of the elongation of the bond to be acknowledged for the priority bonds.

    - ignore_ionic_bond (bool) – Whether to ignore ionic bonds.

    - bond_13_cap (float) – The ratio of the elongation of the 1-3 bond to be acknowledged.

  are_equal(mol1, mol2) → bool

    Compare the bond table of the two molecules.

    Parameters:

      - mol1 – first molecule. pymatgen Molecule object.

      - mol2 – second molecules. pymatgen Molecule object.

  as_dict()

    Get MSONable dict.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      MoleculeStructureComparator

  static get_13_bonds(priority_bonds)

    Get the 1-3 bonds implied by the given priority bonds.

    Parameters:

      priority_bonds (list[tuple]) – 12 bonds

    Returns:

      13 bonds

    Return type:

      tuple

  halogen_list = ('F', 'Cl', 'Br', 'I')
  ionic_element_list = ('Na', 'Mg', 'Al', 'Sc', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Rb', 'Sr')

## 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: NDArray) → 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: NDArray[np.float64], point_b: NDArray[np.float64], 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: NDArray[np.float64], to_a: NDArray[np.float64], r_a: NDArray[np.float64], from_b: NDArray[np.float64], to_b: NDArray[np.float64], r_b: NDArray[np.float64], 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: NDArray, angle: float, angle_in_radians: bool = False, translation_vec: Sequence[float] | NDArray = (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: Sequence[float] | NDArray, axis: Sequence[float] | NDArray, 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[np.float64]

    Apply the operation on a point.

    Parameters:

      point – Cartesian coordinate.

    Returns:

      Coordinates of point after operation.

  operate_multi(points: ArrayLike) → NDArray[np.float64]

    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: Sequence[float], angle: float, origin: Sequence[float] = (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 species 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 species 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(value)

  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 (kg/m³).

    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. For scalar, the unit may also be available:

        >>> hydrogen.atomic_radius_calculated
        0.53

        >>> hydrogen.atomic_radius_calculated.unit
        ang

  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.

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

  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 (kg/m³).

    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. For scalar, the unit may also be available:

        >>> hydrogen.atomic_radius_calculated
        0.53

        >>> hydrogen.atomic_radius_calculated.unit
        ang

  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.

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

    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: Literal['s', 'p', 'd', 'f']

    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.

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

    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 | float, 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(value)

  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: str, 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: str, 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.

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

    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 species 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 | float, 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: Literal[0, 1] = 0) → dict

    JSON-serializable dict representation of PeriodicSite.

    Parameters:

      verbosity (0 | 1) – 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[np.float64]

    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, NDArray[np.int_]]

    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, NDArray[np.int_]]

    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[np.float64]

    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 (NDArray) – 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: ArrayLike) → 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: ArrayLike, y: ArrayLike, *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] | 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[Self, Self]

  property center_of_mass: NDArray[np.float64]

    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) → IMolecule | Molecule

    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: tuple[int, int, int] = (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: PathLike = '', fmt: str = '') → str | None

    Outputs the molecule 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 “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: TypeAlias

    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: Literal[0, 1] = 1, fmt: Literal['abivars'] | None = None, **kwargs) → dict[str, Any]

    Dict representation of Structure.

    Parameters:

      - verbosity (0 | 1) – 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[np.float64]

    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_, 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: ArrayLike | 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: Sequence[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: ArrayLike | Lattice, species: Sequence[str | Element | Species | DummySpecies | Composition], coords: Sequence[ArrayLike], 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) → tuple[int, ...]

    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:

      tuple[int, …]

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

    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 an 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: Structure | IStructure, 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.core.structure_matcher.StructureMatcher.

    Returns:

      True if the structures are similar under some affine transformation.

    Return type:

      bool

  property pbc: tuple[bool, bool, bool]

    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 string (and to a file when filename is given).

    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 specified, it overrides whatever the filename is. Options include “cif”, “poscar”, “cssr”, “json”, “xsf”, “mcsqs”, “prismatic”, “yaml”, “yml”, “fleur-inpgen”, “pwmat”, “aims”. Case insensitive.

      - **kwargs – Kwargs pass thru to relevant methods. This allows the passing of parameters like symprec to the CifWriter.__init__ method for generation of symmetric CIFs.

    Returns:

      String representation of structure 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[CompositionLike], coords: Sequence[ArrayLike] | 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, min_distance: float | None = None, seed: int | None = None) → Self

    Perturbs the positions of sites by a random vector of specified distance and minimum distance. The perturbation is constrained within a norm range between min_distance and distance.

    Parameters:

      - distance – Maximum distance by which sites can be perturbed.

      - min_distance – Minimum distance for the perturbation range. Defaults to None, which means all perturbations are the same magnitude.

      - seed – The seed for the random number generator. Defaults to None.

    Returns:

      The perturbed 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.

  coords: NDArray
  classmethod from_dict(dct: dict) → Site

    Get a Neighbor from a dict.

    Parameters:

      dct – MSONable dict format.

    Returns:

      Neighbor

  index: int
  nn_distance: float
  properties: dict

class PeriodicNeighbor(species: Composition, coords: NDArray, lattice: Lattice, properties: dict | None = None, nn_distance: float = 0.0, index: int = 0, image: tuple[int, int, int] = (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 | 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[np.float64]

    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[np.float64]

    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.

  classmethod from_ase_atoms(atoms: Atoms, **kwargs) → Self

    Convert ase.Atoms to pymatgen (I)Structure/(I)Molecule.

    Parameters:

      - atoms (Atom) – ASE Atoms object

      - kwargs – Passed to AseAtomsAdaptor.get_structure.

    Returns:

      Self

  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: PathLike = '', fmt: FileFormats = '') → 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] | 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: `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

  calc_property(prop: str, calculator='TensorNet-MatPES-PBE-v2025.1-PES', **kwargs) → dict

    Calculate the specified material property using the provided calculation method or default calculator. This function dynamically maps the property to its corresponding calculation class and performs the computation.

    Parameters:

      - prop (str) – The material property to calculate. Expected values are “elastic”, “phonon”, or “eos”.

      - calculator (str, optional) – The specific calculator to use for the computation. Defaults to “TensorNet-MatPES-PBE-v2025.1-PES”.

      - kwargs – Additional keyword arguments passed to the calculation method.

    Returns:

      A dictionary containing the calculated results.

    Return type:

      dict

  calculate(calculator: str | Calculator = 'TensorNet-MatPES-PBE-v2025.1-PES', verbose: bool = False) → Calculator

    Perform an ASE calculation.

    Parameters:

      - calculator – An ASE Calculator or a string from the following options: “TensorNet-MatPES-PBE-v2025.1-PES”. Defaults to ‘TensorNet-MatPES-PBE-v2025.1-PES’ 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 = 0.0, seed: int | None = None) → Self

    Perturbs the positions of sites in the structure by translating each site by a random vector. The magnitude of the translation is determined by the specified distance and, optionally, a minimum distance.

    Parameters:

      - distance – The maximum distance for the translation of each site. The corresponding random vector’s magnitude will not exceed this distance.

      - min_distance – Minimum distance for the perturbation range. Defaults to None, which means all perturbations are the same magnitude.

      - seed – Seed for the random number generator to ensure reproducibility. If None (the default for numpy’s generator), the generator will be initialized without a specific seed.

    Returns:

      The updated object with perturbed site positions.

  relax(calculator: str | Calculator = 'TensorNet-MatPES-PBE-v2025.1-PES', 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: “TensorNet-MatPES-PBE-v2025.1-PES”. Defaults to ‘TensorNet-MatPES-PBE-v2025.1-PES’ 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.structure_analyzer module

This module provides classes to perform topological analyses of structures.

class OxideType(structure: Structure, relative_cutoff=1.1)

  Bases: `object`

  Separate class for determining oxide type.

  Parameters:

    - structure – Input structure.

    - relative_cutoff – Relative_cutoff * act. cutoff stipulates the max. distance two O atoms must be from each other. Default value is 1.1. At most 1.1 is recommended, nothing larger, otherwise the script cannot distinguish between superoxides and peroxides.

  parse_oxide() → tuple[str, int]

    Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide.

    Returns:

      Type of oxide (ozonide/peroxide/superoxide/hydroxide/None) and number of

        peroxide/superoxide/hydroxide bonds in structure.

    Return type:

      tuple[str, int]

class RelaxationAnalyzer(initial_structure: Structure, final_structure: Structure)

  Bases: `object`

  This class analyzes the relaxation in a calculation.

  Please note that the input and final structures should have the same ordering of sites. This is typically the case for most computational codes.

  Parameters:

    - initial_structure (Structure) – Initial input structure to calculation.

    - final_structure (Structure) – Final output structure from calculation.

  Raises:

    ValueError – If initial and final structures have different formulas.

  get_percentage_bond_dist_changes(max_radius: float = 3.0) → dict[int, dict[int, float]]

    Get the percentage bond distance changes for each site up to a maximum radius for nearest neighbors.

    Parameters:

      max_radius (float) – Maximum radius to search for nearest neighbors. This radius is applied to the initial structure, not the final structure.

    Returns:

      Bond distance changes in the form {index1: {index2: 0.011, …}}.

        For economy of representation, the index1 is always less than index2, i.e., since bonding between site1 and site_n is the same as bonding between site_n and site1, there is no reason to duplicate the information or computation.

    Return type:

      dict[int, dict[int, float]]

  get_percentage_lattice_parameter_changes() → dict[str, float]

    Get the percentage lattice parameter changes.

    Returns:

      Percent changes in lattice parameter, e.g.

        {‘a’: 0.012, ‘b’: 0.021, ‘c’: -0.031} implies a change of 1.2%, 2.1% and -3.1% in the a, b and c lattice parameters respectively.

    Return type:

      dict[str, float]

  get_percentage_volume_change() → float

    Get the percentage volume change.

    Returns:

      Volume change in percent. 0.055 means a 5.5% increase.

    Return type:

      float

class VoronoiAnalyzer(cutoff=5.0, qhull_options='Qbb Qc Qz')

  Bases: `object`

  Performs a statistical analysis of Voronoi polyhedra around each site. Each Voronoi polyhedron is described using Schaefli notation. That is a set of indices {c_i} where c_i is the number of faces with i number of vertices. E.g. for a bcc crystal, there is only one polyhedron notation of which is [0,6,0,8,0,0,…]. In perfect crystals, these also corresponds to the Wigner-Seitz cells. For distorted-crystals, liquids or amorphous structures, rather than one-type, there is a statistical distribution of polyhedra. See ref: Microstructure and its relaxation in Fe-B amorphous system simulated by molecular dynamics,

  > Stepanyuk et al., J. Non-cryst. Solids (1993), 159, 80-87.

  Parameters:

    - cutoff (float) – cutoff distance to search for neighbors of a given atom (default = 5.0)

    - qhull_options (str) – options to pass to qhull (optional).

  analyze(structure: Structure, n=0)

    Performs Voronoi analysis and returns the polyhedra around atom n in Schlaefli notation.

    Parameters:

      - structure (Structure) – structure to analyze

      - n (int) – index of the center atom in structure

    Returns:

      <c3,c4,c6,c6,c7,c8,c9,c10>

        where c_i denotes number of facets with i vertices.

    Return type:

      voronoi index of n

  analyze_structures(structures, step_freq=10, most_frequent_polyhedra=15)

    Perform Voronoi analysis on a list of Structures. Note that this might take a significant amount of time depending on the size and number of structures.

    Parameters:

      - structures (list) – list of Structures

      - (float (cutoff) – cutoff distance around an atom to search for neighbors

      - step_freq (int) – perform analysis every step_freq steps

      - qhull_options (str) – options to pass to qhull

      - most_frequent_polyhedra (int) – this many unique polyhedra with highest frequencies is stored.

    Returns:

      A list of tuples in the form (voronoi_index,frequency)

  static plot_vor_analysis(voronoi_ensemble: list[tuple[str, float]]) → Axes

    Plot the Voronoi analysis.

    Parameters:

      voronoi_ensemble (list[tuple[str, float]]) – List of tuples containing labels and values for Voronoi analysis.

    Returns:

      Matplotlib Axes object with the plotted Voronoi analysis.

    Return type:

      plt.Axes

class VoronoiConnectivity(structure: Structure, cutoff=10)

  Bases: `object`

  Computes the solid angles swept out by the shared face of the voronoi polyhedron between two sites.

  Parameters:

    - structure (Structure) – Input structure

    - cutoff (float) – Cutoff distance.

  property connectivity_array

    The connectivity array of shape [atom_i, atom_j, image_j]. atom_i is the index of the atom in the input structure. Since the second atom can be outside of the unit cell, it must be described by both an atom index and an image index. Array data is the solid angle of polygon between atom_i and image_j of atom_j.

  get_connections()

    Get a list of site pairs that are Voronoi Neighbors, along with their real-space distances.

  get_sitej(site_index, image_index)

    Assuming there is some value in the connectivity array at indices (1, 3, 12). site_i can be obtained directly from the input structure (structure[1]). site_j can be obtained by passing 3, 12 to this function.

    Parameters:

      - site_index (int) – index of the site (3 in the example)

      - image_index (int) – index of the image (12 in the example)

  property max_connectivity

    The 2d array [site_i, site_j] that represents the maximum connectivity of site i to any periodic image of site j.

average_coordination_number(structures, freq=10)

  Calculates the ensemble averaged Voronoi coordination numbers of a list of Structures using VoronoiNN. Typically used for analyzing the output of a Molecular Dynamics run.

  Parameters:

    - structures (list) – list of Structures.

    - freq (int) – sampling frequency of coordination number [every freq steps].

  Returns:

    Dictionary of elements as keys and average coordination numbers as values.

contains_peroxide(structure, relative_cutoff=1.1)

  Determines if a structure contains peroxide anions.

  Parameters:

    - structure (Structure) – Input structure.

    - relative_cutoff – The peroxide bond distance is 1.49 Angstrom. Relative_cutoff * 1.49 stipulates the maximum distance two O atoms must be to each other to be considered a peroxide.

  Returns:

    True if structure contains a peroxide anion.

  Return type:

    bool

get_max_bond_lengths(structure, el_radius_updates=None)

  Provides max bond length estimates for a structure based on the JMol table and algorithms.

  Parameters:

    - structure – (structure)

    - el_radius_updates – (dict) symbol->float to update atom_ic radii

  Returns:

    The two elements are ordered by Z.

  Return type:

    dict[(Element1, Element2)], float]

oxide_type(structure: Structure, relative_cutoff: float = 1.1, return_nbonds: bool = False) → str | tuple[str, int]

  Determines if an oxide is a peroxide/superoxide/ozonide/normal oxide.

  Parameters:

    - structure (Structure) – Input structure.

    - relative_cutoff (float) – Relative_cutoff * act. cutoff stipulates the max distance two O atoms must be from each other.

    - return_nbonds (bool) – Should number of bonds be requested?

solid_angle(center, coords)

  Helper method to calculate the solid angle of a set of coords from the center.

  Parameters:

    - center (3x1 array) – Center to measure solid angle from.

    - coords (Nx3 array) – List of coords to determine solid angle.

  Returns:

    The solid angle.

  Return type:

    float

sulfide_type(structure)

  Determines if a structure is a sulfide/polysulfide/sulfate.

  Parameters:

    structure (Structure) – Input structure.

  Returns:

    sulfide/polysulfide or None if structure is a sulfate.

  Return type:

    str

## pymatgen.core.structure_matcher module

This module provides classes to perform fitting of structures.

class AbstractComparator

  Bases: `MSONable`, `ABC`

  Abstract Comparator class. A Comparator defines how sites are compared in a structure.

  abstractmethod are_equal(sp1, sp2) → bool

    Defines how the species of two sites are considered equal. For example, one can consider sites to have the same species only when the species are exactly the same, i.e., Fe2+ matches Fe2+ but not Fe3+. Or one can define that only the element matters, and all oxidation state information are ignored.

    Parameters:

      - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

      - sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

    Returns:

      True if species are considered equal.

    Return type:

      bool

  as_dict()

    MSONable dict.

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      Comparator.

  abstractmethod get_hash(composition)

    Defines a hash to group structures. This allows structures to be grouped efficiently for comparison. The hash must be invariant under supercell creation. (e.g. composition is not a good hash, but fractional_composition might be). Reduced formula is not a good formula, due to weird behavior with fractional occupancy.

    Composition is used here instead of structure because for anonymous matches it is much quicker to apply a substitution to a composition object than a structure object.

    Parameters:

      composition (Composition) – composition of the structure

    Returns:

      A hashable object. Examples can be string formulas, integers etc.

class ElementComparator

  Bases: `AbstractComparator`

  A Comparator that matches elements. i.e. oxidation states are ignored.

  are_equal(sp1, sp2) → bool

    True if element:amounts are exactly the same, i.e., oxidation state is not considered.

    Parameters:

      - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

      - sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

    Returns:

      True if species are the same based on element and amounts.

    Return type:

      bool

  get_hash(composition)

    Get the fractional element composition.

class FrameworkComparator

  Bases: `AbstractComparator`

  A Comparator that matches sites, regardless of species.

  are_equal(sp1, sp2) → bool

    True if there are atoms on both sites.

    Parameters:

      - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

      - sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

    Returns:

      True always

  get_hash(composition)

    No hash possible.

class OccupancyComparator

  Bases: `AbstractComparator`

  A Comparator that matches occupancies on sites, irrespective of the species of those sites.

  are_equal(sp1, sp2) → bool
    Parameters:

      - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

      - sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

    Returns:

      True if sets of occupancies (amt) are equal on both sites.

    Return type:

      bool

  get_hash(composition)
    Parameters:

      composition – Composition.

    TODO: might need a proper hash method

    Returns:

      1. Difficult to define sensible hash

class OrderDisorderElementComparator

  Bases: `AbstractComparator`

  A Comparator that matches sites, given some overlap in the element composition.

  are_equal(sp1, sp2) → bool

    True if there is some overlap in composition between the species.

    Parameters:

      - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

      - sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

    Returns:

      True always

  get_hash(composition)

    Get the fractional composition.

class SiteOrderedIStructure(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: `IStructure`

  Imutable structure where the order of sites matters.

  In caching reduced structures (see StructureMatcher._get_reduced_structure) the order of input sites can be important. In general, the order of sites in a structure does not matter, but when a method like StructureMatcher.get_s2_like_s1 tries to put s2’s sites in the same order as s1, the site order matters.

  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.

class SpeciesComparator

  Bases: `AbstractComparator`

  A Comparator that matches species exactly. The default used in StructureMatcher.

  are_equal(sp1, sp2) → bool

    True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+.

    Parameters:

      - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

      - sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

    Returns:

      True if species are equal.

    Return type:

      bool

  get_hash(composition: Composition)

    Get the fractional composition.

class SpinComparator

  Bases: `AbstractComparator`

  A Comparator that matches magnetic structures to their inverse spins. This comparator is primarily used to filter magnetically ordered structures with opposite spins, which are equivalent.

  are_equal(sp1, sp2) → bool

    True if species are exactly the same, i.e., Fe2+ == Fe2+ but not Fe3+. and the spins are reversed. i.e., spin up maps to spin down, and vice versa.

    Parameters:

      - sp1 – First species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

      - sp2 – Second species. A dict of {specie/element: amt} as per the definition in Site and PeriodicSite.

    Returns:

      True if species are equal.

    Return type:

      bool

  get_hash(composition)

    Get the fractional composition.

class StructureMatcher(ltol: float = 0.2, stol: float = 0.3, angle_tol: float = 5, primitive_cell: bool = True, scale: bool = True, attempt_supercell: bool = False, allow_subset: bool = False, comparator: AbstractComparator | None = None, supercell_size: Literal['num_sites', 'num_atoms', 'volume'] = 'num_sites', ignored_species: Sequence[SpeciesLike] = ())

  Bases: `MSONable`

  Match structures by similarity.

  Algorithm: 1. Given two structures: s1 and s2 2. Optional: Reduce to primitive cells. 3. If the number of sites do not match, return False 4. Reduce to s1 and s2 to Niggli Cells 5. Optional: Scale s1 and s2 to same volume. 6. Optional: Remove oxidation states associated with sites 7. Find all possible lattice vectors for s2 within shell of ltol. 8. For s1, translate an atom in the smallest set to the origin 9. For s2: find all valid lattices from permutations of the list

  > of lattice vectors (invalid if: det(Lattice Matrix) < half volume of original s2 lattice)

  10. For each valid lattice:

      1. If the lattice angles of are within tolerance of s1, basis change s2 into new lattice.

      2. For each atom in the smallest set of s2:

         > i. Translate to origin and compare fractional sites in structure within a fractional tolerance. ii. If true:

         > > ia. Convert both lattices to Cartesian and place both structures on an average lattice ib. Compute and return the average and max rms displacement between the two structures normalized by the average free length per atom

         > > if fit function called:

         > >   if normalized max rms displacement is less than stol. Return True

         > > if get_rms_dist function called:

         > >   if normalized average rms displacement is less than the stored rms displacement, store and continue. (This function will search all possible lattices for the smallest average rms displacement between the two structures)

  Parameters:

    - ltol (float) – Fractional length tolerance. Default is 0.2.

    - stol (float) – Site tolerance. Defined as the fraction of the average free length per atom := ( V / Nsites ) ** (1/3) Default is 0.3.

    - angle_tol (float) – Angle tolerance in degrees. Default is 5 degrees.

    - primitive_cell (bool) – If true: input structures will be reduced to primitive cells prior to matching. Default to True.

    - scale (bool) – Input structures are scaled to equivalent volume if true; For exact matching, set to False.

    - attempt_supercell (bool) – If set to True and number of sites in cells differ after a primitive cell reduction (divisible by an integer) attempts to generate a supercell transformation of the smaller cell which is equivalent to the larger structure.

    - allow_subset (bool) – Allow one structure to match to the subset of another structure. Eg. Matching of an ordered structure onto a disordered one, or matching a delithiated to a lithiated structure. This option cannot be combined with attempt_supercell, or with structure grouping.

    - comparator (Comparator) –

      A comparator object implementing an equals method that declares equivalency of sites. Default is SpeciesComparator, which implies rigid species mapping, i.e., Fe2+ only matches Fe2+ and not Fe3+.

      Other comparators are provided, e.g. ElementComparator which matches only the elements and not the species.

      The reason why a comparator object is used instead of supplying a comparison function is that it is not possible to pickle a function, which makes it otherwise difficult to use StructureMatcher with Python’s multiprocessing.

    - supercell_size (str or list) – Method to use for determining the size of a supercell (if applicable). Possible values are ‘num_sites’, ‘num_atoms’, ‘volume’, or an element or list of elements present in both structures.

    - ignored_species (list) – A list of ions to be ignored in matching. Useful for matching structures that have similar frameworks except for certain ions, e.g. Li-ion intercalation frameworks. This is more useful than allow_subset because it allows better control over what species are ignored in the matching.

  as_dict()

    MSONable dict.

  fit(struct1: Structure | IStructure, struct2: Structure | IStructure, symmetric: bool = False, skip_structure_reduction: bool = False) → bool

    Fit two structures.

    Parameters:

      - struct1 (Structure | IStructure) – 1st structure

      - struct2 (Structure | IStructure) – 2nd structure

      - symmetric (bool) – Defaults to False If True, check the equality both ways. This only impacts a small percentage of structures

      - skip_structure_reduction (bool) – Defaults to False If True, skip to get a primitive structure and perform Niggli reduction for struct1 and struct2

    Returns:

      True if the structures are equivalent

    Return type:

      bool

  fit_anonymous(struct1: Structure | IStructure, struct2: Structure | IStructure, niggli: bool = True, skip_structure_reduction: bool = False) → bool

    Performs an anonymous fitting, which allows distinct species in one structure to map to another. e.g. to compare if the Li2O and Na2O structures are similar.

    Parameters:

      - struct1 (Structure) – 1st structure

      - struct2 (Structure) – 2nd structure

      - niggli (bool) – If true, perform Niggli reduction for struct1 and struct2

      - skip_structure_reduction (bool) – Defaults to False If True, skip to get a primitive structure and perform Niggli reduction for struct1 and struct2

    Returns:

      True if a species mapping can map struct1 to struct2

    Return type:

      bool

  classmethod from_dict(dct: dict) → Self
    Parameters:

      dct (dict) – Dict representation.

    Returns:

      StructureMatcher

  get_all_anonymous_mappings(struct1, struct2, niggli=True, include_dist=False)

    Performs an anonymous fitting, which allows distinct species in one structure to map to another. Returns a dictionary of species substitutions that are within tolerance.

    Parameters:

      - struct1 (Structure) – 1st structure

      - struct2 (Structure) – 2nd structure

      - niggli (bool) – Find niggli cell in preprocessing

      - include_dist (bool) – Return the maximin distance with each mapping

    Returns:

      list of species mappings that map struct1 to struct2.

  get_best_electronegativity_anonymous_mapping(struct1: Structure | IStructure, struct2: Structure | IStructure) → dict | None

    Performs an anonymous fitting, which allows distinct species in one structure to map to another. e.g. to compare if the Li2O and Na2O structures are similar. If multiple substitutions are within tolerance this will return the one which minimizes the difference in electronegativity between the matches species.

    Parameters:

      - struct1 (Structure) – 1st structure

      - struct2 (Structure) – 2nd structure

    Returns:

      Mapping of struct1 species to struct2 species.

    Return type:

      dict[Element, Element] | None

  get_mapping(superset, subset)

    Calculate the mapping from superset to subset.

    Parameters:

      - superset (Structure) – Structure containing at least the sites in subset (within the structure matching tolerance)

      - subset (Structure) – Structure containing some of the sites in superset (within the structure matching tolerance)

    Returns:

      numpy array such that superset.sites[mapping] is within matching tolerance of subset.sites or None if no such mapping is possible

  get_rms_anonymous(struct1, struct2)

    Performs an anonymous fitting, which allows distinct species in one structure to map to another. e.g. to compare if the Li2O and Na2O structures are similar.

    Parameters:

      - struct1 (Structure) – 1st structure

      - struct2 (Structure) – 2nd structure

    Returns:

      1st element is min_rms, 2nd is min_mapping.

        min_rms is the minimum RMS distance, and min_mapping is the corresponding minimal species mapping that would map struct1 to struct2. (None, None) is returned if the minimax_rms exceeds the threshold.

    Return type:

      tuple[float, float] | tuple[None, None]

  get_rms_dist(struct1, struct2)

    Calculate RMS displacement between two structures.

    Parameters:

      - struct1 (Structure) – 1st structure

      - struct2 (Structure) – 2nd structure

    Returns:

      rms displacement normalized by (Vol / nsites) ** (1/3) and maximum distance between paired sites. If no matching lattice is found None is returned.

  get_s2_like_s1(struct1, struct2, include_ignored_species=True)

    Performs transformations on struct2 to put it in a basis similar to struct1 (without changing any of the inter-site distances).

    Parameters:

      - struct1 (Structure) – Reference structure

      - struct2 (Structure) – Structure to transform.

      - include_ignored_species (bool) – Defaults to True, the ignored_species is also transformed to the struct1 lattice orientation, though obviously there is no direct matching to existing sites.

    Returns:

      A structure object similar to struct1, obtained by making a supercell, sorting, and translating struct2.

  get_supercell_matrix(supercell, struct) → ndarray | None

    Get the matrix for transforming struct to supercell. This can be used for very distorted ‘supercells’ where the primitive cell is impossible to find.

  get_transformation(struct1, struct2)

    Get the supercell transformation, fractional translation vector, and a mapping to transform struct2 to be similar to struct1.

    Parameters:

      - struct1 (Structure) – Reference structure

      - struct2 (Structure) – Structure to transform.

    Returns:

      supercell matrix vector (np.array(3)): fractional translation vector mapping (list[int | None]):

      > The first len(struct1) items of the mapping vector are the indices of struct1’s corresponding sites in struct2 (or None if there is no corresponding site), and the other items are the remaining site indices of struct2.

    Return type:

      supercell (np.array(3, 3))

  group_structures(s_list, anonymous=False)

    Given a list of structures, use fit to group them by structural equality.

    Parameters:

      - s_list ([Structure]) – List of structures to be grouped

      - anonymous (bool) – Whether to use anonymous mode.

    Returns:

      A list of lists of matched structures Assumption: if s1 == s2 but s1 != s3, than s2 and s3 will be put in different groups without comparison.

get_linear_assignment_solution(cost_matrix: ndarray)

  Wrapper for SciPy’s linear_sum_assignment.

  Parameters:

    cost_matrix – The cost matrix of the problem. cost[i,j] should be the cost of matching x[i] to y[j]. The cost matrix may be rectangular

  Returns:

    The minimum cost of the matching. solution: The matching of the rows to columns. i.e solution = [1, 2, 0]

    > would match row 0 to column 1, row 1 to column 2 and row 2 to column 0. Total cost would be c[0, 1] + c[1, 2] + c[2, 0].

  Return type:

    min_cost

## 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 | IStructure, 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, species: Sequence[Any], coords: NDArray[np.float64], miller_index: tuple[int, ...], oriented_unit_cell: Structure | IStructure, shift: float, scale_factor: NDArray[np.float64], 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 (tuple[int, ...]) – 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: NDArray[np.float64], cartesian: bool = False) → NDArray[np.float64]

    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: NDArray[np.float64], 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 (NDArray[np.float_]) – 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 | IStructure, miller_index: tuple[int, ...], 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 | IStructure, 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 | IStructure, 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 | IStructure, 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: ndarray, miller_index: tuple[int, ...]) → tuple[int, int, int]

  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 (tuple[int, ...]) – 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) → tuple[int, int, int]

  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[np.float64], vscale: NDArray[np.float64] | 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: list[NDArray[np.float64]], einsum_string: str | None = None) → NDArray[np.float64]

    Performs a tensor contraction using the Einstein summation convention. The function either uses a provided Einstein summation notation (`einsum_string`) or generates one based on the dimensions of the arrays involved.

    Parameters:

      - other_arrays – A sequence of NumPy arrays to be included in the Einstein summation operation.

      - einsum_string – An optional string representing the Einstein summation notation. If not provided, it will be auto-generated based on the ranks of the involved arrays.

    Returns:

      Resultant NumPy array after performing the Einstein summation operation.

  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[np.float64]) → 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[np.float64]]

    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[np.float64]) → NDArray[np.float64]

    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[np.float64]

    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[np.float64]]

    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[np.float64]) → NDArray[np.float64]

  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[tuple[float, float, float]]] | np.ndarray | list[np.ndarray], charge: float | None = None, spin_multiplicity: float | None = None, lattice: Lattice | list[Lattice] | list[np.ndarray] | 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[tuple[float, float, float]]] | 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 | Trajectory

    Get molecule at specified index.

    Parameters:

      idx – Index of molecule.

    Returns:

      A pymatgen Molecule object.

  get_structure(idx: int) → Structure | Trajectory

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

    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: ArrayLike, unit: str | Unit | None, 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
      >>> energy_arr_c
      [1.03674933 2.07349865] Ha
      >>> energy_arr_c.to("eV")
      [28.21138625 56.42277249] eV

  Override __new__.

  property as_base_units: Self

    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[str, dict[str, float]]

    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”) [27.21138625 29.93252487] 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
        >>> 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: Self

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

  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[str, float], 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: str)

  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`