Coverage for ase/optimize/precon/fire.py: 85.09%

114 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import time 

2 

3import numpy as np 

4 

5from ase.filters import UnitCellFilter 

6from ase.optimize.optimize import Optimizer 

7from ase.utils import deprecate_positionals 

8 

9 

10class PreconFIRE(Optimizer): 

11 @deprecate_positionals(2) 

12 def __init__( 

13 self, 

14 atoms, 

15 restart=None, 

16 logfile='-', 

17 trajectory=None, 

18 dt=0.1, 

19 maxmove=0.2, 

20 dtmax=1.0, 

21 Nmin=5, 

22 finc=1.1, 

23 fdec=0.5, 

24 astart=0.1, 

25 fa=0.99, 

26 a=0.1, 

27 theta=0.1, 

28 precon=None, 

29 use_armijo=True, 

30 variable_cell=False, 

31 **kwargs, 

32 ): 

33 """ 

34 Preconditioned version of the FIRE optimizer 

35 

36 In time this implementation is expected to replace 

37 :class:`~ase.optimize.fire.FIRE`. 

38 

39 Parameters 

40 ---------- 

41 atoms: :class:`~ase.Atoms` 

42 The Atoms object to relax. 

43 

44 restart: string 

45 JSON file used to store hessian matrix. If set, file with 

46 such a name will be searched and hessian matrix stored will 

47 be used, if the file exists. 

48 

49 trajectory: string 

50 Trajectory file used to store optimisation path. 

51 

52 logfile: file object or str 

53 If *logfile* is a string, a file with that name will be opened. 

54 Use '-' for stdout. 

55 

56 variable_cell: bool 

57 If True, wrap atoms in UnitCellFilter to relax cell and positions. 

58 

59 kwargs : dict, optional 

60 Extra arguments passed to 

61 :class:`~ase.optimize.optimize.Optimizer`. 

62 

63 """ 

64 if variable_cell: 

65 atoms = UnitCellFilter(atoms) 

66 super().__init__(atoms, restart, logfile, trajectory, **kwargs) 

67 

68 self._actual_atoms = atoms 

69 

70 self.dt = dt 

71 self.Nsteps = 0 

72 self.maxmove = maxmove 

73 self.dtmax = dtmax 

74 self.Nmin = Nmin 

75 self.finc = finc 

76 self.fdec = fdec 

77 self.astart = astart 

78 self.fa = fa 

79 self.a = a 

80 self.theta = theta 

81 self.precon = precon 

82 self.use_armijo = use_armijo 

83 

84 def initialize(self): 

85 self.v = None 

86 self.skip_flag = False 

87 self.e1 = None 

88 

89 def read(self): 

90 self.v, self.dt = self.load() 

91 

92 def step(self, f=None): 

93 atoms = self._actual_atoms 

94 if f is None: 

95 f = atoms.get_forces() 

96 r = atoms.get_positions() 

97 

98 if self.precon is not None: 

99 # Can this be moved out of the step method? 

100 self.precon.make_precon(atoms) 

101 invP_f = self.precon.solve(f.reshape(-1)).reshape(len(atoms), -1) 

102 

103 if self.v is None: 

104 self.v = np.zeros((len(self._actual_atoms), 3)) 

105 else: 

106 if self.use_armijo: 

107 if self.precon is None: 

108 v_test = self.v + self.dt * f 

109 else: 

110 v_test = self.v + self.dt * invP_f 

111 

112 r_test = r + self.dt * v_test 

113 

114 self.skip_flag = False 

115 func_val = self.func(r_test) 

116 self.e1 = func_val 

117 if func_val > self.func(r) - self.theta * self.dt * np.vdot( 

118 v_test, f 

119 ): 

120 self.v[:] *= 0.0 

121 self.a = self.astart 

122 self.dt *= self.fdec 

123 self.Nsteps = 0 

124 self.skip_flag = True 

125 

126 if not self.skip_flag: 

127 v_f = np.vdot(self.v, f) 

128 if v_f > 0.0: 

129 if self.precon is None: 

130 self.v = (1.0 - self.a) * self.v + self.a * f / np.sqrt( 

131 np.vdot(f, f) 

132 ) * np.sqrt(np.vdot(self.v, self.v)) 

133 else: 

134 self.v = (1.0 - self.a) * self.v + self.a * ( 

135 np.sqrt( 

136 self.precon.dot( 

137 self.v.reshape(-1), self.v.reshape(-1) 

138 ) 

139 ) 

140 / np.sqrt(np.dot(f.reshape(-1), invP_f.reshape(-1))) 

141 * invP_f 

142 ) 

143 if self.Nsteps > self.Nmin: 

144 self.dt = min(self.dt * self.finc, self.dtmax) 

145 self.a *= self.fa 

146 self.Nsteps += 1 

147 else: 

148 self.v[:] *= 0.0 

149 self.a = self.astart 

150 self.dt *= self.fdec 

151 self.Nsteps = 0 

152 

153 if self.precon is None: 

154 self.v += self.dt * f 

155 else: 

156 self.v += self.dt * invP_f 

157 dr = self.dt * self.v 

158 normdr = np.sqrt(np.vdot(dr, dr)) 

159 if normdr > self.maxmove: 

160 dr = self.maxmove * dr / normdr 

161 atoms.set_positions(r + dr) 

162 self.dump((self.v, self.dt)) 

163 

164 def func(self, x): 

165 """Objective function for use of the optimizers""" 

166 self._actual_atoms.set_positions(x.reshape(-1, 3)) 

167 potl = self._actual_atoms.get_potential_energy() 

168 return potl 

169 

170 def run(self, fmax=0.05, steps=100000000, smax=None): 

171 if smax is None: 

172 smax = fmax 

173 self.smax = smax 

174 return super().run(fmax, steps) 

175 

176 def gradient_converged(self, gradient): 

177 """Did the optimization converge?""" 

178 # XXX ignoring gradient 

179 forces = self._actual_atoms.get_forces() 

180 if isinstance(self._actual_atoms, UnitCellFilter): 

181 natoms = len(self._actual_atoms.atoms) 

182 forces, stress = forces[:natoms], self._actual_atoms.stress 

183 fmax_sq = (forces**2).sum(axis=1).max() 

184 smax_sq = (stress**2).max() 

185 return fmax_sq < self.fmax**2 and smax_sq < self.smax**2 

186 else: 

187 fmax_sq = (forces**2).sum(axis=1).max() 

188 return fmax_sq < self.fmax**2 

189 

190 def log(self, gradient): 

191 forces = self._actual_atoms.get_forces() 

192 if isinstance(self._actual_atoms, UnitCellFilter): 

193 natoms = len(self._actual_atoms.atoms) 

194 forces, stress = forces[:natoms], self._actual_atoms.stress 

195 fmax = np.sqrt((forces**2).sum(axis=1).max()) 

196 smax = np.sqrt((stress**2).max()) 

197 else: 

198 fmax = np.sqrt((forces**2).sum(axis=1).max()) 

199 if self.e1 is not None: 

200 # reuse energy at end of line search to avoid extra call 

201 e = self.e1 

202 else: 

203 e = self._actual_atoms.get_potential_energy() 

204 T = time.localtime() 

205 if self.logfile is not None: 

206 name = self.__class__.__name__ 

207 if isinstance(self._actual_atoms, UnitCellFilter): 

208 self.logfile.write( 

209 '%s: %3d %02d:%02d:%02d %15.6f %12.4f %12.4f\n' 

210 % (name, self.nsteps, T[3], T[4], T[5], e, fmax, smax) 

211 ) 

212 

213 else: 

214 self.logfile.write( 

215 '%s: %3d %02d:%02d:%02d %15.6f %12.4f\n' 

216 % (name, self.nsteps, T[3], T[4], T[5], e, fmax) 

217 )