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