# pymatgen.analysis.defects.utils module

Utilities for defects module.

class ChargeDensityAnalyzer(chgcar)

  Bases: `monty.json.MSONable`

  Analyzer to find potential interstitial sites based on charge density. The total charge density is used.

  Initialization.

  Parameters

    chgcar (pmg.Chgcar) – input Chgcar object.

  property charge_distribution_df

    Charge distribution.

    Type

      return

  cluster_nodes(tol=0.2)

    Cluster nodes that are too close together using a tol.

    Parameters

      tol (float) – A distance tolerance. PBC is taken into account.

  property extrema_df

    The extrema in charge density.

    Type

      return

  classmethod from_file(chgcar_filename)

    Init from a CHGCAR.

    Parameters

      chgcar_filename –

    Returns

  get_local_extrema(find_min=True, threshold_frac=None, threshold_abs=None)

    Get all local extrema fractional coordinates in charge density, searching for local minimum by default. Note that sites are NOT grouped symmetrically.

    Parameters

      - find_min (bool) – True to find local minimum else maximum, otherwise find local maximum.

      - threshold_frac (float) –

        optional fraction of extrema shown, which returns threshold_frac * tot_num_extrema extrema fractional coordinates based on highest/lowest intensity.

        E.g. set 0.2 to show the extrema with 20% highest or lowest intensity. Value range: 0 <= threshold_frac <= 1

        Note that threshold_abs and threshold_frac should not set in the same time.

      - threshold_abs (float) –

        optional filter. When searching for local minima, intensity <= threshold_abs returns; when searching for local maxima, intensity >= threshold_abs returns.

        Note that threshold_abs and threshold_frac should not set in the same time.

    Returns

      list of fractional coordinates corresponding

        to local extrema.

    Return type

      extrema_coords (list)

  get_structure_with_nodes(find_min=True, min_dist=0.5, tol=0.2, threshold_frac=None, threshold_abs=None)

    Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecies X.

    Parameters

      - find_min (bool) – True to find local minimum else maximum, otherwise find local maximum.

      - min_dist (float) – The minimum distance (in Angstrom) that a predicted site needs to be from existing atoms. A min_dist with value <= 0 returns all sites without distance checking.

      - tol (float) – A distance tolerance of nodes clustering that sites too closed to other predicted sites will be merged. PBC is taken into account.

      - threshold_frac (float) –

        optional fraction of extrema, which returns threshold_frac * tot_num_extrema extrema fractional coordinates based on highest/lowest intensity.

        E.g. set 0.2 to insert DummySpecies atom at the extrema with 20% highest or lowest intensity. Value range: 0 <= threshold_frac <= 1

        Note that threshold_abs and threshold_frac should not set in the same time.

      - threshold_abs (float) –

        optional filter. When searching for local minima, intensity <= threshold_abs returns; when searching for local maxima, intensity >= threshold_abs returns.

        Note that threshold_abs and threshold_frac should not set in the same time.

    Returns

      structure (Structure)

  remove_collisions(min_dist=0.5)

    Remove predicted sites that are too close to existing atoms in the structure.

    Parameters

      min_dist (float) – The minimum distance (in Angstrom) that a predicted site needs to be from existing atoms. A min_dist with value <= 0 returns all sites without distance checking.

  sort_sites_by_integrated_chg(r=0.4)

    Get the average charge density around each local minima in the charge density and store the result in _extrema_df :param r: radius of sphere around each site to evaluate the average :type r: float

class ChargeInsertionAnalyzer(chgcar, working_ion='Li', avg_radius=0.4, max_avg_charge=1.0, clustering_tol=0.6, ltol=0.2, stol=0.3, angle_tol=5)

  Bases: `pymatgen.analysis.defects.utils.ChargeDensityAnalyzer`

  Analyze the charge density and create new candidate structures by inserting at each charge minima The similar inserterd structures are given the same uniqueness label. This works best with AECCAR data since CHGCAR data often contains spurious local minima in the core. However you can still use CHGCAR with an appropriate max_avg_charge value.

  Application of this for Li can be found at: J.-X. Shen et al.: npj Comput. Mater. 6, 1 (2020) https://www.nature.com/articles/s41524-020-00422-3

  Parameters

    - chgcar – The charge density object to analyze

    - working_ion – The working ion to be inserted

    - avg_radius – The radius used to calculate average charge density at each site

    - max_avg_charge – Do no consider local minmas with avg charge above this value.

    - clustering_tol – Distance tolerance for grouping sites together

    - ltol – StructureMatcher ltol parameter

    - stol – StructureMatcher stol parameter

    - angle_tol – StructureMatcher angle_tol parameter

  get_labels()

    Populate the extrema dataframe (self._extrema_df) with the insertion structure. Then, group the sites by structure similarity. Finally store a full list of the insertion sites, with their labels as a Structure Object

class QModel(beta=1.0, expnorm=0.0, gamma=1.0)

  Bases: `monty.json.MSONable`

  Model for the defect charge distribution. A combination of exponential tail and gaussian distribution is used (see Freysoldt (2011), DOI: 10.1002/pssb.201046289 ) q_model(r) = q [x exp(-r/gamma) + (1-x) exp(-r^2/beta^2)]

  > without normalization constants

  By default, gaussian distribution with 1 Bohr width is assumed. If defect charge is more delocalized, exponential tail is suggested.

  Parameters

    - beta – Gaussian decay constant. Default value is 1 Bohr. When delocalized (eg. diamond), 2 Bohr is more appropriate.

    - expnorm – Weight for the exponential tail in the range of [0-1]. Default is 0.0 indicating no tail . For delocalized charges ideal value is around 0.54-0.6.

    - gamma – Exponential decay constant

  rho_rec(g2)

    Reciprocal space model charge value for input squared reciprocal vector. :param g2: Square of reciprocal vector

    Returns

      Charge density at the reciprocal vector magnitude

  property rho_rec_limit0

    Reciprocal space model charge value close to reciprocal vector 0 . rho_rec(g->0) -> 1 + rho_rec_limit0 * g^2

class StructureMotifInterstitial(struct, inter_elem, motif_types=('tetrahedral', 'octahedral'), op_threshs=(0.3, 0.5), dl=0.2, doverlap=1, facmaxdl=1.01, verbose=False)

  Bases: `object`

  Generate interstitial sites at positions where the interstitialcy is coordinated by nearest neighbors in a way that resembles basic structure motifs (e.g., tetrahedra, octahedra). The algorithm is called InFiT (Interstitialcy Finding Tool), it was introducted by Nils E. R. Zimmermann, Matthew K. Horton, Anubhav Jain, and Maciej Haranczyk (Front. Mater., 4, 34, 2017), and it is used by the Python Charged Defect Toolkit (PyCDT: D. Broberg et al., Comput. Phys. Commun., in press, 2018).

  Generates symmetrically distinct interstitial sites at positions where the interstitial is coordinated by nearest neighbors in a pattern that resembles a supported structure motif (e.g., tetrahedra, octahedra).

  Parameters

    - struct (Structure) – input structure for which symmetrically distinct interstitial sites are to be found.

    - inter_elem (string) – element symbol of desired interstitial.

    - motif_types ([string]) – list of structure motif types that are to be considered. Permissible types are: tet (tetrahedron), oct (octahedron).

    - op_threshs ([float]) – threshold values for the underlying order parameters to still recognize a given structural motif (i.e., for an OP value >= threshold the coordination pattern match is positive, for OP < threshold the match is negative.

    - dl (float) – grid fineness in Angstrom. The input structure is divided into a grid of dimension a/dl x b/dl x c/dl along the three crystallographic directions, with a, b, and c being the lengths of the three lattice vectors of the input unit cell.

    - doverlap (float) – distance that is considered to flag an overlap between any trial interstitial site and a host atom.

    - facmaxdl (float) – factor to be multiplied with the maximum grid width that is then used as a cutoff distance for the clustering prune step.

    - verbose (bool) – flag indicating whether (True) or not (False; default) to print additional information to screen.

  enumerate_defectsites()

    Get all defect sites.

    Returns

      list of periodic sites

        representing the interstitials.

    Return type

      defect_sites ([PeriodicSite])

  get_coordinating_elements_cns(i)

    Get element-specific coordination numbers of defect with index i.

    Returns

      dictionary storing the coordination numbers (int)

        with string representation of elements as keys. (i.e., {elem1 (string): cn1 (int), …}).

    Return type

      elem_cn (dict)

  get_defectsite_multiplicity(n)

    Returns the symmtric multiplicity of the defect site at the index.

  get_motif_type(i)

    Get the motif type of defect with index i (e.g., “tet”).

    Returns

      motif type.

    Return type

      motif (string)

  get_op_value(i)

    Get order-parameter value of defect with index i.

    Returns

      OP value.

    Return type

      opval (float)

  make_supercells_with_defects(scaling_matrix)

    Generate a sequence of supercells in which each supercell contains a single interstitial, except for the first supercell in the sequence which is a copy of the defect-free input structure.

    Parameters

      scaling_matrix (3x3 integer array) – scaling matrix to transform the lattice vectors.

    Returns

      sequence of supercells.

    Return type

      scs ([Structure])

class TopographyAnalyzer(structure, framework_ions, cations, tol=0.0001, max_cell_range=1, check_volume=True, constrained_c_frac=0.5, thickness=0.5)

  Bases: `object`

  This is a generalized module to perform topological analyses of a crystal structure using Voronoi tessellations. It can be used for finding potential interstitial sites. Applications including using these sites for inserting additional atoms or for analyzing diffusion pathways.

  Note that you typically want to do some preliminary postprocessing after the initial construction. The initial construction will create a lot of points, especially for determining potential insertion sites. Some helper methods are available to perform aggregation and elimination of nodes. A typical use is something like:

      a = TopographyAnalyzer(structure, ["O"], ["P"])
      a.cluster_nodes()
      a.remove_collisions()

  Init.

  Parameters

    - structure (Structure) – An initial structure.

    - framework_ions ([str]) – A list of ions to be considered as a framework. Typically, this would be all anion species. E.g., [“O”, “S”].

    - cations ([str]) – A list of ions to be considered as non-migrating cations. E.g., if you are looking at Li3PS4 as a Li conductor, Li is a mobile species. Your cations should be [ “P”]. The cations are used to exclude polyhedra from diffusion analysis since those polyhedra are already occupied.

    - tol (float) – A tolerance distance for the analysis, used to determine if something are actually periodic boundary images of each other. Default is usually fine.

    - max_cell_range (int) – This is the range of periodic images to construct the Voronoi tesselation. A value of 1 means that we include all points from (x +- 1, y +- 1, z+- 1) in the voronoi construction. This is because the Voronoi poly extends beyond the standard unit cell because of PBC. Typically, the default value of 1 works fine for most structures and is fast. But for really small unit cells with high symmetry, you may need to increase this to 2 or higher.

    - check_volume (bool) – Set False when ValueError always happen after tuning tolerance.

    - constrained_c_frac (float) – Constraint the region where users want to do Topology analysis the default value is 0.5, which is the fractional coordinate of the cell

    - thickness (float) – Along with constrained_c_frac, limit the thickness of the regions where we want to explore. Default is 0.5, which is mapping all the site of the unit cell.

  analyze_symmetry(tol)
    Parameters

      tol – Tolerance for SpaceGroupAnalyzer

    Returns

      List

  check_volume()

    Basic check for volume of all voronoi poly sum to unit cell volume Note that this does not apply after poly combination.

  cluster_nodes(tol=0.2)

    Cluster nodes that are too close together using a tol.

    Parameters

      tol (float) – A distance tolerance. PBC is taken into account.

  get_structure_with_nodes()

    Get the modified structure with the voronoi nodes inserted. The species is set as a DummySpecies X.

  print_stats()

    Print stats such as the MSE dist.

  remove_collisions(min_dist=0.5)

    Remove vnodes that are too close to existing atoms in the structure

    Parameters

      min_dist (float) – The minimum distance that a vertex needs to be from existing atoms.

  vtk()

    Show VTK visualization.

  write_topology(fname='Topo.cif')

    Write topology to a file.

    Parameters

      fname – Filename

class VoronoiPolyhedron(lattice, frac_coords, polyhedron_indices, all_coords, name=None)

  Bases: `object`

  Convenience container for a voronoi point in PBC and its associated polyhedron.

  Parameters

    - lattice –

    - frac_coords –

    - polyhedron_indices –

    - all_coords –

    - name –

  property coordination

    Coordination number

    Type

      return

  is_image(poly, tol)
    Parameters

      - poly – VoronoiPolyhedron

      - tol – Coordinate tolerance.

    Returns

      Whether a poly is an image of the current one.

  property volume

    Volume

    Type

      return

calculate_vol(coords)

  Calculate volume given a set of coords.

  Parameters

    coords – List of coords.

  Returns

    Volume

closestsites(struct_blk, struct_def, pos)

  Returns closest site to the input position for both bulk and defect structures :param struct_blk: Bulk structure :param struct_def: Defect structure :param pos: Position

  Return: (site object, dist, index)

converge(f, step, tol, max_h)

  simple newton iteration based convergence function

eV_to_k(energy)

  Convert energy to reciprocal vector magnitude k via hbar*k^2/2m :param a: Energy in eV.

  Returns

    (double) Reciprocal vector magnitude (units of 1/Bohr).

generate_R_and_G_vecs(gamma, prec_set, lattice, epsilon)

  This returns a set of real and reciprocal lattice vectors (and real/recip summation values) based on a list of precision values (prec_set)

  gamma (float): Ewald parameter prec_set (list or number): for prec values to consider (20, 25, 30 are sensible numbers) lattice: Lattice object of supercell in question

generate_reciprocal_vectors_squared(a1, a2, a3, encut)

  Generate reciprocal vector magnitudes within the cutoff along the specied lattice vectors. :param a1: Lattice vector a (in Bohrs) :param a2: Lattice vector b (in Bohrs) :param a3: Lattice vector c (in Bohrs) :param encut: Reciprocal vector energy cutoff

  Returns

    [[g1^2], [g2^2], …] Square of reciprocal vectors (1/Bohr)^2 determined by a1, a2, a3 and whose magntidue is less than gcut^2.

generic_groupby(list_in, comp=<built-in function eq>)

  Group a list of unsortable objects :param list_in: A list of generic objects :param comp: (Default value = operator.eq) The comparator

  Returns

    [int] list of labels for the input list

genrecip(a1, a2, a3, encut)
  Parameters

    - a1 – lattice vectors in bohr

    - a2 – lattice vectors in bohr

    - a3 – lattice vectors in bohr

    - encut – energy cut off in eV

  Returns

    reciprocal lattice vectors with energy less than encut

tune_for_gamma(lattice, epsilon)

  This tunes the gamma parameter for Kumagai anisotropic Ewald calculation. Method is to find a gamma parameter which generates a similar number of reciprocal and real lattice vectors, given the suggested cut off radii by Kumagai and Oba