Coverage for ase/_4/optimize/_symopt/relax.py: 91.59%
464 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
1from dataclasses import asdict, dataclass
3import numpy as np
4import scipy
6from ase import Atoms
7from ase._4.optimize._symopt.relax_print import (
8 pprint_atoms,
9 pretty,
10 pretty_atomic_dofs,
11 pretty_dofs,
12 pretty_header,
13 pretty_subheader,
14)
15from ase.cell import Cell
16from ase.utils import spglib_new_errorhandling
17from ase.utils.abc import Optimizable
20def green(text: str) -> str:
21 return f'\x1b[32m{text}\x1b[0m'
24def argsort_rotations(rotations):
25 return sorted(
26 range(len(rotations)),
27 key=lambda i: tuple(rotations[i].reshape(9).tolist()),
28 )
31def snap_translations_to_zero(translations, tol=1e-13):
32 # spglib may produce translations that are +/- 1e-15, we want those to be 0
33 # It may also produce 1 (+/- 1e-15), and we want those to be zero as well.
35 # If a translation is 1, it means a whole lattice vector and that we
36 # can also use 0 instead (no matter the corresponding rotation).
37 cleaned_translations = translations - np.rint(translations)
38 cleaned_translations[abs(cleaned_translations) < tol] = 0.0
39 assert (abs(cleaned_translations) <= 0.5).all()
40 return cleaned_translations
43def chol_derivative(A, dA):
44 """
45 Compute the derivative of the Cholesky factorization.
47 A = L L^T
49 where L is lower-triangular. For a small symmetric perturbation `dA`,
50 this function returns an approximation of the differential `dL` of
51 the Cholesky factor:
53 L + dL ≈ chol(A + dA).
55 Either L or A must be given as an input.
56 """
57 A = (A + A.T) / 2
58 dA = (dA + dA.T) / 2
60 L = np.linalg.cholesky(A)
61 Linv = np.linalg.inv(L)
62 S = Linv @ dA @ Linv.T
63 X = np.tril(S)
64 X[np.diag_indices_from(X)] *= 0.5
65 return L @ X
68def symmetrize_atoms(
69 S_ac: np.ndarray, U_scc: np.ndarray, f_sc: np.ndarray, atommap_sa, tol=1e-12
70):
71 """
72 Symmetrize fractional atomic coordinates under a space-group.
74 Given atomic scaled positions `S_ac` and a set of space-group operations
75 (U_scc, f_sc), this function projects the positions onto the symmetry-
76 invariant subspace by averaging over all symmetry-related images.
78 Parameters
79 ----------
80 S_ac : ndarray, shape (na, 3)
81 Scaled atomic coordinates.
83 U_scc : ndarray, shape (ns, 3, 3)
84 Rotation matrices.
86 f_sc : ndarray, shape (ns, 3)
87 Translation vectors.
89 atommap_sa : ndarray, shape (ns, na)
90 Mapping such that atommap_sa[s, a] gives the index of the atom
91 to which atom `a` is mapped by symmetry operation `s`.
93 tol : float, optional
94 Tolerance for snapping values close to 0 or 1 back to 0.
96 Returns
97 -------
98 Ssym_ac : ndarray, shape (na, 3)
99 Symmetrized fractional atomic coordinates in [0, 1).
101 Notes
102 -----
103 The symmetrization is done in the complex phase representation
104 exp(2πi x) to correctly average periodic fractional coordinates.
105 """
106 ns, na = atommap_sa.shape
107 complex_Ssym_ac = np.zeros_like(S_ac, dtype=np.complex128)
108 for a in range(na):
109 for s in range(ns):
110 new = U_scc[s].T @ S_ac[a] - f_sc[s]
111 complex_Ssym_ac[atommap_sa[s, a]] += np.exp(2j * np.pi * new)
112 Ssym_ac = (np.angle(complex_Ssym_ac) / (2 * np.pi)) % 1.0 % 1.0
113 Ssym_ac[np.abs(Ssym_ac) < tol] = 0.0
114 Ssym_ac[np.abs(Ssym_ac - 1.0) < tol] = 0.0
115 return Ssym_ac
118def apply_pbc_to_symops(rotations, translations, pbc):
119 """spglib thinks we are a 3d system, but actually we may be 2D/1D.
121 spglib will produce symops that involve e.g. a z-flip, but that
122 flips the positions to negative z-values, and we need to apply the
123 full z axis as translation vector in order to map the position back
124 into the cell.
126 This function equips such operations with the necessary translations.
128 We also do some sanity checking.
129 """
130 translations = translations.copy()
131 assert len(rotations) == len(translations)
133 for i in range(3):
134 if pbc[i]:
135 continue
137 for s in range(len(rotations)):
138 nonpbc_rot = rotations[s, i, i]
139 assert nonpbc_rot in (-1, 1)
140 nonpbc_op_row = np.zeros(3, int)
141 nonpbc_op_row[i] = nonpbc_rot
142 assert (rotations[s, :, i] == nonpbc_op_row).all()
143 assert (rotations[s, i, :] == nonpbc_op_row).all()
144 if nonpbc_rot == -1:
145 assert abs(translations[s, i]) < 1e-15, translations[s, i]
146 translations[s, i] = 1.0
148 return translations
151@dataclass
152class AtomsSymmetries:
153 """
154 Dataclass to contain symmetry information from atoms.
156 This is to set up an interface for spglib/GPAW or whatever
157 source of symmetry operations.
158 """
160 rotation_scc: np.ndarray
161 atommap_sa: np.ndarray
162 translation_sc: np.ndarray
164 def __post_init__(self):
165 ns = len(self.rotation_scc)
166 assert self.rotation_scc.shape == (ns, 3, 3)
167 assert len(self.atommap_sa) == ns
168 assert self.translation_sc.shape == (ns, 3)
170 @classmethod
171 def from_spglib_auto(cls, atoms, *, symprec=1e-4):
172 from spglib import get_symmetry_dataset
174 dataset = spglib_new_errorhandling(get_symmetry_dataset)(
175 (atoms.cell, atoms.get_scaled_positions(), atoms.numbers),
176 symprec=symprec,
177 )
178 return cls.from_spglib(atoms, dataset, atommap_maxerr=symprec * 1.1)
180 @classmethod
181 def from_spglib(cls, atoms, dataset, atommap_maxerr=1e-12):
182 """Get symmetry dataset from spglib.
184 By default we assume that the atoms have been symmetirized exactly.
185 However, if spglib dataset came for example with symprec 0.1, this
186 function needs to be caled with atommap_maxerr ~ 0.1 in order to pass
187 the sanity checks.
188 """
189 from ase._4.optimize._symopt.atommap import build_atommaps
191 args = argsort_rotations(dataset.rotations.transpose(0, 2, 1))
193 rotations = dataset.rotations[args]
194 translations = apply_pbc_to_symops(
195 dataset.rotations, dataset.translations, pbc=atoms.pbc
196 )[args]
197 translations = snap_translations_to_zero(translations)
199 return cls(
200 rotation_scc=rotations.transpose(0, 2, 1).copy(),
201 translation_sc=-translations,
202 atommap_sa=build_atommaps(
203 atoms.copy(),
204 rotations,
205 translations.copy(),
206 maxerr=atommap_maxerr,
207 ),
208 )
210 @classmethod
211 def from_GPAW(cls, atoms, *, log, tolerance, symmorphic):
212 from gpaw.new.symmetry import create_symmetries_object
214 gpaw_symmetries = create_symmetries_object(
215 atoms, tolerance=tolerance, symmorphic=symmorphic
216 )
217 args = argsort_rotations(gpaw_symmetries.rotation_scc)
218 log(gpaw_symmetries)
219 return cls(
220 gpaw_symmetries.rotation_scc[args],
221 gpaw_symmetries.atommap_sa[args],
222 gpaw_symmetries.translation_sc[args],
223 )
226# The symmetry-reduced coordinates for positions and cell
227# have an arbitrary scale.
228#
229# It is nice that both sets of coordinates produce human-friendly
230# numbers of approximately the same magnitude in typical cases. To
231# this effect, we scale the cell coordinates by this number. This
232# actually affects the run if there's a specific initial Hessian, step
233# limitation using "maxstep", etc., but any value is in principle
234# valid.
235CELL_COORDINATE_SCALING_FACTOR = 40
238@dataclass
239class SymmetryAdaptedCellCoordinates:
240 """Class for defining symmetry adapted cell coordinates
242 Note: This is not symmetry adapted cell, it just provides the set of
243 generalized coordinates for the symmetry adapted cell.
244 To get the cell, call C_cv = get_cell(cell_z).
246 sacc = SymmetryAdaptedCellCoordinates(...)
247 sacc.get_cell(cell_z), where cell_z is 1D array of the cell coordinates.
249 Thus, the M_cc and C_cv here is just the origin of the coordinate system.
250 """
252 # Symmetrized cell
253 M_cc: np.ndarray # Rename to M0_cc
254 C_cv: np.ndarray # Rename to C0_cv
255 dM_zcc: np.ndarray
256 dM_zvv: np.ndarray
257 rot_vv: np.ndarray
259 def get_cell(self, cell_z):
260 """
261 Construct the real-space unit cell from symmetry-adapted coordinates.
263 Given generalized cell coordinates `cell_z`, this method reconstructs
264 the metric tensor (see get_M_cc) and then computes a corresponding
265 cell matrix C_cv via a Cholesky factorization of M_cc,
266 followed by a fixed rotation `rot_vv`:
268 C_cv = chol(M_cc) @ rot_vv.T
270 Parameters
271 ----------
272 cell_z : ndarray, shape (nz,)
273 Symmetry-adapted cell coordinates.
275 Returns
276 -------
277 cell : ase.geometry.Cell
278 The reconstructed unit cell.
279 """
281 M_cc = self.get_M_cc(cell_z)
282 try:
283 C_cv = np.linalg.cholesky(M_cc) @ self.rot_vv.T
284 except np.linalg.LinAlgError:
285 raise RuntimeError('Failed to create cell from metric', M_cc)
287 return Cell(C_cv)
289 def get_M_cc(self, cell_z):
290 """
291 Reconstruct the metric tensor from symmetry-adapted coordinates.
293 Computes the metric tensor as a linear expansion around a reference
294 metric M0_cc in the symmetry-allowed tangent directions:
296 M_cc = M0_cc + sum_z cell_z[z] * dM_zcc[z]
298 Parameters
299 ----------
300 cell_z : ndarray, shape (nz,)
301 Symmetry-adapted cell coordinates.
303 Returns
304 -------
305 M_cc : ndarray, shape (3, 3)
306 Symmetrized metric tensor corresponding to `cell_z`.
307 """
308 return self.M_cc + np.einsum('z,zcd->cd', cell_z, self.dM_zcc)
310 @classmethod
311 def build(cls, cell, pbc_c, rotation_scc: np.ndarray, *, log, **kwargs):
312 return cls(
313 *cls.unit_cell_symmetry(
314 cell, rotation_scc, pbc_c, log=log, **kwargs
315 )
316 )
318 @classmethod
319 def symmetrize_cell(cls, C_cv, rotation_scc):
320 """Symmetrize the cell
322 Calculates the cell metric, and applies the rotation operations to it.
323 New cell lower diagonal cell is calculated via Cholesky decomposition.
324 By doing polar decomposition to the deformation gradient, the rotation
325 back to the original cell rotation is obtained.
327 Returns osymC_cV, symC_cv, M_cc, rot_vv
329 Where osymC_cv is the symmetrized original like cell
330 symC_cv is the lower diagonal symmetrized cell
331 M_cc is the symmetrized cell metric
332 rot_vv is the rotation matrix between osymC_Cv and symC_cv
333 such that osymC_cv = symC_cv @ rot_vv.T
335 """
336 # Calculate the cell metric
337 M_cc = C_cv @ C_cv.T
338 # Symmetrize the cell metric
339 M_cc = np.einsum(
340 'scd,de,sfe->cf', rotation_scc, M_cc, rotation_scc, optimize=True
341 ) / len(rotation_scc)
343 symC_cv = np.linalg.cholesky(M_cc)
345 # Deformation gradient
346 F_vv = np.linalg.inv(C_cv) @ symC_cv
348 # Sanity check
349 assert np.allclose(C_cv @ F_vv, symC_cv)
351 # Do a polar decomposition to rotate the symmetrized cell back
352 rot_vv, P_vv = scipy.linalg.polar(F_vv)
353 osymC_cv = symC_cv @ rot_vv.T
355 return osymC_cv, symC_cv, M_cc, rot_vv
357 @classmethod
358 def unit_cell_symmetry(
359 cls, C_cv, rotation_scc, pbc_c, units='Å^2', *, log, fixcell=False
360 ):
361 pretty(
362 C_cv @ C_cv.T, "Cell metric (M_cc' = C_cv C_c'v)", units, log=log
363 )
364 osymC_cv, symC_cv, M_cc, rot_vv = cls.symmetrize_cell(
365 C_cv, rotation_scc
366 )
367 pretty(
368 M_cc, "Symmetrized cell metric (M_cc' = C_cv C_c'v)", units, log=log
369 )
371 # Now we can construct exact Cartesian rotation matrices
372 iosymC_cv = np.linalg.inv(osymC_cv)
373 U_svv = [osymC_cv.T @ U_cc.T @ iosymC_cv.T for U_cc in rotation_scc]
374 U_svv = np.array(U_svv)
376 # Build unit vector in symmetric matrix space
377 def e(i, j):
378 eps_ij = np.zeros((3, 3))
379 eps_ij[i, j] = 1.0
380 eps_ij[j, i] = 1.0
381 return eps_ij
383 eps_ijk = np.zeros((3, 3, 6))
384 k = 0
385 for i in range(3):
386 for j in range(i, 3):
387 if i == j:
388 s = 1.0
389 else:
390 s = 2 ** (-0.5)
391 eps_ijk[i, j, k] = s
392 eps_ijk[j, i, k] = s
393 k += 1
395 A_blocks = []
396 for U_vv in U_svv:
397 rows = []
398 for k in range(6):
399 row = U_vv @ eps_ijk[:, :, k] @ U_vv.T - eps_ijk[:, :, k]
400 rows.append(row.reshape(9))
401 A_blocks.append(np.vstack(rows))
402 for c in range(3):
403 if not pbc_c[c]:
404 for cprime in range(3):
405 A_blocks.append(e(c, cprime).reshape(9))
406 A = np.vstack(A_blocks)
407 A = A @ eps_ijk.reshape((9, 6))
408 # Compute null space via SVD
409 U, S, Vh = np.linalg.svd(A)
410 tol = 1e-6
411 null_mask = S < tol
412 nullspace = Vh[null_mask]
414 if fixcell:
415 dM_zcc = np.zeros((0, 3, 3))
416 dM_zvv = np.zeros((0, 3, 3))
417 else:
418 dM_zcc = []
419 dM_zvv = []
420 for B in nullspace:
421 B = B @ eps_ijk.reshape((9, 6)).T
422 dM_vv = B.reshape((3, 3))
423 dof = osymC_cv @ dM_vv @ osymC_cv.T
424 dM_zcc.append(dof)
425 dM_zvv.append(rot_vv @ dM_vv @ rot_vv.T)
426 dM_zcc = np.array(dM_zcc).reshape((-1, 3, 3))
427 dM_zvv = np.array(dM_zvv).reshape((-1, 3, 3))
429 # Do a QR decomposition, try to get more zeros to coordinates
430 basis = np.array(dM_zcc).reshape((-1, 9))
431 Q, R = np.linalg.qr(basis)
432 dM_zcc = (Q.T @ basis).reshape((-1, 3, 3))
434 # Normalize tangent space vectors
435 Cinv = np.linalg.inv(C_cv)
436 for z in range(len(dM_zcc)):
437 dC = chol_derivative(M_cc, dM_zcc[z]) @ rot_vv.T
438 eps = 0.5 * (Cinv @ dC + dC.T @ Cinv.T)
440 dM_zcc[z] /= np.sum(np.abs(eps)) * np.linalg.det(C_cv)
441 dM_zcc[z] *= CELL_COORDINATE_SCALING_FACTOR
442 # Define the direction of the tangent vector such that
443 # it increases the volume. Sign cannot be used because of shear
444 if np.trace(np.linalg.inv(C_cv) @ dC) < 0:
445 dM_zcc[z] *= -1
447 pretty_dofs(dM_zcc, M_cc, rot_vv, osymC_cv, log=log)
449 # TODO: Move U_svv
450 return M_cc, osymC_cv, dM_zcc, dM_zvv, rot_vv
453@dataclass
454class SymmetryAdaptedScaledCoordinates:
455 dof_zac: np.ndarray
456 s0_ac: np.ndarray
458 def get_scaled_coordinates(self, atoms_z: np.ndarray):
459 return self.s0_ac + np.einsum('zac,z->ac', self.dof_zac, atoms_z)
461 @classmethod
462 def build(
463 cls,
464 s_ac,
465 rotation_scc,
466 translation_sc,
467 atommap_sa,
468 C_cv,
469 *,
470 log,
471 ):
472 ns, na = atommap_sa.shape
473 B_ascac = np.zeros((na, ns, 3, na, 3), int)
474 for s, U_cc in enumerate(rotation_scc):
475 for a in range(na):
476 a2 = atommap_sa[s, a]
477 B_ascac[a, s, :, a] = U_cc.T
478 B_ascac[a, s, :, a2] -= np.eye(3, dtype=int)
479 B_EA = B_ascac.reshape((na * ns * 3, na * 3))
480 # Extra translational gauge degrees of freedom
481 B_A = np.zeros((na * 3, 3))
482 for a in range(na):
483 B_A[(a * 3) : (a * 3 + 3), :] = np.eye(3)
484 B_EA = np.vstack([B_EA, B_A.T])
486 # Make sure the old svd code reproduces the same result
487 U, S, Vh = np.linalg.svd(B_EA, False)
488 tol = 1e-6
489 null_mask = S < tol
490 nullspace = Vh[null_mask]
492 # def same_rowspace(N, M, tol=1e-10):
493 # A = np.vstack([N, M])
494 # rA = np.linalg.matrix_rank(A, tol)
495 # rN = np.linalg.matrix_rank(N, tol)
496 # rM = np.linalg.matrix_rank(M, tol)
497 # return rA == rN == rM
498 # assert same_rowspace(nullspace, nullspace2)
500 # Just make the printing prettyer for now
501 nullspace = np.where(np.abs(nullspace) < 1e-10, 0, nullspace)
503 s0_ac = symmetrize_atoms(
504 s_ac,
505 rotation_scc,
506 translation_sc,
507 atommap_sa,
508 )
510 log(f'Atomic degrees of freedom: {len(nullspace)}')
512 dof_zac = nullspace.reshape((-1, na, 3))
514 if len(dof_zac):
515 dof_zav = np.einsum('zac,cv->zav', dof_zac, C_cv)
516 # Normalize such that the distance in Cartesian real space
517 # is reflected on the generalized coordinate
518 dof_zac /= np.max(np.linalg.norm(dof_zav, axis=2), axis=1)[
519 :, None, None
520 ]
522 return SymmetryAdaptedScaledCoordinates(dof_zac, s0_ac)
525class SymmetryAdaptedAtoms(Optimizable):
526 """Implementation of symmetry adapted atoms
528 Symmetry adapted atoms WILL symmetrize the actual_atoms given to init.
530 SymmetryAdaptedAtoms does not behave like Atoms object, but will expose the
531 __ase_optimizable__ protocol, so it can be optimized with ASE.
532 """
534 def __init__(
535 self,
536 actual_atoms: Atoms,
537 symmetries: AtomsSymmetries,
538 log=print,
539 cell_coordinates: SymmetryAdaptedCellCoordinates | None = None,
540 atom_coordinates=None,
541 value_z=None,
542 fixcell: bool = False,
543 symmetry_maxerror: float = 1e-7,
544 ):
545 self.actual_atoms = actual_atoms
546 self.symmetries = symmetries
548 # XXX remove these attributes:
549 self.symmetry_force_violation = np.inf
550 self.fmax = 0.01
552 if cell_coordinates is None:
553 pretty_subheader('Symmetry adapted cell coordinates', log)
554 cell_coordinates = SymmetryAdaptedCellCoordinates.build(
555 self.actual_atoms.cell,
556 self.actual_atoms.pbc,
557 self.symmetries.rotation_scc,
558 log=log,
559 fixcell=fixcell,
560 )
562 self.cell_coordinates = cell_coordinates
564 if atom_coordinates is None:
565 pretty_subheader('Symmetry adapted atomic coordinates', log)
566 atom_coordinates = SymmetryAdaptedScaledCoordinates.build(
567 self.actual_atoms.get_scaled_positions(),
568 self.symmetries.rotation_scc,
569 self.symmetries.translation_sc,
570 self.symmetries.atommap_sa,
571 self.cell_coordinates.C_cv,
572 log=log,
573 )
574 pretty_atomic_dofs(actual_atoms, atom_coordinates.dof_zac, log=log)
576 assert isinstance(atom_coordinates, SymmetryAdaptedScaledCoordinates)
577 self.atom_coordinates = atom_coordinates
579 # s_ac = dof_zac s_z -> ds_ac/d_sz = dof_zac
580 # dR_av / dsz = dR_av / d_sac ds_ac / ds_z
581 # R_av = s_ac C_cv
582 #
583 # self.actual_atoms.set_cell(self.cell_coordinates.C_cv,
584 # scale_atoms=True)
585 #
586 # self.actual_atoms.wrap()
587 # self.actual_atoms.set_scaled_positions(self.S_ac)
588 # if 1:
589 # log('Skipping sanity checks for now')
590 # else:
591 # pass
592 # # new_positions = atoms.get_positions()
593 # # dR_av = new_positions - old_positions
594 # # s_ac = np.linalg.solve(self.C_cv, dR_av.T)
595 # # assert (
596 # # np.max(np.abs(new_positions.flatten() -
597 # # old_positions.flatten()))
598 # # < symprec
599 # # )
601 self._ndofs_cell = len(self.cell_coordinates.dM_zcc)
602 self._ndofs_atoms = len(self.atom_coordinates.dof_zac)
603 self._ndofs = self._ndofs_cell + self._ndofs_atoms
605 if value_z is None:
606 value_z = np.zeros(self._ndofs)
608 self.value_z = value_z
609 # !!! This actually symmetrizes actual atoms
610 self.set_x(self.value_z)
611 if fixcell:
612 # For fixed-cell optimizations, only accept cells
613 # that are already symmetric. We can relax this restriction
614 # of there are any use cases for doing so.
615 cell_error = np.linalg.norm(
616 self.actual_atoms.cell - self.cell_coordinates.C_cv
617 ).max()
618 if cell_error > symmetry_maxerror:
619 raise ValueError(
620 f'Symmetrized cell differs by {cell_error:g} '
621 'from original cell but is allowed to differ only '
622 'by up to symmetry_maxerror={symmetry_maxerror:g}. '
623 )
625 self.actual_atoms.wrap()
627 def datafy(self):
628 return {
629 'actual_atoms': self.actual_atoms,
630 'symmetries': asdict(self.symmetries),
631 'value_z': self.value_z,
632 'cell_coordinates': asdict(self.cell_coordinates),
633 'atom_coordinates': asdict(self.atom_coordinates),
634 }
636 @classmethod
637 def undatafy(cls, dct, calc):
638 dct = dct.copy()
639 dct['symmetries'] = AtomsSymmetries(**dct['symmetries'])
640 dct['cell_coordinates'] = SymmetryAdaptedCellCoordinates(
641 **dct['cell_coordinates']
642 )
643 dct['atom_coordinates'] = SymmetryAdaptedScaledCoordinates(
644 **dct['atom_coordinates']
645 )
646 dct['actual_atoms'].calc = calc
647 return cls(**dct, log=lambda *args, **kwargs: None)
649 @classmethod
650 def from_atoms_spglib(cls, atoms, log=print, *, symprec=1e-4, **kwargs):
651 # We set default symprec=1e-4 because structures from POSCARS
652 # often have 5 digits.
653 symmetries = AtomsSymmetries.from_spglib_auto(atoms, symprec=symprec)
654 return cls(atoms, symmetries, log=log, **kwargs)
656 @classmethod
657 def from_spglib_dataset(cls, atoms, dataset, log=print, **kwargs):
658 # XXX This will fail in atommaps if atoms are not exactly symmetrized.
659 # Better to not fail now, but rather wait until after the
660 # symmetrization and then check the atommaps against the
661 # symmetrized atoms with a fine tolerance.
662 #
663 # Here we can only promise ~symprec tolerance.
664 symmetries = AtomsSymmetries.from_spglib(atoms, dataset)
665 return cls(atoms, symmetries, log=log, **kwargs)
667 @classmethod
668 def from_atoms(cls, atoms, **kwargs):
669 return cls.from_atoms_spglib(atoms, **kwargs)
671 @classmethod
672 def from_atoms_GPAW(cls, atoms, log=print, *, symprec, symmorphic):
673 # XXX Move this to GPAW.
674 symmetries = AtomsSymmetries.from_GPAW(
675 atoms,
676 tolerance=symprec,
677 symmorphic=symmorphic,
678 log=log,
679 )
680 return cls(atoms, symmetries, log=log)
682 @property
683 def stress_conv(self):
684 S_vv = self.actual_atoms.get_stress(voigt=False)
685 C_cv = self.actual_atoms.cell
686 S_cc = C_cv @ S_vv @ np.linalg.inv(C_cv)
687 for c, periodic in enumerate(self.actual_atoms.pbc):
688 if periodic:
689 continue
690 S_cc[c, :] = 0.0
691 S_cc[:, c] = 0.0
692 S_vv = np.linalg.inv(C_cv) @ S_cc @ C_cv
693 return np.linalg.norm(S_vv)
695 # Properties for internal degrees of freedom
696 @property
697 def cell_z(self):
698 return self.get_x()[: self._ndofs_cell]
700 # From here on out, these are the __ase_optimizable__ interface
701 def ndofs(self):
702 return self._ndofs
704 def get_x(self):
705 return self.value_z.copy()
707 def set_x(self, x):
708 self.value_z[:] = x
709 if self._ndofs_cell > 0:
710 self.actual_atoms.set_cell(
711 self.cell_coordinates.get_cell(self.cell_z)
712 )
713 self.actual_atoms.set_scaled_positions(
714 self.atom_coordinates.get_scaled_coordinates(self.atoms_z)
715 )
717 def get_Fback_av(self, F_av, C_cv, atoms_grad_z):
718 natomz = len(self.atom_coordinates.dof_zac)
719 # For sanity check, we want to project the atomic gradient back
720 # minimizing the Cartesian metrix.
721 if natomz > 0:
722 dof_zX = np.einsum(
723 'cv,zac->zav', C_cv, self.atom_coordinates.dof_zac
724 ).reshape((natomz, -1))
725 back_Fav = -(
726 dof_zX.T @ np.linalg.inv(dof_zX @ dof_zX.T) @ atoms_grad_z
727 ).reshape(F_av.shape)
728 else:
729 # Even if there is degrees of freedom, it is possible to
730 # get symmetry violation
731 back_Fav = np.zeros_like(F_av)
732 return back_Fav
734 def get_Sback_vv(self, S_vv, A_zV, grad_z):
735 ncellz = len(A_zV)
736 if ncellz > 0:
737 return (A_zV.T @ np.linalg.inv(A_zV @ A_zV.T) @ grad_z).reshape(
738 (3, 3)
739 )
741 # Even if there are no cell degrees of freedom, the stress can
742 # still violate the imposed symmetry in Cartesian space.
743 return np.zeros((3, 3))
745 def _get_gradient(self, fmax, smax):
746 grad_z = np.zeros(self._ndofs_cell)
747 if self._ndofs_cell:
748 S_vv = self.actual_atoms.get_stress(voigt=False)
749 else:
750 S_vv = np.zeros((3, 3))
751 C_cv = self.cell_coordinates.get_cell(self.cell_z)
752 V = np.linalg.det(C_cv)
753 Cinv = np.linalg.inv(C_cv)
755 M_cc = self.cell_coordinates.get_M_cc(self.cell_z)
757 # TODO: Move to SymmetryAdaptedCellCoordinates
758 # dE/deps_vv deps_vv/dC_cv dC_cv/dz
760 ncellz = len(self.cell_coordinates.dM_zcc)
761 A_zV = np.zeros((ncellz, 9))
762 for z in range(ncellz):
763 dC_cv = (
764 chol_derivative(M_cc, self.cell_coordinates.dM_zcc[z])
765 @ self.cell_coordinates.rot_vv.T
766 )
767 A_zV[z] = (V * (Cinv @ dC_cv + dC_cv.T @ Cinv.T) / 2).reshape(9)
769 grad_z[:] = np.dot(A_zV, S_vv.reshape(9))
770 back_Svv = self.get_Sback_vv(S_vv, A_zV, grad_z)
772 def get_mask_3x3(pbc):
773 from ase._4.optimize.frechet import default_mask
774 from ase.stress import voigt_6_to_full_3x3_stress
776 mask_6 = default_mask(pbc)
777 return voigt_6_to_full_3x3_stress(mask_6)
779 mask_3x3 = get_mask_3x3(self.actual_atoms.pbc)
781 dS_vv = S_vv * mask_3x3 - back_Svv
782 symmetry_stress_violation = np.linalg.norm(dS_vv)
784 if symmetry_stress_violation > smax:
785 import warnings
787 warnings.warn(
788 'Warning!!! Back projection of symmetry adapted '
789 'stresses to Cartesian space failed by '
790 f'{symmetry_stress_violation:7.13f}\n'
791 f'Cartesian stress:\n{S_vv * mask_3x3}\n'
792 f'Back projected stress:\n{back_Svv}'
793 )
795 F_av = self.actual_atoms.get_forces()
796 # dE/ds_z = dE/dR_av dR_av/ds_ac ds_ac/ds_z
797 # R_av = ds_ac C_cv
798 # ds_ac = self.dof_zac S_z
800 atoms_grad_z = -np.einsum(
801 'av,cv,zac->z', F_av, C_cv, self.atom_coordinates.dof_zac
802 )
804 back_Fav = self.get_Fback_av(F_av, C_cv, atoms_grad_z)
806 dF_av = F_av - back_Fav
807 symmetry_force_violation = np.max(np.linalg.norm(dF_av, axis=1))
809 if symmetry_force_violation > fmax / 20:
810 # Should probably be logged somehow instead of being a warning
811 # as such. This may happen if the code's forces are noisy.
812 import warnings
814 warning_chunks = [
815 'Warning!!! Back projection of symmetry adapted'
816 ' forces to Cartesian space failed by '
817 f'{symmetry_force_violation:7.13f}\n'
818 'atom Obtained force Back projected force'
819 ]
821 for a, (F_v, F2_v) in enumerate(zip(F_av, back_Fav)):
822 warning_chunks.append(
823 f'{a:5d} {F_v[0]:7.4f} {F_v[1]:7.4f} {F_v[2]:7.4f}'
824 f' {F2_v[0]:7.4f} {F2_v[1]:7.4f} {F2_v[2]:7.4f}'
825 )
827 warnings.warn('\n'.join(warning_chunks))
829 converged = self._converged(back_Fav, fmax, back_Svv, smax)
831 from ase._4.optimize.symopt import SymGradient
833 return SymGradient(
834 gradient=np.hstack([grad_z, atoms_grad_z]),
835 backF_av=back_Fav,
836 backS_vv=back_Svv,
837 symmetry_force_violation=symmetry_force_violation,
838 symmetry_stress_violation=symmetry_stress_violation,
839 converged=converged,
840 fnorm=self._fnorm(back_Fav),
841 snorm=self._snorm(back_Svv),
842 volume=self.actual_atoms.cell.volume,
843 )
845 def get_gradient(self):
846 grad_obj = self._get_gradient(fmax=self.fmax, smax=self.smax)
847 self.back_Fav = grad_obj.backF_av
848 self.back_Svv = grad_obj.backS_vv
849 self.symmetry_force_violation = grad_obj.symmetry_force_violation
850 self.symmetry_stress_violation = grad_obj.symmetry_stress_violation
851 return grad_obj.gradient
853 def gradient_norm(self, grad_z):
854 # Go actually to cell metric
855 return np.max(np.abs(grad_z))
857 def get_value(self):
858 return self.actual_atoms.get_potential_energy()
860 def iterimages(self):
861 return [self.actual_atoms]
863 def converged(self, gradient, fmax):
864 # Convergence needs to be from the back projected forces.
865 # The symmetry violating forces will never converge.
866 return self._converged(
867 backF_av=self.back_Fav,
868 fmax=self.fmax,
869 smax=self.smax,
870 backS_av=self.stress_conv,
871 ) # XXX use backS_av
873 def _fnorm(self, backF_av):
874 return np.max(np.linalg.norm(backF_av, axis=1))
876 def _snorm(self, backS_av):
877 return abs(backS_av).max()
879 def _converged(self, backF_av, fmax, backS_av, smax):
880 Fconv = self._fnorm(backF_av)
881 return Fconv < fmax and self._snorm(backS_av) < smax
883 @property
884 def atoms_z(self):
885 return self.get_x()[self._ndofs_cell :]
887 def logheaders(self):
888 dtitles = ' '.join([f'q{i:02d}' for i in range(len(self.atoms_z))])
889 return (
890 f'iter time E maxF maxS maxG a1 a2'
891 f' a3 L1 L2 L3 {dtitles}'
892 ' log_10 viol. (F / S)'
893 )
895 def step_to_string(self, i, fmax, smax, gradient_obj):
896 import time
898 tstr = time.strftime('%H:%M:%S')
899 E = self.actual_atoms.get_potential_energy()
900 g = gradient_obj.gradient # XXX clean up
901 Fmax = gradient_obj.fnorm
902 sFmax = f'{Fmax:7.3f}'
904 if Fmax < fmax:
905 sFmax = green(sFmax)
907 Smax = gradient_obj.snorm
908 sSmax = f'{Smax:7.4f}'
909 if Smax < smax:
910 sSmax = green(sSmax)
912 gmax = np.max(np.abs(g), initial=0.0)
914 cell = self.actual_atoms.cell
915 a = cell.angles()
916 l = cell.lengths()
917 cell = f'{a[0]:5.1f} {a[1]:5.1f} {a[2]:5.1f} '
918 cell += f'{l[0]:7.3f} {l[1]:7.3f} {l[2]:7.3f}'
920 dofs = ''
921 for Z in self.atoms_z:
922 dofs += f' {Z:6.3f}'
923 if gradient_obj.symmetry_force_violation:
924 syviol = np.log10(gradient_obj.symmetry_force_violation)
925 else:
926 syviol = -np.inf
927 symviol = f'{syviol:4.1f}'
928 if syviol < fmax:
929 symviol = green(symviol)
930 if gradient_obj.symmetry_stress_violation:
931 syviol2 = np.log10(gradient_obj.symmetry_stress_violation)
932 else:
933 syviol2 = -np.inf
934 symviol2 = f'{syviol2:4.1f}'
935 if syviol2 < smax:
936 symviol2 = green(symviol2)
937 return (
938 f'{i:5d} {tstr} {E:9.5f} {sFmax} {sSmax} {gmax:7.3f}'
939 f' {cell}{dofs} {symviol} {symviol2}'
940 )
943def print_headers(atoms, log):
944 pretty_header('Symmetry adapted Cell and Atomic Relaxation', log)
945 pretty_subheader('Original atoms', log)
946 pprint_atoms(atoms, log)
949def print_symmetrized_atoms(atoms, log):
950 pretty_subheader('Symmetrized atoms', log)
951 pprint_atoms(atoms, log)
954class Relax:
955 """General utility class to log and perform symmetry adapted relax."""
957 def __init__(
958 self,
959 symmorphic=False,
960 logfile=None,
961 teelog=True,
962 *,
963 atoms: Atoms,
964 calc,
965 optimizer_factory,
966 symprec,
967 comm,
968 atoms_symmetries=None,
969 ):
970 self.comm = comm
971 self.logfile = logfile
972 self.logf = None
973 if self.logfile:
974 if self.comm.rank == 0:
975 self.logf = open(self.logfile, 'w')
976 self.teelog = teelog
978 if atoms.calc is not None:
979 raise ValueError('Do not attach a calculator to Atoms yet.')
981 self.symprec = symprec
983 print_headers(atoms, self.log)
985 self.atoms = atoms
986 if atoms_symmetries is None:
987 atoms_symmetries = AtomsSymmetries.from_spglib_auto(
988 self.atoms, symprec=symprec
989 )
991 self.symmetry_adapted_atoms = SymmetryAdaptedAtoms(
992 self.atoms, atoms_symmetries
993 )
995 # Now, with cell and atoms symmetrized,
996 # it is safe to assign the calculator
997 # TODO: Implement Setter or something
998 self.calc = calc
999 self.symmetry_adapted_atoms.actual_atoms.calc = calc()
1001 print_symmetrized_atoms(
1002 self.symmetry_adapted_atoms.actual_atoms, self.log
1003 )
1005 self.optimizer_factory = optimizer_factory
1006 self.optimizer = self.optimizer_factory(self.symmetry_adapted_atoms)
1008 def log(self, *args, **kwargs):
1009 if self.comm.rank == 0:
1010 if self.logf:
1011 print(*args, **kwargs, flush=True, file=self.logf)
1012 if self.teelog:
1013 print(*args, **kwargs)
1015 def run(self, *, fmax=0.01, smax=0.0001, steps=20):
1016 # Why would symmetry adapted atoms care about smax and fmax
1017 # But it needs to be ase optimizable, so it needs to do that
1018 self.symmetry_adapted_atoms.smax = smax
1019 self.symmetry_adapted_atoms.fmax = fmax
1021 self.smax = smax
1022 self.fmax = fmax
1023 self.maxiter = steps
1025 self.log(self.symmetry_adapted_atoms.logheaders())
1027 for i, _ in enumerate(self.optimizer.irun(fmax=fmax)):
1028 gradient_obj = self.symmetry_adapted_atoms._get_gradient(
1029 fmax=fmax, smax=smax
1030 )
1031 line = self.symmetry_adapted_atoms.step_to_string(
1032 i, self.fmax, self.smax, gradient_obj
1033 )
1034 self.log(line)
1036 if i > self.maxiter or i > 40:
1037 self.log(f'Not converged in {self.maxiter} or 40 steps.')
1038 return False
1040 return True
1042 def visualize_modes(self):
1043 from ase.io.trajectory import Trajectory
1045 with Trajectory('modes.traj', 'w') as traj:
1046 for z in range(self.ndofs()):
1047 x = np.zeros((self.ndofs(),))
1048 for i in np.arange(0, 6 * np.pi, 0.1):
1049 x[z] = np.sin(i) * 0.004
1050 self.set_x(x)
1051 traj.write(self.atoms.copy())