Coverage for ase / optimize / cellawarebfgs.py: 100.00%
67 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-04 10:20 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-04 10:20 +0000
1# fmt: off
3import time
4from typing import IO, Optional, Union
6import numpy as np
8from ase import Atoms
9from ase.geometry import cell_to_cellpar
10from ase.optimize import BFGS
11from ase.optimize.optimize import Dynamics
12from ase.units import GPa
15def calculate_isotropic_elasticity_tensor(bulk_modulus, poisson_ratio,
16 suppress_rotation=0):
17 """
18 Parameters:
19 bulk_modulus Bulk Modulus of the isotropic system used to set up the
20 Hessian (in ASE units (eV/Å^3)).
22 poisson_ratio Poisson ratio of the isotropic system used to set up the
23 initial Hessian (unitless, between -1 and 0.5).
25 suppress_rotation The rank-2 matrix C_ijkl.reshape((9,9)) has by
26 default 6 non-zero eigenvalues, because energy is
27 invariant to orthonormal rotations of the cell
28 vector. This serves as a bad initial Hessian due to 3
29 zero eigenvalues. Suppress rotation sets a value for
30 those zero eigenvalues.
32 Returns C_ijkl
33 """
35 # https://scienceworld.wolfram.com/physics/LameConstants.html
36 _lambda = 3 * bulk_modulus * poisson_ratio / (1 + 1 * poisson_ratio)
37 _mu = _lambda * (1 - 2 * poisson_ratio) / (2 * poisson_ratio)
39 # https://en.wikipedia.org/wiki/Elasticity_tensor
40 g_ij = np.eye(3)
42 # Construct 4th rank Elasticity tensor for isotropic systems
43 C_ijkl = _lambda * np.einsum('ij,kl->ijkl', g_ij, g_ij)
44 C_ijkl += _mu * (np.einsum('ik,jl->ijkl', g_ij, g_ij) +
45 np.einsum('il,kj->ijkl', g_ij, g_ij))
47 # Supplement the tensor with suppression of pure rotations that are right
48 # now 0 eigenvalues.
49 # Loop over all basis vectors of skew symmetric real matrix
50 for i, j in ((0, 1), (0, 2), (1, 2)):
51 Q = np.zeros((3, 3))
52 Q[i, j], Q[j, i] = 1, -1
53 C_ijkl += (np.einsum('ij,kl->ijkl', Q, Q)
54 * suppress_rotation / 2)
56 return C_ijkl
59class CellAwareBFGS(BFGS):
60 def __init__(
61 self,
62 atoms: Atoms,
63 restart: Optional[str] = None,
64 logfile: Union[IO, str] = '-',
65 trajectory: Optional[str] = None,
66 append_trajectory: bool = False,
67 maxstep: Optional[float] = None,
68 bulk_modulus: Optional[float] = 145 * GPa,
69 poisson_ratio: Optional[float] = 0.3,
70 alpha: Optional[float] = None,
71 long_output: Optional[bool] = False,
72 **kwargs,
73 ):
74 self.bulk_modulus = bulk_modulus
75 self.poisson_ratio = poisson_ratio
76 self.long_output = long_output
77 super().__init__(
78 atoms=atoms, restart=restart, logfile=logfile,
79 trajectory=trajectory, maxstep=maxstep,
80 alpha=alpha, append_trajectory=append_trajectory,
81 **kwargs)
82 assert not isinstance(atoms, Atoms)
83 if hasattr(atoms, 'exp_cell_factor'):
84 assert atoms.exp_cell_factor == 1.0
86 def initialize(self):
87 super().initialize()
88 C_ijkl = calculate_isotropic_elasticity_tensor(
89 self.bulk_modulus,
90 self.poisson_ratio,
91 suppress_rotation=self.alpha)
92 cell_H = self.H0[-9:, -9:]
93 ind = np.where(self.atoms.mask.ravel() != 0)[0]
94 cell_H[np.ix_(ind, ind)] = C_ijkl.reshape((9, 9))[
95 np.ix_(ind, ind)] * self.atoms.atoms.cell.volume
97 def converged(self, gradient):
98 # XXX currently ignoring gradient
99 forces = self.atoms.atoms.get_forces()
100 stress = self.atoms.atoms.get_stress(voigt=False) * self.atoms.mask
101 return np.max(np.sum(forces**2, axis=1))**0.5 < self.fmax and \
102 np.max(np.abs(stress)) < self.smax
104 def run(self, fmax=0.05, smax=0.005, steps=None):
105 """ call Dynamics.run and keep track of fmax"""
106 self.fmax = fmax
107 self.smax = smax
108 if steps is not None:
109 return Dynamics.run(self, steps=steps)
110 return Dynamics.run(self)
112 def log(self, gradient):
113 # XXX ignoring gradient
114 forces = self.atoms.atoms.get_forces()
115 fmax = (forces ** 2).sum(axis=1).max() ** 0.5
116 e = self.optimizable.get_value()
117 T = time.localtime()
118 smax = abs(self.atoms.atoms.get_stress(voigt=False) *
119 self.atoms.mask).max()
120 volume = self.atoms.atoms.cell.volume
121 if self.logfile is not None:
122 name = self.__class__.__name__
123 if self.nsteps == 0:
124 args = (" " * len(name),
125 "Step", "Time", "Energy", "fmax", "smax", "volume")
126 msg = "\n%s %4s %8s %15s %15s %15s %15s" % args
127 if self.long_output:
128 msg += ("%8s %8s %8s %8s %8s %8s" %
129 ('A', 'B', 'C', 'α', 'β', 'γ'))
130 msg += '\n'
131 self.logfile.write(msg)
133 ast = ''
134 args = (name, self.nsteps, T[3], T[4], T[5], e, ast, fmax, smax,
135 volume)
136 msg = ("%s: %3d %02d:%02d:%02d %15.6f%1s %15.6f %15.6f %15.6f" %
137 args)
138 if self.long_output:
139 msg += ("%8.3f %8.3f %8.3f %8.3f %8.3f %8.3f" %
140 tuple(cell_to_cellpar(self.atoms.atoms.cell)))
141 msg += '\n'
142 self.logfile.write(msg)