Coverage for ase/build/supercells.py: 84.00%
150 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""Helper functions for creating supercells."""
3import numpy as np
4import numpy.typing as npt
6from ase import Atoms
7from ase.utils import deprecated
10def _get_reference_cell(target_shape: str) -> npt.NDArray[np.floating]:
11 """Return the primitive cell vectors of the target Bravais lattice."""
12 return {
13 'sc': np.eye(3),
14 'bcc': 0.5 * (np.ones((3, 3)) - 2.0 * np.eye(3)),
15 'fcc': 0.5 * (np.ones((3, 3)) - np.eye(3)),
16 }[target_shape]
19def _get_target_metric(target_shape: str) -> npt.NDArray[np.floating]:
20 """Return the metric tensor of the target Bravais lattice."""
21 h = _get_reference_cell(target_shape)
22 g = h @ h.T
23 return g / g[0, 0] # unit diagonal, cos(angle) off-diagonal
26def _get_length_factor(target_shape: str) -> float:
27 """Return the ratio of the 1NN distance to the cubic root of cell volume."""
28 h = _get_reference_cell(target_shape)
29 return np.linalg.norm(h[0]) / np.cbrt(abs(np.linalg.det(h)))
32class SupercellError(Exception):
33 """Use if construction of supercell fails"""
36@deprecated('use `eval_length_deviation` instead.')
37def get_deviation_from_optimal_cell_shape(*args, **kwargs):
38 return eval_length_deviation(*args, **kwargs)
41def eval_shape_deviation(
42 cell: npt.NDArray[np.floating],
43 target_shape: str = 'sc',
44) -> npt.NDArray[np.floating]:
45 r"""Calculate the deviation of the cell metric from the target shape.
47 The deviation is calculated as the squared Frobenius norm of the
48 difference between the normalized cell metric tensor and the
49 target metric tensor;
51 .. math::
53 \Delta = \bigg\lVert
54 \frac{\mathbf{G}}{l_\mathrm{target}^2} - \mathbf{G}_\mathrm{target}
55 \bigg\rVert_\mathrm{F}^2
57 where :math:`\mathbf{G} \equiv \mathbf{h} \mathbf{h}^\top` is the metric
58 tensor of the given cell, and :math:`\mathbf{G}_\mathrm{target} \equiv
59 \mathbf{h}_\mathrm{target} \mathbf{h}_\mathrm{target}^\top` is the metric
60 tensor of the target cell shape with the lattice vector lengths normalized
61 to 1.
62 :math:`l_\mathrm{target}` is the ideal lattice vector length of
63 `target_shape` for the given cell volume.
65 .. versionadded:: 3.26.0 (:mr:`3616`)
67 Parameters
68 ----------
69 cell : (..., 3, 3) array_like
70 Lattice vectors given as a 3x3 matrix of the input structure.
71 Multiple cells can also be given as a higher-dimensional array.
72 target_shape : {'sc', 'bcc', 'fcc'}
73 Desired supercell shape.
75 Returns
76 -------
77 float or ndarray
78 Cell metric(s) (0 is perfect score)
80 """
82 cell = np.asarray(cell)
84 eff_cubic_length = np.cbrt(np.abs(np.linalg.det(cell))) # 'a_0'
85 target_len = eff_cubic_length * _get_length_factor(target_shape)
86 target_metric = _get_target_metric(target_shape)
88 # calculate cell @ cell.T for (... , 3, 3)
89 # with cell -> C_mij
90 # and metric -> M_mkl
91 # M_mkl = (sum_j C_mkj * C_mlj) / leff**2
92 metric = cell @ np.swapaxes(cell, -2, -1)
93 normed = metric / target_len[..., None, None] ** 2
95 # offdiagonal ~ cos angle -> score = np.abs(cos angle - cos target_angle)
96 scores = np.add.reduce((normed - target_metric) ** 2, axis=(-2, -1))
98 return scores
101def eval_length_deviation(
102 cell: npt.NDArray[np.floating],
103 target_shape: str = 'sc',
104) -> npt.NDArray[np.floating]:
105 r"""Calculate the deviation of cell vector lengths from the target shape.
107 The deviation is calculated as the Euclidean norm of the relative
108 differences between the cell vector lengths and the ideal length;
110 .. math::
112 \Delta = \sqrt{ \sum_{i=1}^{3}
113 \bigg(\frac{|\mathbf{a}_i|}{l_\mathrm{target}} - 1\bigg)^{2}}
115 :math:`l_\mathrm{target}` is the ideal lattice vector length of
116 `target_shape` for the given cell volume.
118 Parameters
119 ----------
120 cell : (..., 3, 3) array_like
121 Lattice vectors given as a 3x3 matrix of the input structure.
122 Multiple cells can also be given as a higher-dimensional array.
123 target_shape : {'sc', 'bcc', 'fcc'}
124 Desired supercell shape.
126 Returns
127 -------
128 float or ndarray
129 Cell metric(s) (0 is perfect score)
131 Notes
132 -----
133 This function does not consider cell angles.
134 For this, use `eval_shape_deviation`.
136 .. deprecated:: 3.24.0
137 `norm` is unused in ASE 3.24.0 and removed in ASE 3.25.0.
139 .. versionchanged:: 3.24.0
141 Replaced with code from the `doped` defect simulation package
142 (https://doped.readthedocs.io) to be rotationally invariant,
143 boosting performance. (:mr:`3404`)
145 Previously, the deviation was evaluated by [1]_
147 .. math::
149 \Delta = || Q \mathbf{h} - \mathbf{h}_\mathrm{target} ||_\mathrm{F}
151 where
153 .. math::
155 \mathbf{h}
156 \equiv
157 \begin{pmatrix}
158 \mathbf{a}_1 \\
159 \mathbf{a}_2 \\
160 \mathbf{a}_3
161 \end{pmatrix}
163 was the input lattice vectors (`cell`), :math:`Q` was a normalization
164 factor (`norm`), and :math:`\mathbf{h}_\mathrm{target}` was the target
165 lattice vectors specified by `target_shape`.
166 However, this approach was not rotational invariant.
168 .. versionchanged:: 3.26.0
169 Renamed from `get_deviation_from_optimal_cell_shape` to
170 `eval_length_deviation`. (:mr:`3616`)
172 References
173 ----------
174 .. [1] P. Erhart, B. Sadigh, A. Schleife, and D. Åberg.
175 First-principles study of codoping in lanthanum bromide,
176 Phys. Rev. B, Vol **91**, 165206 (2015),
177 :doi:`10.1103/PhysRevB.91.165206`; Appendix C
179 """
181 cell = np.asarray(cell)
182 cell_lengths = np.sqrt(np.add.reduce(cell**2, axis=-1))
184 eff_cubic_length = np.cbrt(np.abs(np.linalg.det(cell))) # 'a_0'
185 target_len = eff_cubic_length * _get_length_factor(target_shape)
186 inv_target_len = 1.0 / target_len
188 # rms difference to eff cubic/FCC length:
189 diffs = cell_lengths * inv_target_len[..., None] - 1.0
190 scores = np.sqrt(np.add.reduce(diffs**2, axis=-1))
192 return scores
195def _guess_initial_transformation(
196 cell: npt.NDArray[np.floating],
197 target_shape: str,
198 target_size: int,
199 verbose: bool = False,
200) -> tuple[npt.NDArray[np.floating], npt.NDArray[np.integer]]:
202 target_metric = _get_reference_cell(target_shape)
204 if verbose:
205 print('target metric (h_target):')
206 print(target_metric)
208 # Normalize cell metric to reduce computation time during looping
209 norm = (
210 target_size * abs(np.linalg.det(cell)) / np.linalg.det(target_metric)
211 ) ** (-1.0 / 3)
212 norm_cell = norm * cell
213 if verbose:
214 print(f'normalization factor (Q): {norm:g}')
216 # Approximate initial P matrix
217 ideal_P = np.dot(target_metric, np.linalg.inv(norm_cell))
218 if verbose:
219 print('idealized transformation matrix:')
220 print(ideal_P)
221 starting_P = np.array(np.around(ideal_P, 0), dtype=int)
222 if verbose:
223 print('closest integer transformation matrix (P_0):')
224 print(starting_P)
226 return ideal_P, starting_P
229def _build_matrix_operations(
230 starting_P: npt.NDArray[np.integer],
231 lower_limit: int,
232 upper_limit: int,
233) -> npt.NDArray[np.integer]:
234 mat_dim = starting_P.shape[0]
236 if not mat_dim == starting_P.shape[1]:
237 raise ValueError('Cell matrix should be quadratic.')
239 # Build a big matrix of all admissible integer matrix operations.
240 # (If this takes too much memory we could do blocking but there are
241 # too many for looping one by one.)
242 dimensions = [(upper_limit + 1) - lower_limit] * mat_dim**2
243 operations = np.moveaxis(np.indices(dimensions), 0, -1)
244 operations = operations.reshape(-1, mat_dim, mat_dim)
245 operations += lower_limit # Each element runs from lower to upper limits.
246 operations += starting_P
248 return operations
251def _screen_supercell_size(operations, target_size):
253 # screen supercells with the target size
254 determinants = np.round(np.linalg.det(operations), 0).astype(int)
255 good_indices = np.where(np.abs(determinants) == target_size)[0]
257 if not good_indices.size:
258 print('Failed to find a transformation matrix.')
259 return None
260 operations = operations[good_indices]
262 return operations
265def _optimal_transformation(
266 operations: npt.NDArray[np.integer],
267 scores: npt.NDArray[np.floating],
268 ideal_P: npt.NDArray[np.floating],
269) -> tuple[npt.NDArray[np.integer], np.floating]:
271 imin = np.argmin(scores)
272 best_score = scores[imin]
273 # screen candidates with the same best score
274 operations = operations[np.abs(scores - best_score) < 1e-6]
276 # select the one whose cell orientation is the closest to the target
277 # https://gitlab.com/ase/ase/-/merge_requests/3522
278 imin = np.argmin(np.add.reduce((operations - ideal_P) ** 2, axis=(-2, -1)))
280 optimal_P = operations[imin]
282 if np.linalg.det(optimal_P) <= 0:
283 optimal_P *= -1 # flip signs if negative determinant
285 return optimal_P, best_score
288all_score_funcs = {
289 'length': eval_length_deviation,
290 'metric': eval_shape_deviation,
291}
294def find_optimal_cell_shape(
295 cell: npt.NDArray[np.floating],
296 target_size: int,
297 target_shape: str,
298 lower_limit: int = -2,
299 upper_limit: int = 2,
300 verbose: bool = False,
301 score_key: str = 'length',
302) -> npt.NDArray[np.integer]:
303 """Obtain the optimal supercell matrix of target size and shape.
305 This determines the transformation matrix for a supercell containing
306 `target_size` unit cells that minimizes the deviation from `target_shape`
307 according to the scoring function selected by `score_key`.
309 Parameters
310 ----------
311 cell : npt.NDArray[np.floating]
312 Lattice vectors of the input structure given as a 3x3 matrix.
313 target_size : int
314 Size of desired supercell in number of unit cells.
315 target_shape : {'sc', 'bcc', 'fcc'}
316 Desired supercell shape.
318 - 'sc': simple cubic
319 - 'bcc': body-centered cubic
320 - 'fcc': face-centered cubic
322 .. versionadded:: 3.30.0 (:mr:`4333`)
323 'bcc' is added.
325 lower_limit : int
326 Lower limit of search range.
327 upper_limit : int
328 Upper limit of search range.
329 verbose : bool
330 Set to True to obtain additional information regarding
331 construction of transformation matrix.
332 score_key : {'length', 'metric'}
333 key to select score function.
335 - `length`: lattice vector lengths
336 (:func:`~supercells.eval_length_deviation`)
337 - `metric`: metric tensor
338 (:func:`~supercells.eval_shape_deviation`)
340 .. versionadded:: 3.26.0 (:mr:`3616`)
342 Returns
343 -------
344 npt.NDArray[np.integer]
345 Transformation matrix that produces the optimal supercell.
347 """
349 # transform to np.array
350 cell = np.asarray(cell)
352 # get starting transformation
353 # ideal_P ... transformation: target_cell = ideal_P @ cell
354 # starting_P ... integer rounded (ideal_P)
355 ideal_P, starting_P = _guess_initial_transformation(
356 cell, target_shape, target_size, verbose=verbose
357 )
359 # build all admissible matrix operations 'centered' at starting_P
360 operations = _build_matrix_operations(starting_P, lower_limit, upper_limit)
362 # pre-screen operations based on target_size
363 operations = _screen_supercell_size(operations, target_size)
365 # evaluate derivations of the screened supercells
366 if score_key in all_score_funcs:
367 get_deviation_score = all_score_funcs[score_key]
368 else:
369 msg = (
370 f'Score func key {score_key} not implemented.'
371 + f'Please select from {all_score_funcs}.'
372 )
373 raise SupercellError(msg)
375 scores = get_deviation_score(operations @ cell, target_shape)
377 # obtain optimal transformation from scores
378 optimal_P, best_score = _optimal_transformation(operations, scores, ideal_P)
380 # Finalize.
381 if verbose:
382 print(f'smallest score (|Q P h_p - h_target|_2): {best_score:f}')
383 print('optimal transformation matrix (P_opt):')
384 print(optimal_P)
385 print('supercell metric:')
386 print(np.round(np.dot(optimal_P, cell), 4))
387 det = np.linalg.det(optimal_P)
388 print(f'determinant of optimal transformation matrix: {det:g}')
390 return optimal_P
393def make_supercell(prim, P, *, wrap=True, order='cell-major', tol=1e-5):
394 r"""Generate a supercell by applying a general transformation (*P*) to
395 the input configuration (*prim*).
397 The transformation is described by a 3x3 integer matrix
398 `\mathbf{P}`. Specifically, the new cell metric
399 `\mathbf{h}` is given in terms of the metric of the input
400 configuration `\mathbf{h}_p` by `\mathbf{P h}_p =
401 \mathbf{h}`.
403 Parameters
404 ----------
406 prim: ASE Atoms object
407 Input configuration.
408 P: 3x3 integer matrix
409 Transformation matrix `\mathbf{P}`.
410 wrap: bool
411 wrap in the end
412 order: str (default: "cell-major")
413 how to order the atoms in the supercell
415 "cell-major":
416 [atom1_shift1, atom2_shift1, ..., atom1_shift2, atom2_shift2, ...]
417 i.e. run first over all the atoms in cell1 and then move to cell2.
419 "atom-major":
420 [atom1_shift1, atom1_shift2, ..., atom2_shift1, atom2_shift2, ...]
421 i.e. run first over atom1 in all the cells and then move to atom2.
422 This may be the order preferred by most VASP users.
424 tol: float
425 tolerance for wrapping
426 """
428 supercell_matrix = P
429 supercell = clean_matrix(supercell_matrix @ prim.cell)
431 # cartesian lattice points
432 lattice_points_frac = lattice_points_in_supercell(supercell_matrix)
433 lattice_points = np.dot(lattice_points_frac, supercell)
434 N = len(lattice_points)
436 if order == 'cell-major':
437 shifted = prim.positions[None, :, :] + lattice_points[:, None, :]
438 elif order == 'atom-major':
439 shifted = prim.positions[:, None, :] + lattice_points[None, :, :]
440 else:
441 raise ValueError(f'invalid order: {order}')
442 shifted_reshaped = shifted.reshape(-1, 3)
444 superatoms = Atoms(positions=shifted_reshaped, cell=supercell, pbc=prim.pbc)
446 # Copy over any other possible arrays, inspired by atoms.__imul__
447 for name, arr in prim.arrays.items():
448 if name == 'positions':
449 # This was added during construction of the super cell
450 continue
451 shape = (N * arr.shape[0], *arr.shape[1:])
452 if order == 'cell-major':
453 new_arr = np.repeat(arr[None, :], N, axis=0).reshape(shape)
454 elif order == 'atom-major':
455 new_arr = np.repeat(arr[:, None], N, axis=1).reshape(shape)
456 superatoms.set_array(name, new_arr)
458 # check number of atoms is correct
459 n_target = abs(int(np.round(np.linalg.det(supercell_matrix) * len(prim))))
460 if n_target != len(superatoms):
461 msg = 'Number of atoms in supercell: {}, expected: {}'.format(
462 n_target, len(superatoms)
463 )
464 raise SupercellError(msg)
466 if wrap:
467 superatoms.wrap(eps=tol)
469 return superatoms
472def lattice_points_in_supercell(supercell_matrix):
473 """Find all lattice points contained in a supercell.
475 Adapted from pymatgen, which is available under MIT license:
476 The MIT License (MIT) Copyright (c) 2011-2012 MIT & The Regents of the
477 University of California, through Lawrence Berkeley National Laboratory
478 """
480 diagonals = np.array(
481 [
482 [0, 0, 0],
483 [0, 0, 1],
484 [0, 1, 0],
485 [0, 1, 1],
486 [1, 0, 0],
487 [1, 0, 1],
488 [1, 1, 0],
489 [1, 1, 1],
490 ]
491 )
492 d_points = np.dot(diagonals, supercell_matrix)
494 mins = np.min(d_points, axis=0)
495 maxes = np.max(d_points, axis=0) + 1
497 ar = np.arange(mins[0], maxes[0])[:, None] * np.array([1, 0, 0])[None, :]
498 br = np.arange(mins[1], maxes[1])[:, None] * np.array([0, 1, 0])[None, :]
499 cr = np.arange(mins[2], maxes[2])[:, None] * np.array([0, 0, 1])[None, :]
501 all_points = ar[:, None, None] + br[None, :, None] + cr[None, None, :]
502 all_points = all_points.reshape((-1, 3))
504 frac_points = np.dot(all_points, np.linalg.inv(supercell_matrix))
506 tvects = frac_points[
507 np.all(frac_points < 1 - 1e-10, axis=1)
508 & np.all(frac_points >= -1e-10, axis=1)
509 ]
510 assert len(tvects) == round(abs(np.linalg.det(supercell_matrix)))
511 return tvects
514def clean_matrix(matrix, eps=1e-12):
515 """clean from small values"""
516 matrix = np.array(matrix)
517 for ij in np.ndindex(matrix.shape):
518 if abs(matrix[ij]) < eps:
519 matrix[ij] = 0
520 return matrix