Coverage for ase/optimize/cellawarebfgs.py: 100.00%
69 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
1import time
2from typing import IO
4import numpy as np
6from ase import Atoms
7from ase.geometry import cell_to_cellpar
8from ase.optimize import BFGS
9from ase.optimize.optimize import Dynamics
10from ase.units import GPa
11from ase.utils import deprecate_positionals
14def calculate_isotropic_elasticity_tensor(
15 bulk_modulus, poisson_ratio, suppress_rotation=0
16):
17 """
18 Parameters
19 ----------
20 bulk_modulus Bulk Modulus of the isotropic system used to set up the
21 Hessian (in ASE units (eV/Å^3)).
23 poisson_ratio Poisson ratio of the isotropic system used to set up the
24 initial Hessian (unitless, between -1 and 0.5).
26 suppress_rotation The rank-2 matrix C_ijkl.reshape((9,9)) has by
27 default 6 non-zero eigenvalues, because energy is
28 invariant to orthonormal rotations of the cell
29 vector. This serves as a bad initial Hessian due to 3
30 zero eigenvalues. Suppress rotation sets a value for
31 those zero eigenvalues.
33 Returns C_ijkl
34 """
36 # https://scienceworld.wolfram.com/physics/LameConstants.html
37 _lambda = 3 * bulk_modulus * poisson_ratio / (1 + poisson_ratio)
38 _mu = _lambda * (1 - 2 * poisson_ratio) / (2 * poisson_ratio)
40 # https://en.wikipedia.org/wiki/Elasticity_tensor
41 g_ij = np.eye(3)
43 # Construct 4th rank Elasticity tensor for isotropic systems
44 C_ijkl = _lambda * np.einsum('ij,kl->ijkl', g_ij, g_ij)
45 C_ijkl += _mu * (
46 np.einsum('ik,jl->ijkl', g_ij, g_ij)
47 + np.einsum('il,kj->ijkl', g_ij, g_ij)
48 )
50 # Supplement the tensor with suppression of pure rotations that are right
51 # now 0 eigenvalues.
52 # Loop over all basis vectors of skew symmetric real matrix
53 for i, j in ((0, 1), (0, 2), (1, 2)):
54 Q = np.zeros((3, 3))
55 Q[i, j], Q[j, i] = 1, -1
56 C_ijkl += np.einsum('ij,kl->ijkl', Q, Q) * suppress_rotation / 2
58 return C_ijkl
61class CellAwareBFGS(BFGS):
62 @deprecate_positionals(2)
63 def __init__(
64 self,
65 atoms: Atoms,
66 restart: str | None = None,
67 logfile: IO | str = '-',
68 trajectory: str | None = None,
69 append_trajectory: bool = False,
70 maxstep: float | None = None,
71 bulk_modulus: float | None = 145 * GPa,
72 poisson_ratio: float | None = 0.3,
73 alpha: float | None = None,
74 long_output: bool | None = False,
75 **kwargs,
76 ):
77 self.bulk_modulus = bulk_modulus
78 self.poisson_ratio = poisson_ratio
79 self.long_output = long_output
80 super().__init__(
81 atoms=atoms,
82 restart=restart,
83 logfile=logfile,
84 trajectory=trajectory,
85 maxstep=maxstep,
86 alpha=alpha,
87 append_trajectory=append_trajectory,
88 **kwargs,
89 )
90 assert not isinstance(atoms, Atoms)
91 if hasattr(atoms, 'exp_cell_factor'):
92 assert atoms.exp_cell_factor == 1.0
94 """
95 Examples
96 --------
97 >>> from ase.build import bulk
98 >>> from ase.calculators.emt import EMT
99 >>> from ase.filters import FrechetCellFilter
100 >>> from ase.optimize.cellawarebfgs import CellAwareBFGS
101 >>> from ase.units import GPa
102 >>> atoms = bulk('Au')
103 >>> atoms.calc = EMT()
104 >>> dyn = CellAwareBFGS(
105 ... FrechetCellFilter(atoms, exp_cell_factor=1.0),
106 ... # suppress-ratio for elastic tensor calculation
107 ... alpha=70,
108 ... bulk_modulus = 100 * GPa,
109 ... poisson_ratio = 0.37,
110 ... long_output=False,
111 ... )
112 ... dyn.run(fmax=0.005) # doctest:+SKIP
113 """
115 def initialize(self):
116 super().initialize()
117 C_ijkl = calculate_isotropic_elasticity_tensor(
118 self.bulk_modulus, self.poisson_ratio, suppress_rotation=self.alpha
119 )
120 cell_H = self.H0[-9:, -9:]
121 ind = np.where(self.atoms.mask.ravel() != 0)[0]
122 cell_H[np.ix_(ind, ind)] = (
123 C_ijkl.reshape((9, 9))[np.ix_(ind, ind)]
124 * self.atoms.atoms.cell.volume
125 )
127 def gradient_converged(self, gradient):
128 # XXX currently ignoring gradient
129 forces = self.atoms.atoms.get_forces()
130 stress = self.atoms.atoms.get_stress(voigt=False) * self.atoms.mask
131 return (
132 np.max(np.sum(forces**2, axis=1)) ** 0.5 < self.fmax
133 and np.max(np.abs(stress)) < self.smax
134 )
136 def run(self, fmax=0.05, smax=0.005, steps=None):
137 """call Dynamics.run and keep track of fmax"""
138 self.fmax = fmax
139 self.smax = smax
140 if steps is not None:
141 return Dynamics.run(self, steps=steps)
142 return Dynamics.run(self)
144 def log(self, gradient):
145 # XXX ignoring gradient
146 forces = self.atoms.atoms.get_forces()
147 fmax = (forces**2).sum(axis=1).max() ** 0.5
148 e = self.optimizable.get_value()
149 T = time.localtime()
150 smax = abs(
151 self.atoms.atoms.get_stress(voigt=False) * self.atoms.mask
152 ).max()
153 volume = self.atoms.atoms.cell.volume
154 if self.logfile is not None:
155 name = self.__class__.__name__
156 if self.nsteps == 0:
157 args = (
158 ' ' * len(name),
159 'Step',
160 'Time',
161 'Energy',
162 'fmax',
163 'smax',
164 'volume',
165 )
166 msg = '\n%s %4s %8s %15s %15s %15s %15s' % args
167 if self.long_output:
168 msg += '%8s %8s %8s %8s %8s %8s' % (
169 'A',
170 'B',
171 'C',
172 'α',
173 'β',
174 'γ',
175 )
176 msg += '\n'
177 self.logfile.write(msg)
179 ast = ''
180 args = (
181 name,
182 self.nsteps,
183 T[3],
184 T[4],
185 T[5],
186 e,
187 ast,
188 fmax,
189 smax,
190 volume,
191 )
192 msg = (
193 '%s: %3d %02d:%02d:%02d %15.6f%1s %15.6f %15.6f %15.6f' % args
194 )
195 if self.long_output:
196 msg += '%8.3f %8.3f %8.3f %8.3f %8.3f %8.3f' % tuple(
197 cell_to_cellpar(self.atoms.atoms.cell)
198 )
199 msg += '\n'
200 self.logfile.write(msg)