Utils

This module contains utility functions used across the package and which may be useful also for external applications.

class clusterx.utils.Exponential(exponent, coefficient=1)

Basic exponential object of type coefficient * x ^ exponent. Numerically evaluated using the method evaluate ( x ) .

Parameters:
exponent

exponent of the exponential

coefficient

coefficient of the exponential

class clusterx.utils.ListDict

Datastructure that allows efficient (O(1)) insert, remove and random sampling. Adapted from https://stackoverflow.com/questions/15993447/python-data-structure-for-efficient-add-remove-and-random-choice.

class clusterx.utils.PolynomialBasis(max_order=10, symmetric=False)

Polynomial basis, constructed from several PolynomialFunction(). Constructs orthonormal basis sets using scalcar_product . When initialized, all orthonormal basis sets to the order max_order are generated.

Parameters:
max_order

Maximal order to which the basis set is initialized.

symmetric

Defines if the scalar product uses sigmas symmetrized around 0 or ascending from 0.

scalar_product(function1, function2, m)

returns the result of the scalar product 1/m sum_{sigma} f_1(sigma) * f_2(sigma)

class clusterx.utils.PolynomialFunction

Polynomial function, build from Exponential() .

class clusterx.utils.SuperCellIndexSearcher(positions_scell)

Does the job of get_cl_idx_sc more efficiently by using a KDTree. This is useful for large supercells.

get_cluster_indices(positions_cluster, tol=0.001)

Return atom indexes of cluster points in SuperCell

Parameters:
positions_clusternpoints x 3 matrix

matrix of cartesian coordinates of cluster points. Cluster positions are expected to be wrapped inside supercell sc

tolreal positive number

tolerance to determine whether cluster and atom positions are the same.

exception clusterx.utils.SupercellError
clusterx.utils.add_noise(v, noise_level)

Add randomly distributed noise to vector coordinates

To each coordinate of the input vector v, random noise uniformly distributed between -noise_level and noise_level is added. The input vector v is left unchanged. The modified vector is returned.

Parameters:
vlist of floats

The input vector

noise_levelfloat

Width of the uniform distribution used to add noise.

clusterx.utils.atat_to_cell(file_path='lat.in', interpret_as='parent_lattice', parent_lattice=None, pbc=None, wrap=True)

Parse a lat.in or str.out file from ATAT.

ATAT users may use the input files from ATAT to perform a cluster expansion with CELL. This function allows to convert an input lat.in file from ATAT to a ParentLattice object in CELL. One may also read str.out files, which are converted to Structure objects in CELL.

Parameters:
file_pathstr

string containing the path of the file to be parsed. The file must have format corresponding to a lat.in or str.out file from ATAT.

interpret_asstr or None

Indicate how to interpret the file in file_path. Possible values are:

  • None:

    Three arrays are returned: cell, r, and species.

  • parent_lattice:

    The recommended value if file_path corresponds to a lat.in input file from ATAT. A ParentLattice CELL object will be returned.

  • super_cell:

    The recommended value if file_path corresponds to a lat.in file with a matrix of lattice vectors (u,v,w in ATAT doc) different to the identity, or if it is known that the structure is a periodic repetition of a parent lattice. For this option, the parent lattice must be provided (see parent_lattice parameter below). A SuperCell object will be returned.

  • structure:

    The recommended value if file_path corresponds to a str.out file from ATAT. For this option, the parent lattice must be provided (see parent_lattice parameter below). In this case a Structure object will be returned.

parent_latticeParentLattice

If interpret_as is super_cell or structure, a parent lattice must be provided. This must be compatible with the information in the lat.in file that was used to create the str.out files. See the examples below.

pbcone or three bool (same as ASE’s Atoms)

Periodic boundary conditions flags. Examples: True, False, 0, 1, (1, 1, 0), (True, False, False). Default value: False. The returned CELL objects will have these pbc’s set up.

wrapbool, default True

Wrap atomic coordinates. If pbc is None, pbc is set to (1,1,1). Set wrap to False if structure corresponds to a supercell, i.e., if the second matrix of the structure definition in either the lat.in or str.out file is different from the identity matrix.

Returns:
object

Depending on the value of interpret_as, the returned object can be python arrays (interpret_as=None), a ParentLattice (interpret_as="parent_lattice"), a SuperCell (interpret_as="super_cell"), or a Structure (interpret_as="Structure").

Examples

clusterx.utils.atoms_equivalence_check(atoms, to_primitive=True, pretty_print=False)

Find equivalent structures in an array of Atoms objects

Equivalence is determined in terms of symmetry between structures

The SymmetryEquivalenceCheck tool of ASE <https://wiki.fysik.dtu.dk/ase/ase/utils.html#ase.utils.structure_comparator.SymmetryEquivalenceCheck>`_ is used.

Parameters:
atomsarray of Atoms objects

The structures to be analyzed.

to_primitivebool, default True

If True the structures are reduced to their primitive cells. This feature requires spglib to installed (cf. ASE’s SymmetryEquivalenceCheck)

Returns:
dict

Returns a dictionary. The keys (k) are structure indices of unique representative structures, and the values (v) are arrays of integer, indicating all structure indices equivalent to k (containing k itself too). For instance, the dictionary:

{"0": [0, 1, 3, 8, 9],
 "2": [2, 5, 6],
 "4": [4, 7]}
indicates that in the structures set with indices [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] there are just three distinct structures. These can be represented by strucutres 0, 2 and 4. The structures [0, 1, 3, 8, 9] are all equivalent, etc.
Notice that here equivalence is used in the sense explained above: It is symmetrical equivalence only if cpool and comat are None.
clusterx.utils.calculate_trafo_matrix(pcell, scell, rnd=5)

Calculate integer transformation matrix given a primitive cell and a super-cell

If \(S\) and \(V\) are, respectively, a matrix whose rows are the cartesian coordinates of the parent lattice vectors and a matrix whose rows are the cartesian coordinates of the super-cell lattice vectors; then, this function returns the matrix \(P=SV^{-1}\). If the resulting matrix is not integer (see rnd parameter), then None is returned.

Parameters:
pcell3x3 ndarray of float

The rows of this matrix correspond to the cartesian coordinates of a parent lattice

scell3x3 ndarray of float

The rows of this matrix correspond to the cartesian coordinates of a supercell

rndint (optional)

The matrix \(P=SV^{-1}\) is rounded to rnd decimal places and checked for integrity.

clusterx.utils.check_and_convert_integer_matrix(A, tol=1e-08)

Check whether all elements of a matrix are (numerically) integers, and return (is_integer_matrix, integer_matrix).

Elements like 1.0 are considered integers. A tolerance is used to handle floating point noise.

Parameters:
Andarray

Input array (e.g., 3x3)

tolfloat

Tolerance for checking integer closeness

Returns:
(bool, np.ndarray)
  • True/False whether all elements are integers

  • Matrix converted to integers (rounded)

clusterx.utils.decorate_supercell(scell, atoms: Atoms, tol: float | None = 1e-05, tols: List[float] | None = None, wrap: bool = False, wrap_eps: float = 0.05)

Create a clusterx.Structure by decorating a SuperCell with species taken from an ASE Atoms object.

For each site in scell, this function finds a matching atom in atoms whose Cartesian position is within a distance tolerance (Euclidean distance). The corresponding atomic number is then used as the decoration. If the supercell has a substitutional sublattice that allows vacancies (species number 0, chemical symbol X), missing atoms on that sublattice are decorated as vacancies.

Parameters:
scellSuperCell

The supercell object (from clusterx) providing the lattice and sites.

atomsAtoms

ASE Atoms instance containing the atomic positions and species.

tolfloat, optional

Distance tolerance for matching positions. Used only when tols is None. Default is 1e-5.

tolslist[float], optional

If provided, decorate_supercell ignores tol and tries each tolerance in increasing order until a valid decoration is found.

wrapbool, optional

Whether to wrap ASE atomic positions into the unit cell before matching. Passed directly to atoms.get_positions(wrap=wrap).

wrap_epsfloat, optional

eps argument forwarded to position wrapping.

Returns:
Structure

A clusterx.Structure object decorated with atomic numbers from atoms.

Raises:
ValueError

If no valid decoration is found for the tested tolerance(s).

clusterx.utils.dict_compare(d1, d2, tol=None)

Compare two dictionaries containing mutable objects.

This compares two dictionaries. Two dictionaries are considered equal even if the position of keys differ. Handles mutable values in the dict. Some parts are taken from:

https://stackoverflow.com/questions/4527942/comparing-two-dictionaries-in-python

Parameters:
d1, d2python dict

dictionaries to be compared

tolfloat

a small float number. If not None, the comparison of dictionary values is regarded as a vector comparison and done with utils.isclose(). For the meaning of tol, read the documentation for rtol parameter of utils.isclose().

Returns:
bool

True if dicts are equal, False if they are different.

clusterx.utils.find_sc_shape(scell, pcell, threshold_length=1e-05, tol_int=0.001, true_rescale=False, n_atoms_scell=None, n_atoms_pcell=None)

Determine the integer transformation matrix (shape) relating a supercell to a primitive cell.

Given lattice matrices scell and pcell, the shape is defined as

\[S = P_{\text{sc}} \cdot P_{\text{pc}}^{-1}\]

where rows of each matrix are lattice vectors. The raw shape S is then rescaled so that its first significant element is closest to an integer, and finally checked for integer-valuedness.

Parameters:
scellndarray, shape (3, 3)

Supercell lattice matrix.

pcellndarray, shape (3, 3)

Primitive cell lattice matrix.

threshold_lengthfloat, optional

Matrix elements whose absolute value is below this threshold are zeroed before the inversion. Default is 1e-8.

tol_intfloat, optional

Tolerance passed to check_and_convert_integer_matrix when deciding whether the rescaled shape elements are integers. Default is 1e-3.

n_atoms_scellint, optional

Number of atoms in the supercell. When both n_atoms_scell and n_atoms_pcell are provided, the function checks that n_atoms_scell / n_atoms_pcell agrees with abs(det(shape_int)). A ValueError is raised if they disagree.

n_atoms_pcellint, optional

Number of atoms in the primitive cell. See n_atoms_scell.

Returns:
is_shape_intbool

True if the rescaled shape matrix is integer-valued within tol_int.

shape_intndarray of int, shape (3, 3)

The rescaled shape matrix rounded to the nearest integers.

shape_rescaledndarray, shape (3, 3)

shape divided by the scale factor determined by rescale_by_first_nonzero.

shapendarray, shape (3, 3)

Raw floating-point result of scell @ inv(pcell) (after threshold zeroing).

clusterx.utils.get_cl_idx_sc(cl, sc, method=0, tol=0.001)

Return atom indexes of cluster points in SuperCell

Parameters:
clnpoints x 3 matrix

matrix of cartesian or scaled coordinates of cluster points. Cluster positions are expected to be wrapped inside supercell sc

scnatoms x 3 matrix

matrix of cartesian or scaled coordinates of supercell atomic positions. The type of coordinates (either cartesion or scaled) must coincide with that of cl

methodint

Method to use. 0: (slow) nested for loop using numpy allclose. 1: (fast) calculates all distances from points in cl to atoms in sc, and return indices for which distances are zero.

tolreal positive number

tolerance to determine whether cluster and atom positions are the same.

clusterx.utils.isclose(r1, r2, rtol=0.0001)

Determine whether two vectors are similar

Parameters:
r1, r21D arrays of int or float

Vectors to be compared

rtolfloat

Tolerance.

Returns:
bool

if the euclidean distance between r1 and r2 is smaller than rtol, True is returned, otherwise False is returned.

clusterx.utils.lattice_wrap_index(index, lattice_shape)

Returns periodic lattice index for a given iterable index. Inspired by: https://stackoverflow.com/questions/38066785/np-ndarray-with-periodic-boundary-conditions

Parameters:
indexiterable

one integer for each axis

lattice_shapetuple

the shape of the lattice to index to

clusterx.utils.list_integer_named_folders(root='.', prefix='', suffix='', containing_files=None, not_containing_files=None)

Return integer-named folders or their original string names.

Scans folders in root and detects those whose names match:

prefix + integer + suffix

Parameters:
rootstr

Path of the root folder in which to scan for integer-named folders.

prefixstr

Required prefix before the integer part.

suffixstr

Required suffix after the integer part.

containing_fileslist[str]

File names that must exist inside the returned folders.

not_containing_fileslist[str]

File names that must not exist inside the returned folders.

Returns:
list[int] or list[str]

Returns integers only when:

  • prefix == “”

  • suffix == “”

  • and none of the matched folder names uses zero padding

Otherwise returns the original folder names as strings, preserving zero padding.

Examples

If the folder structure is:

root/
    1/
    2/
    5/
    7/
    8/
    run_2/
    run_3/
    run_4/
    run_5/
    run_old/
    folderx/
    foldery/

then with default arguments this returns:

[1, 2, 5, 7, 8]

If prefix="run_", this returns:

["run_2", "run_3", "run_4", "run_5"]

If folders are zero-padded, e.g.:

root/
    01/
    02/
    10/
    11/

then this returns:

["01", "02", "10", "11"]
clusterx.utils.make_supercell(prim, P, wrap=True, tol=1e-05)

Generate a supercell by applying a general transformation (P) to the input configuration (prim).

This function is a modified version of ASEs build/supercells.py. The modification here fixes a bug in ASEs implementation, introduced in ASEs version 3.18.0: for certain transformation matrices, the determinant of the matrix is negative, and the function exits with error, since a negative number of atoms is obtained. An example script demonstrating the error is:

from ase.build import make_supercell
from ase.atoms  import Atoms

prim = Atoms(symbols='Cu',
      pbc=True,
      cell=[[0.0, 1.805, 1.805], [1.805, 0.0, 1.805], [1.805, 1.805, 0.0]])

sc = make_supercell(prim, P = [[ 2,  2, -2],[ 2, -2,  2],[-2,  2,  2]], wrap = True, tol = 1e-05)

The release 3.22.0 of ASE still contains the bug. It was informed to ASEs developers on the 3.7.2021

The transformation is described by a 3x3 integer matrix mathbf{P}. Specifically, the new cell metric mathbf{h} is given in terms of the metric of the input configuration mathbf{h}_p by mathbf{P h}_p = mathbf{h}.

Parameters:
primASE Atoms

Input configuration.

P3x3 int matrix

Transformation matrix mathbf{P}.

wrapbool

wrap in the end

tolfloat

tolerance for wrapping

clusterx.utils.mgrep(fpath, search_array, prepend='', root='.')

Grep strings in file and return matching lines.

Parameters:
fpathstr

File path to grep

search_arrayarray of strings

Each element of the array is an string to grep in fpath.

prependstr

prepend string prepend to each matching line.

rootstr

File to grep should be in root/fpath.

clusterx.utils.normalize_nsubs_list(nsubs_list: int | List[int] | List[List[int]] | None) → List[List[int]] | None

Normalize the input nsubs_list into a list of lists of integers.

Parameters:
nsubs_listOptional[Union[int, List[int], List[List[int]]]]

The input to normalize. It can be: - An integer (e.g., 3) - A list of integers (e.g., [3, 4, 7]) - A list of lists of integers (e.g., [[3, 4, 7], [1, 2]]) - None

Returns:
list of list of int or None

The normalized list of lists of integers, or None if input is None.

Examples

>>> normalize_nsubs_list(3)
[[3]]
>>> normalize_nsubs_list([3, 4, 7])
[[3, 4, 7]]
>>> normalize_nsubs_list([[3, 4, 7], [1, 2]])
[[3, 4, 7], [1, 2]]
>>> normalize_nsubs_list(None)
None
clusterx.utils.normalize_shape_input(p)

Normalize the supercell shape input into a 3x3 matrix.

Parameters:
pNone, int, list[int], list[list[int]], or ndarray

The supercell shape specification.

Returns:
np.ndarray or None

A 3x3 numpy array if sc_shape is specified, otherwise None.

clusterx.utils.parent_lattice_to_atat(plat, out_fname='lat.in', for_str=False)

Serializes ParentLattice object to ATAT input file

Parameters:
platParentLattice

ParentLattice object to be serialized

out_fnamestr

Output file path

clusterx.utils.poppush(x, val)

Left-shift array one position and writes new value to the right. Returns average.

Parameters:
xndarray
valint or float
clusterx.utils.remove_vacancies(at)

Remove every Atom containing ‘X’ as species symbol or 0 as atomic number from an Atoms object and return the resulting Atoms object.

Parameters:
atAtoms

Notes

clusterx.utils.report_sset_equivalence_check(sset, sset_equivalence_check_output, property_name=None, tol=0.0)

Generate report of equivalent structures

Writes to files: sset_unique_sym.json and sset_unique_gss.json.

The first contains the structures whose index are given by the keys of the dictionary returned by sset_equivalence_check().

The second contains the structures of every equivalence subset where the value of property_name is minimal. So, if the property is an energy, the final set will contain all lowest energy structures of every equivalence subset.

clusterx.utils.rescale_by_first_nonzero(A)

Find the first nonzero element a_ij0 (row-major order) such that closest_int_to(a_ij0) != 0, then compute

factor = a_ij0 / closest_int_to(a_ij0)

and return A scaled by 1/factor.

If no such element exists, raise an error.

clusterx.utils.sort_atoms(atoms, key=(2, 1, 0))

Return atoms object with sorted atomic coordinates

The default sorting is: increasing z-coordinate first, increasing y-coordinate second, increasing x-coordinate third. Useful to get well ordered slab structures, for instance. Sorting can be changed by appropriately setting the key argument, with the same effect as in:

from operator import itemgetter
sp = sorted(p, key=itemgetter(2,1,0))

where p is a Nx3 array of vector coordinates.

clusterx.utils.sset_equivalence_check(sset, to_primitive=True, cpool=None, basis='trigonometric', comat=None, pretty_print=False)

Find equivalent structures in a StructuresSet object

Equivalence is determined i) in terms of symmetry between structures or ii) in terms of cluster basis representation (if a ClustersPool object or a correlation matrix is given).

In the first case, the SymmetryEquivalenceCheck tool of ASE <https://wiki.fysik.dtu.dk/ase/ase/utils.html#ase.utils.structure_comparator.SymmetryEquivalenceCheck>`_ is used.

Parameters:
ssetStructuresSet

The structures set object to be analyzed.

to_primitivebool, default True

If True the structures are reduced to their primitive cells. This feature requires spglib to installed (cf. ASE’s SymmetryEquivalenceCheck)

cpoolClustersPool, default None

This parameter is optional. If given, the equivalence of a pair of structures is determined according to their cluster basis representation: two structures with the same cluster correlations for the clusters in cpool are considered equivalent.

basisstr, default “trigonometric”

Only used if cpool is not None. Site basis functions used in the determination of cluster correlations.

comat2D array of floats, default None

It overrides cpool and basis. If a correlation matrix for the structures set sset was pre-computed, the equivalence in terms of cluster basis representation is performed by comparing the rows of this matrix (each row must correspond to a structure in the structures set).

Returns:
dict

Returns a dictionary. The keys (k) are structure indices of unique representative structures, and the values (v) are arrays of integer, indicating all structure indices equivalent to k (containing k itself too). For instance, the dictionary:

{"0": [0, 1, 3, 8, 9],
 "2": [2, 5, 6],
 "4": [4, 7]}
indicates that in the structures set with indices [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] there are just three distinct structures. These can be represented by strucutres 0, 2 and 4. The structures [0, 1, 3, 8, 9] are all equivalent, etc.
Notice that here equivalence is used in the sense explained above: It is symmetrical equivalence only if cpool and comat are None.
clusterx.utils.ssets_equivalence_check(sset1, sset2=None, to_primitive=True, pretty_print=False)

Find equivalent structures within or between StructuresSet objects.

If only sset1 is provided, structures are compared with other structures in the same set and the return value follows sset_equivalence_check: each key is a representative index and each value contains all equivalent indices from sset1.

If sset2 is provided, each structure in sset1 is compared with all structures in sset2. In that case every key is an index from sset1 and every value contains the matching indices from sset2.

Structures are compared only when their Atoms.get_chemical_formula(mode="hill", empirical=True) strings are identical.

clusterx.utils.sub_folders(root)

Return list of subfolders

Parameters:
rootstr

path of the absolute folder for which you want to get the list of subfolders.

clusterx.utils.super_structure(struc0, d)

Create a super structure

This function takes a Structure instance (struc0) and creates a new structure which is obtained as the periodic repetition of the original structure along its unit cell vectors. The number of repetitions along each cell vector is given by d. It can be an integer, a three-vector, or a 3x3 matrix of integers.

Parameters:
struc0Structure

Original structure for the superstructure.

dint, three-component int array, or 3x3 int array

The super structure is obtained by the transformation d S, with d a 3x3 matrix of integer and S the supercell cell vectors.

clusterx.utils.take_tile(grid: ndarray, i_grid: ndarray, p_reduced: tuple)

Map values from grid to reduced grid around grid index i_grid.

Parameters:
gridndarray, shape (pX, pY, pZ, …, pd n)
i_gridndarray, shape (d + 1,)
p_reducedtuple of int, shape (d,)
clusterx.utils.transformation_containing_sphere_diag(r: float, cell: ndarray | Cell, full_sphere: bool = False) → ndarray

Return diagonal transformation p of cell that describe a supercell, such that a all pairs of points with distance r are contained in the supercell. Only valid for dim=3 (len(cell.shape)==3).

If full_sphere, returned transformation is large enough, such that a sphere with radius r can be fully contained in corresponding supercell, with the center at any point in the original cell.