Coverage for ase/optimize/bfgslinesearch.py: 84.21%

133 statements  

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

1# ******NOTICE*************** 

2# optimize.py module by Travis E. Oliphant 

3# 

4# You may copy and use this module as you see fit with no 

5# guarantee implied provided you keep this notice in all copies. 

6# *****END NOTICE************ 

7 

8import time 

9from typing import IO 

10 

11import numpy as np 

12from numpy import absolute, eye, isinf 

13 

14from ase import Atoms 

15from ase.optimize.optimize import Optimizer 

16from ase.utils import deprecate_positionals 

17from ase.utils.linesearch import LineSearch 

18 

19# These have been copied from Numeric's MLab.py 

20# I don't think they made the transition to scipy_core 

21 

22# Modified from scipy_optimize 

23abs = absolute 

24pymin = min 

25pymax = max 

26__version__ = '0.1' 

27 

28 

29class BFGSLineSearch(Optimizer): 

30 @deprecate_positionals(2) 

31 def __init__( 

32 self, 

33 atoms: Atoms, 

34 restart: str | None = None, 

35 logfile: IO | str = '-', 

36 maxstep: float | None = None, 

37 trajectory: str | None = None, 

38 c1: float = 0.23, 

39 c2: float = 0.46, 

40 alpha: float = 10.0, 

41 stpmax: float = 50.0, 

42 **kwargs, 

43 ): 

44 """Optimize atomic positions in the BFGSLineSearch algorithm, which 

45 uses both forces and potential energy information. 

46 

47 Parameters 

48 ---------- 

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

50 The Atoms object to relax. 

51 

52 restart: str 

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

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

55 be used, if the file exists. 

56 

57 trajectory: str 

58 Trajectory file used to store optimisation path. 

59 

60 maxstep: float 

61 Used to set the maximum distance an atom can move per 

62 iteration (default value is 0.2 Angstroms). 

63 

64 logfile: file object or str 

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

66 Use '-' for stdout. 

67 

68 kwargs : dict, optional 

69 Extra arguments passed to 

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

71 

72 Examples 

73 -------- 

74 

75 >>> from ase import Atoms 

76 >>> from ase.optimize.bfgslinesearch import BFGSLineSearch 

77 >>> from ase.calculators.emt import EMT 

78 ... 

79 >>> system = Atoms( 

80 ... 'N2', 

81 ... positions = [(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)], 

82 ... calculator=EMT() 

83 ... ) 

84 >>> dyn = BFGSLineSearch(system) 

85 >>> dyn.run(fmax=0.05) # doctest:+ELLIPSIS, +NORMALIZE_WHITESPACE 

86 Step[ FC] Time Energy fmax 

87 BFGSLineSearch: 0[ 0] ... 0.440344 3.2518 

88 BFGSLineSearch: 1[ 2] ... 0.265703 0.4702 

89 BFGSLineSearch: 2[ 3] ... 0.262932 0.1103 

90 BFGSLineSearch: 3[ 4] ... 0.262777 0.0027 

91 ... 

92 """ 

93 if maxstep is None: 

94 self.maxstep = self.defaults['maxstep'] 

95 else: 

96 self.maxstep = maxstep 

97 self.stpmax = stpmax 

98 self.alpha = alpha 

99 self.H = None 

100 self.c1 = c1 

101 self.c2 = c2 

102 self.force_calls = 0 

103 self.function_calls = 0 

104 self.r0 = None 

105 self.g0 = None 

106 self.e0 = None 

107 self.load_restart = False 

108 self.task = 'START' 

109 self.rep_count = 0 

110 self.p = None 

111 self.alpha_k = None 

112 self.no_update = False 

113 self.replay = False 

114 

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

116 

117 def read(self): 

118 self.r0, self.g0, self.e0, self.task, self.H = self.load() 

119 self.load_restart = True 

120 

121 def reset(self): 

122 self.H = None 

123 self.r0 = None 

124 self.g0 = None 

125 self.e0 = None 

126 self.rep_count = 0 

127 

128 def step(self, gradient=None): 

129 optimizable = self.optimizable 

130 gradient = self._get_gradient(gradient) 

131 r = optimizable.get_x() 

132 g = gradient / self.alpha 

133 p0 = self.p 

134 self.update(r, g, self.r0, self.g0, p0) 

135 # o,v = np.linalg.eigh(self.B) 

136 e = self.func(r) 

137 

138 self.p = -np.dot(self.H, g) 

139 p_size = np.sqrt((self.p**2).sum()) 

140 if p_size <= np.sqrt(optimizable.ndofs() / 3 * 1e-10): 

141 self.p /= p_size / np.sqrt(optimizable.ndofs() / 3 * 1e-10) 

142 ls = LineSearch(get_gradient_norm=self.optimizable.gradient_norm) 

143 self.alpha_k, e, self.e0, self.no_update = ls._line_search( 

144 self.func, 

145 self.fprime, 

146 r, 

147 self.p, 

148 g, 

149 e, 

150 self.e0, 

151 maxstep=self.maxstep, 

152 c1=self.c1, 

153 c2=self.c2, 

154 stpmax=self.stpmax, 

155 ) 

156 if self.alpha_k is None: 

157 raise RuntimeError('LineSearch failed!') 

158 

159 dr = self.alpha_k * self.p 

160 optimizable.set_x(r + dr) 

161 self.r0 = r 

162 self.g0 = g 

163 self.dump((self.r0, self.g0, self.e0, self.task, self.H)) 

164 

165 def update(self, r, g, r0, g0, p0): 

166 self.I = eye(self.optimizable.ndofs(), dtype=int) 

167 if self.H is None: 

168 self.H = eye(self.optimizable.ndofs()) 

169 # self.B = np.linalg.inv(self.H) 

170 return 

171 else: 

172 dr = r - r0 

173 dg = g - g0 

174 # self.alpha_k can be None!!! 

175 if not ( 

176 ( 

177 (self.alpha_k or 0) > 0 

178 and abs(np.dot(g, p0)) - abs(np.dot(g0, p0)) < 0 

179 ) 

180 or self.replay 

181 ): 

182 return 

183 if self.no_update is True: 

184 print('skip update') 

185 return 

186 

187 try: # this was handled in numeric, let it remain for more safety 

188 rhok = 1.0 / (np.dot(dg, dr)) 

189 except ZeroDivisionError: 

190 rhok = 1000.0 

191 print('Divide-by-zero encountered: rhok assumed large') 

192 if isinf(rhok): # this is patch for np 

193 rhok = 1000.0 

194 print('Divide-by-zero encountered: rhok assumed large') 

195 A1 = self.I - dr[:, np.newaxis] * dg[np.newaxis, :] * rhok 

196 A2 = self.I - dg[:, np.newaxis] * dr[np.newaxis, :] * rhok 

197 self.H = ( 

198 np.dot(A1, np.dot(self.H, A2)) 

199 + rhok * dr[:, np.newaxis] * dr[np.newaxis, :] 

200 ) 

201 # self.B = np.linalg.inv(self.H) 

202 

203 def func(self, x): 

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

205 self.optimizable.set_x(x) 

206 self.function_calls += 1 

207 # Scale the problem as SciPy uses I as initial Hessian. 

208 return self.optimizable.get_value() / self.alpha 

209 

210 def fprime(self, x): 

211 """Gradient of the objective function for use of the optimizers""" 

212 self.optimizable.set_x(x) 

213 self.force_calls += 1 

214 # Scale the problem as SciPy uses I as initial Hessian. 

215 gradient = self.optimizable.get_gradient() 

216 return gradient / self.alpha 

217 

218 def replay_trajectory(self, traj): 

219 """Initialize hessian from old trajectory.""" 

220 self.replay = True 

221 from ase.utils import IOContext 

222 

223 with IOContext() as files: 

224 if isinstance(traj, str): 

225 from ase.io.trajectory import Trajectory 

226 

227 traj = files.closelater(Trajectory(traj, mode='r')) 

228 

229 r0 = None 

230 g0 = None 

231 for i in range(len(traj) - 1): 

232 r = traj[i].get_positions().ravel() 

233 g = -traj[i].get_forces().ravel() / self.alpha 

234 self.update(r, g, r0, g0, self.p) 

235 self.p = -np.dot(self.H, g) 

236 r0 = r.copy() 

237 g0 = g.copy() 

238 self.r0 = r0 

239 self.g0 = g0 

240 

241 def log(self, gradient): 

242 if self.logfile is None: 

243 return 

244 fmax = self.optimizable.gradient_norm(gradient) 

245 e = self.optimizable.get_value() 

246 T = time.localtime() 

247 name = self.__class__.__name__ 

248 w = self.logfile.write 

249 if self.nsteps == 0: 

250 w( 

251 '%s %4s[%3s] %8s %15s %12s\n' 

252 % (' ' * len(name), 'Step', 'FC', 'Time', 'Energy', 'fmax') 

253 ) 

254 w( 

255 '%s: %3d[%3d] %02d:%02d:%02d %15.6f %12.4f\n' 

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

257 ) 

258 

259 

260def wrap_function(function, args): 

261 ncalls = [0] 

262 

263 def function_wrapper(x): 

264 ncalls[0] += 1 

265 return function(x, *args) 

266 

267 return ncalls, function_wrapper