Coverage for ase/filters.py: 86.21%
261 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"""Filters"""
3from __future__ import annotations
5from functools import cached_property
6from typing import TYPE_CHECKING, Never
7from warnings import warn
9import numpy as np
10import numpy.typing as npt
12from ase.calculators.calculator import PropertyNotImplementedError
13from ase.stress import full_3x3_to_voigt_6_stress, voigt_6_to_full_3x3_stress
14from ase.utils import deprecated
15from ase.utils.abc import Optimizable
17if TYPE_CHECKING:
18 from ase import Atom, Atoms
19 from ase.calculators.calculator import BaseCalculator
20 from ase.cell import Cell
21 from ase.constraints.constraint import FixConstraint
24__all__ = [
25 'Filter',
26 'StrainFilter',
27 'UnitCellFilter',
28 'FrechetCellFilter',
29 'ExpCellFilter',
30]
33class OptimizableFilter(Optimizable):
34 def __init__(self, filterobj: Filter) -> None:
35 self.filterobj = filterobj
37 def get_x(self) -> npt.NDArray[np.floating]:
38 return self.filterobj.get_positions().ravel()
40 def set_x(self, x: npt.NDArray[np.floating]) -> None:
41 self.filterobj.set_positions(x.reshape(-1, 3))
43 def get_gradient(self) -> np.ndarray:
44 return -self.filterobj.get_forces().ravel()
46 @cached_property
47 def _use_force_consistent_energy(self) -> bool:
48 # This boolean is in principle invalidated if the
49 # calculator changes. This can lead to weird things
50 # in multi-step optimizations.
51 try:
52 self.filterobj.get_potential_energy(force_consistent=True)
53 except PropertyNotImplementedError:
54 return False
55 else:
56 return True
58 def get_value(self) -> float:
59 force_consistent = self._use_force_consistent_energy
60 return self.filterobj.get_potential_energy(
61 force_consistent=force_consistent
62 )
64 def ndofs(self) -> int:
65 return 3 * len(self.filterobj)
67 def iterimages(self) -> Atoms:
68 return self.filterobj.iterimages()
71class Filter:
72 def __init__(
73 self,
74 atoms: Atoms,
75 indices=None,
76 mask: np.ndarray | None = None,
77 ):
78 """Filter "hiding" specified atoms.
80 This filter "hides" some atoms in the ASE :class:`~ase.Atoms` object
81 and thus fixes their positions during structure optimization.
83 This can be used as an alternative to the
84 :class:`~ase.constraints.FixAtoms` constraint.
86 Parameters
87 ----------
88 atoms : :class:`~ase.Atoms`
89 ASE :class:`~ase.Atoms` object.
90 indices : list[int] | None, default: None
91 Indices for of the atoms that should remain visible.
92 mask : np.ndarray | None, default: None
93 One boolean per atom indicating if the atom should remain
94 visible or not.
96 Notes
97 -----
98 You must supply either ``indices`` or ``mask``.
100 If :class:`~ase.io.Trajectory` tries to save this object,
101 it will instead save the underlying :class:`~ase.Atoms` object.
102 To prevent this, override the :meth:`~Filter.iterimages` method.
104 Examples
105 --------
106 >>> from ase.build import molecule
107 >>> from ase.filters import Filter
108 >>> atoms=molecule('H2O')
109 >>> list(atoms.symbols)
110 ['O', 'H', 'H']
111 >>> atoms.get_positions()
112 array([[ 0. , 0. , 0.119262],
113 [ 0. , 0.763239, -0.477047],
114 [ 0. , -0.763239, -0.477047]])
115 >>> f1 = Filter(atoms, indices=[1, 2])
116 >>> f2 = Filter(atoms, mask=[0, 1, 1])
117 >>> f3 = Filter(atoms, mask=[a.z == 1 for a in atoms])
118 >>> f1.get_positions()
119 array([[ 0. , 0.763239, -0.477047],
120 [ 0. , -0.763239, -0.477047]])
122 In all three filters, only the hydrogen atoms are made visible.
123 When asking for the positions, only the positions of the hydrogen atoms
124 are returned.
126 """
128 self.atoms = atoms
129 self.constraints: list[FixConstraint] = []
130 # Make self.info a reference to the underlying atoms' info dictionary.
131 self.info = self.atoms.info
133 if indices is None and mask is None:
134 raise ValueError('Use "indices" or "mask".')
135 if indices is not None and mask is not None:
136 raise ValueError('Use only one of "indices" and "mask".')
138 if mask is not None:
139 self.index = np.asarray(mask, bool)
140 self.n = self.index.sum()
141 else:
142 self.index = np.asarray(indices, int)
143 self.n = len(self.index)
145 def iterimages(self) -> Atoms:
146 # Present the real atoms object to Trajectory and friends
147 return self.atoms.iterimages()
149 def get_cell(self) -> Cell:
150 """Returns the computational cell.
152 The computational cell is the same as for the original system.
153 """
154 return self.atoms.get_cell()
156 def get_pbc(self) -> npt.NDArray[np.bool_]:
157 """Returns the periodic boundary conditions.
159 The boundary conditions are the same as for the original system.
160 """
161 return self.atoms.get_pbc()
163 def get_positions(self):
164 "Return the positions of the visible atoms."
165 return self.atoms.get_positions()[self.index]
167 def set_positions(self, positions, **kwargs):
168 "Set the positions of the visible atoms."
169 pos = self.atoms.get_positions()
170 pos[self.index] = positions
171 self.atoms.set_positions(pos, **kwargs)
173 positions = property(
174 get_positions, set_positions, doc='Positions of the atoms'
175 )
177 def get_momenta(self) -> npt.NDArray[np.floating]:
178 "Return the momenta of the visible atoms."
179 return self.atoms.get_momenta()[self.index]
181 def set_momenta(self, momenta: npt.NDArray[np.floating], **kwargs) -> None:
182 "Set the momenta of the visible atoms."
183 mom = self.atoms.get_momenta()
184 mom[self.index] = momenta
185 self.atoms.set_momenta(mom, **kwargs)
187 def get_atomic_numbers(self) -> npt.NDArray[np.integer]:
188 "Return the atomic numbers of the visible atoms."
189 return self.atoms.get_atomic_numbers()[self.index]
191 def set_atomic_numbers(
192 self,
193 atomic_numbers: npt.NDArray[np.integer],
194 ) -> None:
195 "Set the atomic numbers of the visible atoms."
196 z = self.atoms.get_atomic_numbers()
197 z[self.index] = atomic_numbers
198 self.atoms.set_atomic_numbers(z)
200 def get_tags(self) -> npt.NDArray[np.integer]:
201 "Return the tags of the visible atoms."
202 return self.atoms.get_tags()[self.index]
204 def set_tags(self, tags: npt.NDArray[np.integer]) -> None:
205 "Set the tags of the visible atoms."
206 tg = self.atoms.get_tags()
207 tg[self.index] = tags
208 self.atoms.set_tags(tg)
210 def get_forces(self, *args, **kwargs):
211 return self.atoms.get_forces(*args, **kwargs)[self.index]
213 def get_stress(self, *args, **kwargs) -> npt.NDArray[np.floating]:
214 return self.atoms.get_stress(*args, **kwargs)
216 def get_stresses(self, *args, **kwargs) -> npt.NDArray[np.floating]:
217 return self.atoms.get_stresses(*args, **kwargs)[self.index]
219 def get_masses(self) -> npt.NDArray[np.floating]:
220 return self.atoms.get_masses()[self.index]
222 def get_potential_energy(self, **kwargs):
223 """Calculate potential energy.
225 Returns the potential energy of the full system.
226 """
227 return self.atoms.get_potential_energy(**kwargs)
229 def get_chemical_symbols(self) -> list[str]:
230 return self.atoms.get_chemical_symbols()
232 def get_initial_magnetic_moments(self) -> npt.NDArray[np.floating]:
233 return self.atoms.get_initial_magnetic_moments()
235 def get_calculator(self) -> BaseCalculator:
236 """Returns the calculator.
238 WARNING: The calculator is unaware of this filter, and sees a
239 different number of atoms.
240 """
241 return self.atoms.calc
243 @property
244 def calc(self) -> BaseCalculator:
245 return self.atoms.calc
247 def get_celldisp(self) -> npt.NDArray[np.floating]:
248 return self.atoms.get_celldisp()
250 def has(self, name: str) -> bool:
251 "Check for existence of array."
252 return self.atoms.has(name)
254 def __len__(self) -> int:
255 "Return the number of movable atoms."
256 return self.n
258 def __getitem__(self, i: int) -> Atom:
259 "Return an atom."
260 return self.atoms[self.index[i]]
262 def __ase_optimizable__(self) -> OptimizableFilter:
263 return OptimizableFilter(self)
266class StrainFilter(Filter):
267 def __init__(
268 self,
269 atoms: Atoms,
270 mask: np.ndarray | None = None,
271 include_ideal_gas: bool = False,
272 ) -> None:
273 """Filter applying a homogeneous strain to a list of atoms.
275 This class is used together with an ASE optimizer in order to optimize
276 the cell shape with minimizing the stress while keeping the scaled
277 positions fixed.
279 This class regards the strain of the cell as the generalized positions
280 and the global stress tensor (times the volume) as the generalized
281 force.
283 The stress and strain are presented as 6-vectors, the order of the
284 components follow the standard engineering practice:
285 ``xx``, ``yy``, ``zz``, ``yz``, ``xz``, ``xy``.
287 Parameters
288 ----------
289 atoms : :class:`~ase.Atoms`
290 ASE :class:`~ase.Atoms` object.
291 mask : np.ndarray | None, default: None
292 Array of six booleans, indicating which of the six independent
293 components of the strain that are allowed to become non-zero.
294 The default (:obj:`None`) relaxes all the six components, i.e.,
295 ``[True, True, True, True, True, True]``.
296 include_ideal_gas : bool, default: False
297 If True, the kinetic contribution of the stress is also considered.
299 Notes
300 -----
301 If this filter is used together with :class:`~ase.optimize.MDMin`,
302 the timestep (``dt``) to be used depends on the system size.
303 0.01/x where x is a typical dimension seems like a good choice.
305 """
307 self.strain = np.zeros(6)
308 self.include_ideal_gas = include_ideal_gas
310 if mask is None:
311 mask = np.ones(6)
312 else:
313 mask = np.array(mask)
315 Filter.__init__(self, atoms=atoms, mask=mask)
316 self.mask = mask
317 self.origcell = atoms.get_cell()
319 def get_positions(self):
320 return self.strain.reshape((2, 3)).copy()
322 def set_positions(self, new):
323 new = new.ravel() * self.mask
324 eps = np.array(
325 [
326 [1.0 + new[0], 0.5 * new[5], 0.5 * new[4]],
327 [0.5 * new[5], 1.0 + new[1], 0.5 * new[3]],
328 [0.5 * new[4], 0.5 * new[3], 1.0 + new[2]],
329 ]
330 )
332 self.atoms.set_cell(np.dot(self.origcell, eps), scale_atoms=True)
333 self.strain[:] = new
335 def get_forces(self, **kwargs):
336 stress = self.atoms.get_stress(include_ideal_gas=self.include_ideal_gas)
337 return -self.atoms.get_volume() * (stress * self.mask).reshape((2, 3))
339 def has(self, x: str) -> bool:
340 return self.atoms.has(x)
342 def __len__(self) -> int:
343 return 2
346class UnitCellFilter(Filter):
347 def __init__(
348 self,
349 atoms: Atoms,
350 mask: np.ndarray | None = None,
351 cell_factor: float | None = None,
352 hydrostatic_strain: bool = False,
353 constant_volume: bool = False,
354 orig_cell: np.ndarray | None = None,
355 scalar_pressure: float = 0.0,
356 ) -> None:
357 r"""Filter returning the atomic forces and the cell stresses together.
359 This class is used together with an ASE optimizer in order to minimize
360 both the atomic forces and the cell stresses simultaneously.
362 Degrees of freedom are the positions in the original undeformed cell,
363 plus the deformation gradient :math:`\mathbf{F}` (extra 3 "atoms").
364 If :math:`\mathbf{r}_i` denotes a Cartesian atomic position, the
365 corresponding atomic degree of freedom is
367 .. math::
368 \mathbf{q}_i = \mathbf{F}^{-1}\mathbf{r}_i.
370 Thus, when :math:`\mathbf{F}` changes while :math:`\mathbf{q}_i` is
371 kept fixed, the atoms follow the cell deformation affinely,
372 :math:`\mathbf{r}_i = \mathbf{F}\mathbf{q}_i`. This separates
373 homogeneous cell deformation from internal atomic displacements.
374 The cell forces are the negative derivatives of the energy with
375 respect to :math:`\mathbf{F}`.
376 For full details, see [1]_.
378 .. [1]
379 E. B. Tadmor, G. S. Smith, N. Bernstein, and E. Kaxiras,
380 Phys. Rev. B 59, 235 (1999).
381 :doi:`10.1103/PhysRevB.59.235`
383 Parameters
384 ----------
385 atoms : :class:`~ase.Atoms`
386 ASE :class:`~ase.Atoms` object.
387 mask : np.ndarray | None, default: None
388 Mask indicating which of the six independent components of the
389 strain are relaxed.
391 - :obj:`True`: relax to zero
392 - :obj:`False`: fixed, ignore this component
394 cell_factor: float, default: float(len(atoms))
395 Factor by which deformation gradient is multiplied to put
396 it on the same scale as the positions when assembling
397 the combined position/cell vector. The stress contribution to
398 the forces is scaled down by the same factor. This can be thought
399 of as a very simple preconditioners. Default is number of atoms
400 which gives approximately the correct scaling.
402 hydrostatic_strain: bool, default: False
403 Constrain the cell by only allowing hydrostatic deformation.
404 The virial tensor is replaced by `np.diag([np.trace(virial)] * 3)`.
406 .. versionadded:: 3.17.0
408 constant_volume: bool, default: False
409 Project out the diagonal elements of the virial tensor to allow
410 relaxations at constant volume, e.g. for mapping out an
411 energy-volume curve. Note: this only approximately conserves
412 the volume and breaks energy/force consistency so can only be
413 used with optimizers that do require do a line minimisation
414 (e.g. :class:`~ase.optimize.FIRE`).
416 .. versionadded:: 3.17.0
418 scalar_pressure: float, default: 0.0
419 Applied pressure in eV/Å3 to use for enthalpy pV term.
420 (Note: 1 eV/Å3 ≈ 160.2 GPa).
421 For example, set ``1.0 * ase.units.GPa`` to provide 1 GPa.
422 As above, this breaks energy/force consistency.
424 .. versionadded:: 3.17.0
426 Notes
427 -----
428 :class:`FrechetCellFilter` will probably perform better.
430 Examples
431 --------
432 You can still use constraints on the atoms, e.g.
433 :class:`~ase.constraints.FixAtoms`, to control
434 the relaxation of the atoms.
436 >>> from ase.build import bulk
437 >>> from ase.constraints import FixAtoms
438 >>> atoms = bulk('BN', 'wurtzite', a=2.55, c=4.23)
439 >>> # this should be equivalent to the StrainFilter
440 >>> atoms.set_constraint(FixAtoms(mask=[True for atom in atoms]))
441 >>> ucf = UnitCellFilter(atoms)
442 """
444 from ase._4.optimize.cellutil import CellUtility
446 Filter.__init__(self, atoms=atoms, indices=range(len(atoms)))
447 self.atoms = atoms
449 if orig_cell is None:
450 orig_cell = atoms.get_cell()
451 else:
452 orig_cell = orig_cell
454 self._utility = CellUtility(
455 orig_cell.copy(),
456 mask=mask,
457 scalar_pressure=scalar_pressure,
458 constant_volume=constant_volume,
459 hydrostatic_strain=hydrostatic_strain,
460 )
462 self.stress = None
464 if cell_factor is None:
465 cell_factor = float(len(atoms))
466 self.cell_factor = cell_factor
467 self.copy = self.atoms.copy
468 self.arrays = self.atoms.arrays
470 @property
471 def hydrostatic_strain(self) -> bool:
472 return self._utility.hydrostatic_strain
474 @hydrostatic_strain.setter
475 def hydrostatic_strain(self, value: bool) -> None:
476 # Probably we do not need these setters but at least one precon
477 # test unwisely does hasattr() magic with these.
478 self._utility.hydrostatic_strain = value
480 @property
481 def constant_volume(self) -> bool:
482 return self._utility.constant_volume
484 @constant_volume.setter
485 def constant_volume(self, value: bool) -> None:
486 self._utility.constant_volume = value
488 @property
489 def scalar_pressure(self) -> float:
490 return self._utility.scalar_pressure
492 @scalar_pressure.setter
493 def scalar_pressure(self, value: float) -> None:
494 self._utility.scalar_pressure = value
496 @property
497 def mask(self) -> np.ndarray:
498 return self._utility.mask3x3
500 @property
501 def orig_cell(self) -> npt.NDArray[np.floating]:
502 return self._utility.orig_cell
504 @orig_cell.setter
505 def orig_cell(self, value: npt.NDArray[np.floating]) -> None:
506 self._utility.orig_cell[:] = value
508 def deform_grad(self) -> npt.NDArray[np.floating]:
509 return self._utility.deform_grad(self.atoms.cell)
511 def get_positions(self):
512 """
513 this returns an array with shape (natoms + 3,3).
515 the first natoms rows are the positions of the atoms, the last
516 three rows are the deformation tensor associated with the unit cell,
517 scaled by self.cell_factor.
518 """
519 return self._utility.get_positions_unitcellfilter(
520 self.atoms.positions, self.atoms.cell, self.cell_factor
521 )
523 def set_positions(self, new, **kwargs):
524 """
525 new is an array with shape (natoms+3,3).
527 the first natoms rows are the positions of the atoms, the last
528 three rows are the deformation tensor used to change the cell shape.
530 the new cell is first set from original cell transformed by the new
531 deformation gradient, then the positions are set with respect to the
532 current cell by transforming them with the same deformation gradient
533 """
534 self._utility.set_positions_unitcellfilter(
535 new, self.atoms, self.cell_factor, **kwargs
536 )
538 def get_potential_energy(self, force_consistent=True):
539 """
540 returns potential energy including enthalpy PV term.
541 """
542 return self._utility.get_energy(self.atoms, force_consistent)
544 def get_forces(self, **kwargs):
545 """
546 returns an array with shape (natoms+3,3) of the atomic forces
547 and unit cell stresses.
549 the first natoms rows are the forces on the atoms, the last
550 three rows are the forces on the unit cell, which are
551 computed from the stress tensor.
552 """
553 stress = self.atoms.get_stress(**kwargs)
554 atoms_forces = self.atoms.get_forces(**kwargs)
556 forces, modified_stress = self._utility.get_forces_unitcellfilter(
557 atoms_forces,
558 stress,
559 cell=self.atoms.cell,
560 cell_factor=self.cell_factor,
561 )
562 self.stress = modified_stress # XXX what's this doing here?
563 return forces
565 def get_stress(self) -> Never:
566 raise PropertyNotImplementedError
568 def has(self, x: str) -> bool:
569 return self.atoms.has(x)
571 def __len__(self) -> int:
572 return len(self.atoms) + 3
575class FrechetCellFilter(UnitCellFilter):
576 def __init__(
577 self,
578 atoms,
579 mask=None,
580 exp_cell_factor=None,
581 *args,
582 **kwargs,
583 ):
584 r"""Filter returning the atomic forces and the cell stresses together.
586 This class is used together with an ASE optimizer in order to minimize
587 both the atomic forces and the cell stresses simultaneously.
589 .. versionadded:: 3.23.0
591 Degrees of freedom are the positions in the original undeformed cell,
592 plus the matrix logarithm :math:`\mathbf{U} = \log(\mathbf{F})` of the
593 deformation gradient (extra 3 "atoms"). The cell forces are computed
594 using the Fréchet derivative of the matrix exponential, giving the
595 negative derivatives of the energy with respect to :math:`\mathbf{U}`.
597 Parameters
598 ----------
599 exp_cell_factor : float, default: float(len(atoms))
600 Scaling factor for cell variables. The cell gradients in
601 :meth:`~ase.filters.FrechetCellFilter.get_forces()` is divided by
602 ``exp_cell_factor``.
603 By default, set the number of atoms. We recommend to set
604 an extensive value for this parameter.
605 *args, **kwargs
606 Additional arguments passed to :class:`~ase.filters.UnitCellFilter`.
608 Notes
609 -----
610 The original :class:`ExpCellFilter` implementation also uses the
611 matrix logarithm of the deformation gradient as the cell variable,
612 but its cell forces are not in general consistent with numerical
613 energy derivatives. :class:`FrechetCellFilter` instead evaluates the
614 required Fréchet derivatives explicitly.
615 If you would like to keep the previous behavior, please use
616 :class:`ExpCellFilter`.
618 The derivation of gradients of energy w.r.t positions and the log of the
619 deformation tensor is given in
620 https://github.com/lan496/lan496.github.io/blob/main/notes/cell_grad.pdf
621 """
623 Filter.__init__(self, atoms=atoms, indices=range(len(atoms)))
624 UnitCellFilter.__init__(
625 self,
626 atoms=atoms,
627 mask=mask,
628 *args,
629 **kwargs,
630 )
632 # We defer the scipy import to avoid high immediate import overhead
633 from scipy.linalg import expm, expm_frechet, logm
635 self.expm = expm
636 self.logm = logm
637 self.expm_frechet = expm_frechet
639 # Scaling factor for cell gradients
640 if exp_cell_factor is None:
641 exp_cell_factor = float(len(atoms))
642 self.exp_cell_factor = exp_cell_factor
644 def get_positions(self):
645 return self._utility.get_positions_frechet(
646 self.atoms.get_positions(),
647 self.atoms.get_cell(),
648 cell_factor=self.cell_factor,
649 exp_cell_factor=self.exp_cell_factor,
650 )
652 def set_positions(self, new, **kwargs):
653 self._utility.set_positions_frechet(
654 new,
655 self.atoms,
656 cell_factor=self.cell_factor,
657 exp_cell_factor=self.exp_cell_factor,
658 **kwargs,
659 )
661 def get_forces(self, **kwargs):
662 # forces on atoms are same as UnitCellFilter, we just
663 # need to modify the stress contribution
664 stress = self.atoms.get_stress(**kwargs)
665 atoms_forces = self.atoms.get_forces(**kwargs)
667 forces, convergence_crit_stress = self._utility.get_forces_frechet(
668 atoms_forces=atoms_forces,
669 stress=stress,
670 cell=self.atoms.get_cell(),
671 exp_cell_factor=self.exp_cell_factor,
672 )
674 self.stress = full_3x3_to_voigt_6_stress(convergence_crit_stress)
675 return forces
678class ExpCellFilter(UnitCellFilter):
679 @deprecated(
680 DeprecationWarning(
681 'Use FrechetCellFilter for better convergence w.r.t. '
682 'cell variables.'
683 )
684 )
685 def __init__(
686 self,
687 atoms,
688 mask=None,
689 cell_factor=None,
690 *args,
691 **kwargs,
692 ):
693 r"""Filter returning the atomic forces and the cell stresses together.
695 .. versionadded:: 3.17.0
697 .. deprecated:: 3.23.0
698 Use :class:`~ase.filters.FrechetCellFilter` for better convergence
699 w.r.t. cell variables.
701 This class is used together with an ASE optimizer in order to minimize
702 both the atomic forces and the cell stresses simultaneously.
704 Degrees of freedom are the positions in the original undeformed cell,
705 plus the log of the deformation tensor (extra 3 "atoms").
707 Parameters
708 ----------
709 cell_factor : float(DEPRECATED)
710 Retained for backwards compatibility, but no longer used.
712 .. deprecated:: 3.23.0
714 *args, **kwargs
715 Additional arguments passed to :class:`~ase.filters.UnitCellFilter`.
717 Notes
718 -----
719 The implementation is based on that of Christoph Ortner in JuLIP.jl:
720 https://github.com/libAtoms/JuLIP.jl/blob/expcell/src/Constraints.jl#L244
722 In :class:`ExpCellFilter`, we express the deformation gradient
723 :math:`\mathbf{F} \in \mathbb{R}^{3 \times 3}` as
725 .. math::
726 \mathbf{F} = \exp(\mathbf{U}),
728 where :math:`\mathbf{U} = \log(\mathbf{F})` is used as the cell
729 optimization variable.
731 For a perturbation
732 :math:`\mathbf{V} \in \mathbb{R}^{3 \times 3}` of
733 :math:`\mathbf{U}`, the corresponding first-order change of
734 :math:`\mathbf{F}` is given by the Fréchet derivative of the
735 matrix exponential,
737 .. math::
738 L_{\exp}(\mathbf{U}, \mathbf{V})
739 \equiv
740 \left.
741 \frac{\mathrm{d}}{\mathrm{d}t}
742 \exp(\mathbf{U} + t\mathbf{V})
743 \right|_{t=0}.
745 Let :math:`\mathbf{S}` denote the virial tensor, defined here as
746 :math:`\mathbf{S} = -\Omega \boldsymbol\sigma`, where :math:`\Omega` is
747 the current cell volume and :math:`\boldsymbol\sigma` is the Cauchy
748 stress tensor. Since the energy gradient with respect to
749 :math:`\mathbf{F}` is :math:`-\mathbf{S}\mathbf{F}^{-\top}`,
750 the directional derivative of the energy with respect to
751 :math:`\mathbf{U}` is
753 .. math::
754 \left.
755 \frac{\mathrm{d}}{\mathrm{d}t}
756 E(\mathbf{U} + t\mathbf{V})
757 \right|_{t=0}
758 =
759 [-\mathbf{S}\exp(-\mathbf{U}^{\top})]
760 :
761 L_{\exp}(\mathbf{U},\mathbf{V}).
763 Here :math:`:` denotes the Frobenius inner product,
764 :math:`\mathbf{A}:\mathbf{B}
765 = \operatorname{tr}(\mathbf{A}^{\!\top}\mathbf{B})`.
767 Using the integral representation of the Fréchet derivative
768 and the cyclic property of the trace, this can be rewritten as
770 .. math::
771 [-\mathbf{S}\exp(-\mathbf{U}^{\top})]
772 :
773 L_{\exp}(\mathbf{U},\mathbf{V})
774 =
775 L_{\exp}\left(
776 \mathbf{U}^{\top},
777 -\mathbf{S}\exp(-\mathbf{U}^{\top})
778 \right)
779 :
780 \mathbf{V}.
782 Therefore,
784 .. math::
785 \left.
786 \frac{\mathrm{d}}{\mathrm{d}t}
787 E(\mathbf{U} + t\mathbf{V})
788 \right|_{t=0}
789 =
790 L_{\exp}\left(
791 \mathbf{U}^{\top},
792 -\mathbf{S}\exp(-\mathbf{U}^{\top})
793 \right)
794 :
795 \mathbf{V}.
797 If :math:`\mathbf{U}` is symmetric, an assumption that does not hold
798 in general, this reduces to
800 .. math::
801 \left.
802 \frac{\mathrm{d}}{\mathrm{d}t}
803 E(\mathbf{U} + t\mathbf{V})
804 \right|_{t=0}
805 =
806 L_{\exp}\left(
807 \mathbf{U},
808 -\mathbf{S}\exp(-\mathbf{U})
809 \right)
810 :
811 \mathbf{V}.
813 Thus, under this assumption, the generalized cell force with respect to
814 :math:`\mathbf{U}`, i.e. the negative energy gradient, is
816 .. math::
818 -\frac{\partial E}{\partial \mathbf{U}}
819 = -L_{\exp}\left(\mathbf{U}, -\mathbf{S}\exp(-\mathbf{U})\right).
821 """
822 Filter.__init__(self, atoms=atoms, indices=range(len(atoms)))
823 UnitCellFilter.__init__(
824 self,
825 atoms=atoms,
826 mask=mask,
827 cell_factor=cell_factor,
828 *args,
829 **kwargs,
830 )
831 if cell_factor is not None:
832 # cell_factor used in UnitCellFilter does not affect on gradients of
833 # ExpCellFilter.
834 warn('cell_factor is deprecated')
835 self.cell_factor = 1.0
837 # We defer the scipy import to avoid high immediate import overhead
838 from scipy.linalg import expm, logm
840 self.expm = expm
841 self.logm = logm
843 def get_forces(self, **kwargs):
844 forces = UnitCellFilter.get_forces(self, **kwargs)
846 # forces on atoms are same as UnitCellFilter, we just
847 # need to modify the stress contribution
848 stress = self.atoms.get_stress(**kwargs)
849 volume = self.atoms.get_volume()
850 virial = -volume * (
851 voigt_6_to_full_3x3_stress(stress)
852 + np.diag([self.scalar_pressure] * 3)
853 )
855 cur_deform_grad = self.deform_grad()
856 cur_deform_grad_log = self.logm(cur_deform_grad)
858 if self.hydrostatic_strain:
859 vtr = virial.trace()
860 virial = np.diag([vtr / 3.0, vtr / 3.0, vtr / 3.0])
862 # Zero out components corresponding to fixed lattice elements
863 if (self.mask != 1.0).any():
864 virial *= self.mask
866 deform_grad_log_force_naive = virial.copy()
867 Y = np.zeros((6, 6))
868 Y[0:3, 0:3] = cur_deform_grad_log
869 Y[3:6, 3:6] = cur_deform_grad_log
870 Y[0:3, 3:6] = -virial @ self.expm(-cur_deform_grad_log)
871 deform_grad_log_force = -self.expm(Y)[0:3, 3:6]
872 for i1, i2 in [(0, 1), (0, 2), (1, 2)]:
873 ff = 0.5 * (
874 deform_grad_log_force[i1, i2] + deform_grad_log_force[i2, i1]
875 )
876 deform_grad_log_force[i1, i2] = ff
877 deform_grad_log_force[i2, i1] = ff
879 # check for reasonable alignment between naive and
880 # exact search directions
881 all_are_equal = np.all(
882 np.isclose(deform_grad_log_force, deform_grad_log_force_naive)
883 )
884 if all_are_equal or (
885 np.sum(deform_grad_log_force * deform_grad_log_force_naive)
886 / np.sqrt(
887 np.sum(deform_grad_log_force**2)
888 * np.sum(deform_grad_log_force_naive**2)
889 )
890 > 0.8
891 ):
892 deform_grad_log_force = deform_grad_log_force_naive
894 # Cauchy stress used for convergence testing
895 convergence_crit_stress = -(virial / volume)
896 if self.constant_volume:
897 # apply constraint to force
898 dglf_trace = deform_grad_log_force.trace()
899 np.fill_diagonal(
900 deform_grad_log_force,
901 np.diag(deform_grad_log_force) - dglf_trace / 3.0,
902 )
903 # apply constraint to Cauchy stress used for convergence testing
904 ccs_trace = convergence_crit_stress.trace()
905 np.fill_diagonal(
906 convergence_crit_stress,
907 np.diag(convergence_crit_stress) - ccs_trace / 3.0,
908 )
910 # pack gradients into vector
911 natoms = len(self.atoms)
912 forces[natoms:] = deform_grad_log_force
913 self.stress = full_3x3_to_voigt_6_stress(convergence_crit_stress)
914 return forces