Coverage for /builds/ase/ase/ase/optimize/cellawarebfgs.py: 100.00%

68 statements  

« prev     ^ index     » next       coverage.py v7.5.3, created at 2025-08-02 00:12 +0000

1# fmt: off 

2 

3import time 

4from typing import IO, Optional, Union 

5 

6import numpy as np 

7 

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 

13 

14 

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

21 

22 poisson_ratio Poisson ratio of the isotropic system used to set up the 

23 initial Hessian (unitless, between -1 and 0.5). 

24 

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. 

31 

32 Returns C_ijkl 

33 """ 

34 

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) 

38 

39 # https://en.wikipedia.org/wiki/Elasticity_tensor 

40 g_ij = np.eye(3) 

41 

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

46 

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) 

55 

56 return C_ijkl 

57 

58 

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 BFGS.__init__(self, atoms=atoms, restart=restart, logfile=logfile, 

78 trajectory=trajectory, maxstep=maxstep, 

79 alpha=alpha, append_trajectory=append_trajectory, 

80 **kwargs) 

81 assert not isinstance(atoms, Atoms) 

82 if hasattr(atoms, 'exp_cell_factor'): 

83 assert atoms.exp_cell_factor == 1.0 

84 

85 def initialize(self): 

86 BFGS.initialize(self) 

87 C_ijkl = calculate_isotropic_elasticity_tensor( 

88 self.bulk_modulus, 

89 self.poisson_ratio, 

90 suppress_rotation=self.alpha) 

91 cell_H = self.H0[-9:, -9:] 

92 ind = np.where(self.atoms.mask.ravel() != 0)[0] 

93 cell_H[np.ix_(ind, ind)] = C_ijkl.reshape((9, 9))[ 

94 np.ix_(ind, ind)] * self.atoms.atoms.cell.volume 

95 

96 def converged(self, gradient): 

97 # XXX currently ignoring gradient 

98 forces = self.atoms.atoms.get_forces() 

99 stress = self.atoms.atoms.get_stress(voigt=False) * self.atoms.mask 

100 return np.max(np.sum(forces**2, axis=1))**0.5 < self.fmax and \ 

101 np.max(np.abs(stress)) < self.smax 

102 

103 def run(self, fmax=0.05, smax=0.005, steps=None): 

104 """ call Dynamics.run and keep track of fmax""" 

105 self.fmax = fmax 

106 self.smax = smax 

107 if steps is not None: 

108 return Dynamics.run(self, steps=steps) 

109 return Dynamics.run(self) 

110 

111 def log(self, gradient): 

112 # XXX ignoring gradient 

113 forces = self.atoms.atoms.get_forces() 

114 fmax = (forces ** 2).sum(axis=1).max() ** 0.5 

115 e = self.optimizable.get_value() 

116 T = time.localtime() 

117 smax = abs(self.atoms.atoms.get_stress(voigt=False) * 

118 self.atoms.mask).max() 

119 volume = self.atoms.atoms.cell.volume 

120 if self.logfile is not None: 

121 name = self.__class__.__name__ 

122 if self.nsteps == 0: 

123 args = (" " * len(name), 

124 "Step", "Time", "Energy", "fmax", "smax", "volume") 

125 msg = "\n%s %4s %8s %15s %15s %15s %15s" % args 

126 if self.long_output: 

127 msg += ("%8s %8s %8s %8s %8s %8s" % 

128 ('A', 'B', 'C', 'α', 'β', 'γ')) 

129 msg += '\n' 

130 self.logfile.write(msg) 

131 

132 ast = '' 

133 args = (name, self.nsteps, T[3], T[4], T[5], e, ast, fmax, smax, 

134 volume) 

135 msg = ("%s: %3d %02d:%02d:%02d %15.6f%1s %15.6f %15.6f %15.6f" % 

136 args) 

137 if self.long_output: 

138 msg += ("%8.3f %8.3f %8.3f %8.3f %8.3f %8.3f" % 

139 tuple(cell_to_cellpar(self.atoms.atoms.cell))) 

140 msg += '\n' 

141 self.logfile.write(msg) 

142 

143 self.logfile.flush()