Coverage for ase/_4/optimize/cellutil.py: 95.24%
105 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 itertools import product
3import numpy as np
5from ase import Atoms
6from ase.stress import full_3x3_to_voigt_6_stress, voigt_6_to_full_3x3_stress
9class CellUtility:
10 def __init__(
11 self,
12 orig_cell: np.ndarray,
13 mask,
14 scalar_pressure: float = 0.0,
15 constant_volume: bool = False,
16 hydrostatic_strain: bool = False,
17 ):
18 from scipy.linalg import expm, expm_frechet, logm
20 self.orig_cell = orig_cell
21 self.expm = expm
22 self.expm_frechet = expm_frechet
23 self.logm = logm
25 if mask is None:
26 mask = np.ones(6, bool)
27 mask = np.asarray(mask)
28 if mask.shape == (6,):
29 mask = voigt_6_to_full_3x3_stress(mask)
30 elif mask.shape == (3, 3):
31 mask = mask
32 else:
33 raise ValueError('shape of mask should be (3,3) or (6,)')
35 self.mask3x3 = mask
37 # Somewhat uncertain how well these are tested in combinations
38 self.scalar_pressure = scalar_pressure
39 self.hydrostatic_strain = hydrostatic_strain
40 self.constant_volume = constant_volume
42 def deform_grad(self, cell) -> np.ndarray:
43 return np.linalg.solve(self.orig_cell, cell).T
45 def get_energy(self, atoms: Atoms, force_consistent: bool | None) -> float:
46 atoms_energy = atoms.get_potential_energy(
47 force_consistent=force_consistent
48 )
49 return atoms_energy + self.get_energy_correction(atoms.cell.volume)
51 def get_energy_correction(self, volume: float) -> float:
52 return self.scalar_pressure * volume
54 def get_positions_unitcellfilter(
55 self, positions: np.ndarray, cell, cell_factor: float
56 ) -> np.ndarray:
57 cur_deform_grad = self.deform_grad(cell)
58 natoms = len(positions)
59 pos = np.zeros((natoms + 3, 3))
60 # UnitCellFilter's positions are the self.atoms.positions but without
61 # the applied deformation gradient
62 pos[:natoms] = np.linalg.solve(cur_deform_grad, positions.T).T
63 # UnitCellFilter's cell DOFs are the deformation gradient times a
64 # scaling factor
65 pos[natoms:] = cell_factor * cur_deform_grad
66 return pos
68 def set_positions_unitcellfilter(
69 self, new: np.ndarray, atoms: Atoms, cell_factor: float, **setpos_kwargs
70 ):
71 # We do a few non-trivial call with Atoms so this is not decoupled
72 # from atoms (yet?).
73 natoms = len(atoms)
74 new_atom_positions = new[:natoms]
75 new_deform_grad = new[natoms:] / cell_factor
76 deform = (new_deform_grad - np.eye(3)).T * self.mask3x3
77 # Set the new cell from the original cell and the new
78 # deformation gradient. Both current and final structures should
79 # preserve symmetry, so if set_cell() calls FixSymmetry.adjust_cell(),
80 # it should be OK
81 newcell = self.orig_cell @ (np.eye(3) + deform)
83 atoms.set_cell(newcell, scale_atoms=True)
84 # Set the positions from the ones passed in (which are without the
85 # deformation gradient applied) and the new deformation gradient.
86 # This should also preserve symmetry, so if set_positions() calls
87 # FixSymmetry.adjust_positions(), it should be OK
88 atoms.set_positions(
89 new_atom_positions @ (np.eye(3) + deform), **setpos_kwargs
90 )
92 def get_positions_frechet(
93 self,
94 positions: np.ndarray,
95 cell,
96 cell_factor: float,
97 exp_cell_factor: float,
98 ) -> np.ndarray:
99 # XXX This is unitcellfilter's
100 # default behaviour
101 cell_factor = float(len(positions))
102 pos = self.get_positions_unitcellfilter(positions, cell, cell_factor)
103 natoms = len(positions)
104 pos[natoms:] = self.logm(pos[natoms:]) * exp_cell_factor
105 return pos
107 def set_positions_frechet(
108 self,
109 new: np.ndarray,
110 atoms: Atoms,
111 cell_factor: float,
112 exp_cell_factor: float,
113 **setpos_kwargs,
114 ) -> None:
115 natoms = len(atoms)
116 new2 = new.copy()
117 new2[natoms:] = self.expm(new[natoms:] / exp_cell_factor)
118 self.set_positions_unitcellfilter(
119 new2, atoms, cell_factor=cell_factor, **setpos_kwargs
120 )
122 def get_forces_unitcellfilter(
123 self,
124 atoms_forces: np.ndarray,
125 stress: np.ndarray,
126 cell,
127 cell_factor: float,
128 ) -> tuple[np.ndarray, np.ndarray]:
129 volume = cell.volume
130 virial = -volume * (
131 voigt_6_to_full_3x3_stress(stress)
132 + np.diag([self.scalar_pressure] * 3)
133 )
134 cur_deform_grad = self.deform_grad(cell)
135 atoms_forces = atoms_forces @ cur_deform_grad
136 virial = np.linalg.solve(cur_deform_grad, virial.T).T
138 if self.hydrostatic_strain:
139 vtr = virial.trace()
140 virial = np.diag([vtr / 3.0, vtr / 3.0, vtr / 3.0])
142 # Zero out components corresponding to fixed lattice elements
143 if (self.mask3x3 != 1.0).any():
144 virial *= self.mask3x3
146 if self.constant_volume:
147 vtr = virial.trace()
148 np.fill_diagonal(virial, np.diag(virial) - vtr / 3.0)
150 natoms = len(atoms_forces)
151 forces = np.zeros((natoms + 3, 3))
152 forces[:natoms] = atoms_forces
153 forces[natoms:] = virial / cell_factor
155 modified_stress = -full_3x3_to_voigt_6_stress(virial) / volume
156 return forces, modified_stress
158 def get_forces_frechet(
159 self,
160 atoms_forces: np.ndarray,
161 stress: np.ndarray,
162 cell,
163 exp_cell_factor: float,
164 ) -> tuple[np.ndarray, np.ndarray]:
165 volume = cell.volume
167 virial = -volume * (
168 voigt_6_to_full_3x3_stress(stress)
169 + np.diag([self.scalar_pressure] * 3)
170 )
172 cur_deform_grad = self.deform_grad(cell)
173 cur_deform_grad_log = self.logm(cur_deform_grad)
175 if self.hydrostatic_strain:
176 vtr = virial.trace()
177 virial = np.diag([vtr / 3.0, vtr / 3.0, vtr / 3.0])
179 # Zero out components corresponding to fixed lattice elements
180 if (self.mask3x3 != 1.0).any():
181 virial *= self.mask3x3
183 # Cell gradient for UnitCellFilter
184 ucf_cell_grad = virial @ np.linalg.inv(cur_deform_grad.T)
186 # Cell gradient for FrechetCellFilter
187 deform_grad_log_force = np.zeros((3, 3))
188 for mu, nu in product(range(3), repeat=2):
189 dir = np.zeros((3, 3))
190 dir[mu, nu] = 1.0
191 # Directional derivative of deformation to (mu, nu) strain direction
192 expm_der = self.expm_frechet(
193 cur_deform_grad_log, dir, compute_expm=False
194 )
195 deform_grad_log_force[mu, nu] = np.sum(expm_der * ucf_cell_grad)
197 # Cauchy stress used for convergence testing
198 convergence_crit_stress = -(virial / volume)
199 if self.constant_volume:
200 # apply constraint to force
201 dglf_trace = deform_grad_log_force.trace()
202 np.fill_diagonal(
203 deform_grad_log_force,
204 np.diag(deform_grad_log_force) - dglf_trace / 3.0,
205 )
206 # apply constraint to Cauchy stress used for convergence testing
207 ccs_trace = convergence_crit_stress.trace()
208 np.fill_diagonal(
209 convergence_crit_stress,
210 np.diag(convergence_crit_stress) - ccs_trace / 3.0,
211 )
213 atoms_forces = atoms_forces @ cur_deform_grad
215 # pack gradients into vector
216 natoms = len(atoms_forces)
217 forces = np.zeros((natoms + 3, 3))
218 forces[:natoms] = atoms_forces
219 forces[natoms:] = deform_grad_log_force / exp_cell_factor
220 return forces, convergence_crit_stress