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

1"""Filters""" 

2 

3from __future__ import annotations 

4 

5from functools import cached_property 

6from typing import TYPE_CHECKING, Never 

7from warnings import warn 

8 

9import numpy as np 

10import numpy.typing as npt 

11 

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 

16 

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 

22 

23 

24__all__ = [ 

25 'Filter', 

26 'StrainFilter', 

27 'UnitCellFilter', 

28 'FrechetCellFilter', 

29 'ExpCellFilter', 

30] 

31 

32 

33class OptimizableFilter(Optimizable): 

34 def __init__(self, filterobj: Filter) -> None: 

35 self.filterobj = filterobj 

36 

37 def get_x(self) -> npt.NDArray[np.floating]: 

38 return self.filterobj.get_positions().ravel() 

39 

40 def set_x(self, x: npt.NDArray[np.floating]) -> None: 

41 self.filterobj.set_positions(x.reshape(-1, 3)) 

42 

43 def get_gradient(self) -> np.ndarray: 

44 return -self.filterobj.get_forces().ravel() 

45 

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 

57 

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 ) 

63 

64 def ndofs(self) -> int: 

65 return 3 * len(self.filterobj) 

66 

67 def iterimages(self) -> Atoms: 

68 return self.filterobj.iterimages() 

69 

70 

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. 

79 

80 This filter "hides" some atoms in the ASE :class:`~ase.Atoms` object 

81 and thus fixes their positions during structure optimization. 

82 

83 This can be used as an alternative to the 

84 :class:`~ase.constraints.FixAtoms` constraint. 

85 

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. 

95 

96 Notes 

97 ----- 

98 You must supply either ``indices`` or ``mask``. 

99 

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. 

103 

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]]) 

121 

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. 

125 

126 """ 

127 

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 

132 

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".') 

137 

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) 

144 

145 def iterimages(self) -> Atoms: 

146 # Present the real atoms object to Trajectory and friends 

147 return self.atoms.iterimages() 

148 

149 def get_cell(self) -> Cell: 

150 """Returns the computational cell. 

151 

152 The computational cell is the same as for the original system. 

153 """ 

154 return self.atoms.get_cell() 

155 

156 def get_pbc(self) -> npt.NDArray[np.bool_]: 

157 """Returns the periodic boundary conditions. 

158 

159 The boundary conditions are the same as for the original system. 

160 """ 

161 return self.atoms.get_pbc() 

162 

163 def get_positions(self): 

164 "Return the positions of the visible atoms." 

165 return self.atoms.get_positions()[self.index] 

166 

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) 

172 

173 positions = property( 

174 get_positions, set_positions, doc='Positions of the atoms' 

175 ) 

176 

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] 

180 

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) 

186 

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] 

190 

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) 

199 

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] 

203 

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) 

209 

210 def get_forces(self, *args, **kwargs): 

211 return self.atoms.get_forces(*args, **kwargs)[self.index] 

212 

213 def get_stress(self, *args, **kwargs) -> npt.NDArray[np.floating]: 

214 return self.atoms.get_stress(*args, **kwargs) 

215 

216 def get_stresses(self, *args, **kwargs) -> npt.NDArray[np.floating]: 

217 return self.atoms.get_stresses(*args, **kwargs)[self.index] 

218 

219 def get_masses(self) -> npt.NDArray[np.floating]: 

220 return self.atoms.get_masses()[self.index] 

221 

222 def get_potential_energy(self, **kwargs): 

223 """Calculate potential energy. 

224 

225 Returns the potential energy of the full system. 

226 """ 

227 return self.atoms.get_potential_energy(**kwargs) 

228 

229 def get_chemical_symbols(self) -> list[str]: 

230 return self.atoms.get_chemical_symbols() 

231 

232 def get_initial_magnetic_moments(self) -> npt.NDArray[np.floating]: 

233 return self.atoms.get_initial_magnetic_moments() 

234 

235 def get_calculator(self) -> BaseCalculator: 

236 """Returns the calculator. 

237 

238 WARNING: The calculator is unaware of this filter, and sees a 

239 different number of atoms. 

240 """ 

241 return self.atoms.calc 

242 

243 @property 

244 def calc(self) -> BaseCalculator: 

245 return self.atoms.calc 

246 

247 def get_celldisp(self) -> npt.NDArray[np.floating]: 

248 return self.atoms.get_celldisp() 

249 

250 def has(self, name: str) -> bool: 

251 "Check for existence of array." 

252 return self.atoms.has(name) 

253 

254 def __len__(self) -> int: 

255 "Return the number of movable atoms." 

256 return self.n 

257 

258 def __getitem__(self, i: int) -> Atom: 

259 "Return an atom." 

260 return self.atoms[self.index[i]] 

261 

262 def __ase_optimizable__(self) -> OptimizableFilter: 

263 return OptimizableFilter(self) 

264 

265 

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. 

274 

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. 

278 

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. 

282 

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``. 

286 

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. 

298 

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. 

304 

305 """ 

306 

307 self.strain = np.zeros(6) 

308 self.include_ideal_gas = include_ideal_gas 

309 

310 if mask is None: 

311 mask = np.ones(6) 

312 else: 

313 mask = np.array(mask) 

314 

315 Filter.__init__(self, atoms=atoms, mask=mask) 

316 self.mask = mask 

317 self.origcell = atoms.get_cell() 

318 

319 def get_positions(self): 

320 return self.strain.reshape((2, 3)).copy() 

321 

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 ) 

331 

332 self.atoms.set_cell(np.dot(self.origcell, eps), scale_atoms=True) 

333 self.strain[:] = new 

334 

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)) 

338 

339 def has(self, x: str) -> bool: 

340 return self.atoms.has(x) 

341 

342 def __len__(self) -> int: 

343 return 2 

344 

345 

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. 

358 

359 This class is used together with an ASE optimizer in order to minimize 

360 both the atomic forces and the cell stresses simultaneously. 

361 

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 

366 

367 .. math:: 

368 \mathbf{q}_i = \mathbf{F}^{-1}\mathbf{r}_i. 

369 

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]_. 

377 

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` 

382 

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. 

390 

391 - :obj:`True`: relax to zero 

392 - :obj:`False`: fixed, ignore this component 

393 

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. 

401 

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)`. 

405 

406 .. versionadded:: 3.17.0 

407 

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`). 

415 

416 .. versionadded:: 3.17.0 

417 

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. 

423 

424 .. versionadded:: 3.17.0 

425 

426 Notes 

427 ----- 

428 :class:`FrechetCellFilter` will probably perform better. 

429 

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. 

435 

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 """ 

443 

444 from ase._4.optimize.cellutil import CellUtility 

445 

446 Filter.__init__(self, atoms=atoms, indices=range(len(atoms))) 

447 self.atoms = atoms 

448 

449 if orig_cell is None: 

450 orig_cell = atoms.get_cell() 

451 else: 

452 orig_cell = orig_cell 

453 

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 ) 

461 

462 self.stress = None 

463 

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 

469 

470 @property 

471 def hydrostatic_strain(self) -> bool: 

472 return self._utility.hydrostatic_strain 

473 

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 

479 

480 @property 

481 def constant_volume(self) -> bool: 

482 return self._utility.constant_volume 

483 

484 @constant_volume.setter 

485 def constant_volume(self, value: bool) -> None: 

486 self._utility.constant_volume = value 

487 

488 @property 

489 def scalar_pressure(self) -> float: 

490 return self._utility.scalar_pressure 

491 

492 @scalar_pressure.setter 

493 def scalar_pressure(self, value: float) -> None: 

494 self._utility.scalar_pressure = value 

495 

496 @property 

497 def mask(self) -> np.ndarray: 

498 return self._utility.mask3x3 

499 

500 @property 

501 def orig_cell(self) -> npt.NDArray[np.floating]: 

502 return self._utility.orig_cell 

503 

504 @orig_cell.setter 

505 def orig_cell(self, value: npt.NDArray[np.floating]) -> None: 

506 self._utility.orig_cell[:] = value 

507 

508 def deform_grad(self) -> npt.NDArray[np.floating]: 

509 return self._utility.deform_grad(self.atoms.cell) 

510 

511 def get_positions(self): 

512 """ 

513 this returns an array with shape (natoms + 3,3). 

514 

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 ) 

522 

523 def set_positions(self, new, **kwargs): 

524 """ 

525 new is an array with shape (natoms+3,3). 

526 

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. 

529 

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 ) 

537 

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) 

543 

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. 

548 

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) 

555 

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 

564 

565 def get_stress(self) -> Never: 

566 raise PropertyNotImplementedError 

567 

568 def has(self, x: str) -> bool: 

569 return self.atoms.has(x) 

570 

571 def __len__(self) -> int: 

572 return len(self.atoms) + 3 

573 

574 

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. 

585 

586 This class is used together with an ASE optimizer in order to minimize 

587 both the atomic forces and the cell stresses simultaneously. 

588 

589 .. versionadded:: 3.23.0 

590 

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}`. 

596 

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`. 

607 

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`. 

617 

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 """ 

622 

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 ) 

631 

632 # We defer the scipy import to avoid high immediate import overhead 

633 from scipy.linalg import expm, expm_frechet, logm 

634 

635 self.expm = expm 

636 self.logm = logm 

637 self.expm_frechet = expm_frechet 

638 

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 

643 

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 ) 

651 

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 ) 

660 

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) 

666 

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 ) 

673 

674 self.stress = full_3x3_to_voigt_6_stress(convergence_crit_stress) 

675 return forces 

676 

677 

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. 

694 

695 .. versionadded:: 3.17.0 

696 

697 .. deprecated:: 3.23.0 

698 Use :class:`~ase.filters.FrechetCellFilter` for better convergence 

699 w.r.t. cell variables. 

700 

701 This class is used together with an ASE optimizer in order to minimize 

702 both the atomic forces and the cell stresses simultaneously. 

703 

704 Degrees of freedom are the positions in the original undeformed cell, 

705 plus the log of the deformation tensor (extra 3 "atoms"). 

706 

707 Parameters 

708 ---------- 

709 cell_factor : float(DEPRECATED) 

710 Retained for backwards compatibility, but no longer used. 

711 

712 .. deprecated:: 3.23.0 

713 

714 *args, **kwargs 

715 Additional arguments passed to :class:`~ase.filters.UnitCellFilter`. 

716 

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 

721 

722 In :class:`ExpCellFilter`, we express the deformation gradient 

723 :math:`\mathbf{F} \in \mathbb{R}^{3 \times 3}` as 

724 

725 .. math:: 

726 \mathbf{F} = \exp(\mathbf{U}), 

727 

728 where :math:`\mathbf{U} = \log(\mathbf{F})` is used as the cell 

729 optimization variable. 

730 

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, 

736 

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}. 

744 

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 

752 

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}). 

762 

763 Here :math:`:` denotes the Frobenius inner product, 

764 :math:`\mathbf{A}:\mathbf{B} 

765 = \operatorname{tr}(\mathbf{A}^{\!\top}\mathbf{B})`. 

766 

767 Using the integral representation of the Fréchet derivative 

768 and the cyclic property of the trace, this can be rewritten as 

769 

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}. 

781 

782 Therefore, 

783 

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}. 

796 

797 If :math:`\mathbf{U}` is symmetric, an assumption that does not hold 

798 in general, this reduces to 

799 

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}. 

812 

813 Thus, under this assumption, the generalized cell force with respect to 

814 :math:`\mathbf{U}`, i.e. the negative energy gradient, is 

815 

816 .. math:: 

817 

818 -\frac{\partial E}{\partial \mathbf{U}} 

819 = -L_{\exp}\left(\mathbf{U}, -\mathbf{S}\exp(-\mathbf{U})\right). 

820 

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 

836 

837 # We defer the scipy import to avoid high immediate import overhead 

838 from scipy.linalg import expm, logm 

839 

840 self.expm = expm 

841 self.logm = logm 

842 

843 def get_forces(self, **kwargs): 

844 forces = UnitCellFilter.get_forces(self, **kwargs) 

845 

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 ) 

854 

855 cur_deform_grad = self.deform_grad() 

856 cur_deform_grad_log = self.logm(cur_deform_grad) 

857 

858 if self.hydrostatic_strain: 

859 vtr = virial.trace() 

860 virial = np.diag([vtr / 3.0, vtr / 3.0, vtr / 3.0]) 

861 

862 # Zero out components corresponding to fixed lattice elements 

863 if (self.mask != 1.0).any(): 

864 virial *= self.mask 

865 

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 

878 

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 

893 

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 ) 

909 

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