Coverage for dynasor/tools/structures.py: 100%
116 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-09 14:30 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-09 14:30 +0000
1from typing import Optional
2import numpy as np
3from ase import Atoms
4from ase.geometry import get_distances
5from ase.geometry import find_mic
6from dynasor.qpoints.lattice import get_P_matrix
7from dynasor.qpoints.tools import exact_inverse
8from numpy.typing import NDArray
11def get_displacements(atoms: Atoms,
12 atoms_ideal: Atoms,
13 check_mic: Optional[bool] = True,
14 cell_tol: Optional[float] = 1e-4) -> NDArray[float]:
15 """Returns the smallest possible displacements between a
16 displaced configuration relative to an ideal (reference)
17 configuration.
19 Parameters
20 ----------
21 atoms
22 Structure with displaced atoms.
23 atoms_ideal
24 Ideal configuration relative to which displacements are computed.
25 check_mic
26 Whether to check minimum image convention.
27 cell_tol
28 Cell tolerance; if the cell mismatch exceeds this value, a `ValueError` is raised.
29 """
31 if not np.array_equal(atoms.numbers, atoms_ideal.numbers):
32 raise ValueError('Atomic numbers do not match.')
33 if np.linalg.norm(atoms.cell - atoms_ideal.cell) > cell_tol:
34 raise ValueError('Cells do not match.')
36 u = atoms.positions - atoms_ideal.positions
37 return get_displacements_from_u(u, atoms_ideal.cell, check_mic=check_mic)
40def get_displacements_from_u(
41 u: NDArray[float],
42 cell: NDArray[float],
43 check_mic: Optional[bool] = True,
44) -> NDArray[float]:
45 """wraps displacements using mic"""
46 if check_mic:
47 u, _ = find_mic(u, cell)
48 return u
51def find_permutation(atoms: Atoms,
52 atoms_ref: Atoms,
53 cell_tol: Optional[float] = 1e-4) -> list[int]:
54 """ Returns the best permutation of atoms for mapping one
55 configuration onto another.
57 Parameters
58 ----------
59 atoms
60 Configuration to be permuted.
61 atoms_ref
62 Configuration onto which to map.
63 cell_tol
64 Cell tolerance; if the cell mismatch exceeds this value, a `ValueError` is raised.
66 Example
67 -------
68 After obtaining the permutation via ``p = find_permutation(atoms1, atoms2)``
69 the reordered structure ``atoms1[p]`` will give the closest match
70 to ``atoms2``.
71 """
72 if np.linalg.norm(atoms.cell - atoms_ref.cell) > cell_tol:
73 raise ValueError('Cells do not match.')
75 permutation = []
76 for i in range(len(atoms_ref)):
77 dist_row = get_distances(
78 atoms.positions, atoms_ref.positions[i], cell=atoms_ref.cell, pbc=True)[1][:, 0]
79 permutation.append(np.argmin(dist_row))
81 if len(set(permutation)) != len(permutation):
82 raise ValueError('Duplicates in permutation.')
83 for i, p in enumerate(permutation):
84 if atoms[p].symbol != atoms_ref[i].symbol:
85 raise ValueError('Matching lattice sites have different occupation.')
86 return permutation
89def align_structure(
90 atoms: Atoms,
91 atol: Optional[float] = 1e-5,
92 method: Optional[str] = 'sequential',
93) -> None:
94 """
95 Rotates a structure into alignment with the x,y,z coordinate system.
97 With :attr:`method` set to ``'sequential'`` the structure is rotated such that
99 * the first cell vector points along the x-direction
100 * the second cell vector lies in the xy-plane
102 which yields a lower triangular cell metric. With :attr:`method` set to
103 ``'best_fit'`` a single rotation is applied that maximizes the sum of the cosines of
104 the angles between the three cell vectors and the x, y and z axes, respectively.
105 All three vectors may then deviate from their respective axis, but the total
106 misalignment is as small as possible; only the directions of the cell vectors enter,
107 not their lengths.
109 Note that this function modifies the :attr:`atoms` object in place, and that only
110 the positions and the cell are rotated; velocities and momenta are left unchanged.
112 Parameters
113 ----------
114 atoms
115 Input structure to be aligned with the x,y,z coordinate system.
116 atol
117 Absolute tolerance used for sanity checking the cell.
118 method
119 Alignment method to use; must be either ``'sequential'`` or ``'best_fit'``.
120 """
121 if method == 'sequential':
122 _align_a_onto_xy(atoms, atol)
123 _align_a_onto_x(atoms, atol)
124 _align_b_onto_xy(atoms, atol)
125 elif method == 'best_fit':
126 _align_best_fit(atoms, atol)
127 else:
128 raise ValueError(f'Unknown method {method}; must be "sequential" or "best_fit".')
131def get_offset_index(
132 primitive: Atoms,
133 supercell: Atoms,
134 tol: Optional[float] = 0.01,
135 wrap: Optional[bool] = True,
136) -> tuple[NDArray[int], NDArray[int]]:
137 """ Returns the basis index and primitive cell offsets for a supercell.
139 This implementation uses a simple iteration procedure that should be fairly quick.
140 If more stability is needed consider the following approach:
142 * find the P-matrix: `P = get_P_matrix(prim.cell, ideal.cell)`
143 * compensate for strain: `P *= len(ideal)/len(prim)/det(P)`
144 * generate the reference structure: `ref_atoms = make_supercell(round(P), prim)`
145 * find the assignment using `ref_atoms` via the Hungarian algorithm using the mic distances
147 Parameters
148 ----------
149 primitive
150 Primitive cell.
151 supercell
152 Some ideal repetition of the primitive cell.
153 tol
154 Tolerance length parameter. Increase to allow for slightly rattled or strained cells.
155 wrap
156 It might happen that the ideal cell boundary cuts through a unit cell
157 whose lattice points lie inside the ideal cell. If there is a basis, an
158 atom belonging to this unit cell might get wrapped while another is
159 not. Then the wrapped atom now belongs to a lattice point outside the P
160 matrix so to say. This would result in more lattice points than
161 expected from `N_unit = len(ideal)/len(prim)`.
163 Returns
164 -------
165 offsets
166 The lattice points as integers in `(N, 3)`-array.
167 index
168 The basis indices as integers in `(N,)`-array.
169 """
171 if not isinstance(primitive, Atoms):
172 raise ValueError('primitive must be an ASE Atoms object.')
173 if not isinstance(supercell, Atoms):
174 raise ValueError('supercell must be an ASE Atoms object.')
176 prim_inv_cell = np.linalg.inv(primitive.cell)
178 P = get_P_matrix(primitive.cell, supercell.cell) # P C = S
179 P_inv = exact_inverse(P)
181 lattice, basis = [], []
182 # Pick an atom in the supercell
183 for pos_ideal in supercell.positions:
184 # Does this atom perhaps belong to site "index"?
185 for index, pos_prim in enumerate(primitive.positions):
186 # if so we can remove the basis position vector and should end up on a lattice site
187 diff_pos = pos_ideal - pos_prim
188 # The lattice site has integer coordinates in reduced coordinates
189 prim_spos = diff_pos @ prim_inv_cell
190 # Rounding should not affect the coordinate much if it is integer
191 prim_spos_round = np.round(prim_spos).astype(int)
192 # If the rounded spos and unrounded spos are the same
193 if np.allclose(prim_spos, prim_spos_round, rtol=0, atol=tol):
194 # Since P_inv is represented using fractions we can neatly
195 # write the supercell spos of the lattice point using fractions
196 # and easily determine if it needs wrapping or not without
197 # worry about numerics
198 ideal_spos = prim_spos_round @ P_inv
199 # wrap if needed
200 ideal_spos_wrap = ideal_spos % 1 if wrap else ideal_spos
201 # This should be integer again
202 prim_spos_wrap = (ideal_spos_wrap @ P).astype(int)
203 # add the results and break out from the basis site loop
204 lattice.append(prim_spos_wrap)
205 basis.append(index)
206 break
207 else: # we get here by not breaking out from the basis site loop.
208 # This means that the candidate lattice site where not close to integers
210 raise ValueError('Supercell not compatible with primitive cell; the atom at '
211 f'{pos_ideal} does not map onto a lattice point (reduced '
212 f'coordinates {prim_spos}, nearest integer {prim_spos_round}).')
214 lattice = np.array(lattice)
215 basis = np.array(basis)
217 # We should have found len(ideal) unique positions
218 lattice_basis = [tuple((*lp, i)) for lp, i in zip(lattice, basis)]
219 assert len(set(lattice_basis)) == len(supercell)
221 return lattice, basis
224def _align_a_onto_xy(atoms: Atoms, atol: float) -> None:
225 """ Rotate cell so that a is in the xy-plane. """
227 cell = atoms.cell.array.copy()
229 a = cell[0]
230 a_xy = a.copy()
231 a_xy[2] = 0 # projection of a onto xy-plane
233 norm_a = np.linalg.norm(a)
234 norm_a_xy = np.linalg.norm(a_xy)
236 assert norm_a >= atol, \
237 f'First cell vector a has near-zero length ({norm_a:.3e}); cannot align cell.'
238 assert norm_a_xy >= atol, \
239 f'First cell vector a is nearly parallel to the z-axis ' \
240 f'(|a_xy| = {norm_a_xy:.3e}); cannot align a onto the xy-plane.'
242 # cosine of the angle between a and its xy-projection
243 cosa = norm_a_xy / norm_a
244 cosa = min(cosa, 1.0) # clamp for floating-point safety
246 # angle between a and xy-plane in degs
247 angle_xy_deg = np.rad2deg(np.arccos(cosa))
249 # get unit vector to rotate around
250 vec = np.cross(a_xy, [0, 0, 1])
251 vec = vec / np.linalg.norm(vec)
252 assert vec[2] == 0
254 # Determine if the rotation should be positive or negative depending on
255 # whether a is pointing in the +z or -z direction
256 sign = -1 if a[2] > 0 else +1
258 # rotate
259 atoms.rotate(sign * angle_xy_deg, vec, rotate_cell=True)
261 assert np.isclose(atoms.cell[0, 2], 0, atol=atol, rtol=0), atoms.cell
264def _align_a_onto_x(atoms: Atoms, atol: float) -> None:
265 assert np.isclose(atoms.cell[0, 2], 0, atol=atol, rtol=0) # make sure a is in xy-plane
267 a = atoms.cell[0]
268 a_x = a[0]
269 a_y = a[1]
271 # angle between a and x-axis (a is already in xy-plane)
273 # tan = y / x -> angle = arctan y / x "=" atan2(y, x)
274 angle_rad = np.arctan2(a_y, a_x)
275 angle_deg = np.rad2deg(angle_rad)
277 atoms.rotate(-angle_deg, [0, 0, 1], rotate_cell=True)
279 assert np.isclose(atoms.cell[0, 1], 0, atol=atol, rtol=0), atoms.cell
280 assert np.isclose(atoms.cell[0, 2], 0, atol=atol, rtol=0), atoms.cell
283def _align_b_onto_xy(atoms: Atoms, atol: float) -> None:
284 assert np.isclose(atoms.cell[0, 1], 0, atol=atol, rtol=0) # make sure a is along x
285 assert np.isclose(atoms.cell[0, 2], 0, atol=atol, rtol=0) # make sure a is along x
287 # rotate so that b is in xy plane
288 # project b onto the yz-plane
289 b = atoms.cell[1]
290 b_y = b[1]
291 b_z = b[2]
292 angle_rad = np.arctan2(b_z, b_y)
293 angle_deg = np.rad2deg(angle_rad)
295 atoms.rotate(-angle_deg, [1, 0, 0], rotate_cell=True)
297 assert np.isclose(atoms.cell[0, 1], 0, atol=atol, rtol=0) # make sure a is in xy-plane
298 assert np.isclose(atoms.cell[0, 2], 0, atol=atol, rtol=0) # make sure a is in xy-plane
299 assert np.isclose(atoms.cell[1, 2], 0, atol=atol, rtol=0), atoms.cell
302def _align_best_fit(atoms: Atoms, atol: float) -> None:
303 """ Rotate cell such that a, b and c match x, y and z as closely as possible. """
305 cell = atoms.cell.array.copy()
307 norms = np.linalg.norm(cell, axis=1)
308 assert np.all(norms >= atol), \
309 f'Cell vector with near-zero length ({np.min(norms):.3e}); cannot align cell.'
311 # rotation that maximizes the sum of e_i . R a_i over proper rotations,
312 # i.e., the orthogonal Procrustes solution for the normalized cell vectors
313 u, _, vh = np.linalg.svd(cell / norms[:, None])
314 d = np.diag([1, 1, np.sign(np.linalg.det(u @ vh))])
315 R = u @ d @ vh
317 atoms.positions[:] = atoms.positions @ R.T
318 atoms.set_cell(cell @ R.T)