Coverage for ase/optimize/sciopt.py: 69.37%

111 statements  

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

1from typing import IO 

2 

3import numpy as np 

4import scipy.optimize as opt 

5 

6from ase import Atoms 

7from ase.optimize.optimize import Optimizer 

8from ase.utils import deprecate_positionals 

9 

10 

11class Converged(Exception): 

12 pass 

13 

14 

15class OptimizerConvergenceError(Exception): 

16 pass 

17 

18 

19class SciPyOptimizer(Optimizer): 

20 """General interface for SciPy optimizers 

21 

22 Only the call to the optimizer is still needed 

23 """ 

24 

25 @deprecate_positionals(2) 

26 def __init__( 

27 self, 

28 atoms: Atoms, 

29 logfile: IO | str = '-', 

30 trajectory: str | None = None, 

31 callback_always: bool = False, 

32 alpha: float = 70.0, 

33 **kwargs, 

34 ): 

35 """Initialize object 

36 

37 Parameters 

38 ---------- 

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

40 The Atoms object to relax. 

41 

42 trajectory: str 

43 Trajectory file used to store optimisation path. 

44 

45 logfile: file object or str 

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

47 Use '-' for stdout. 

48 

49 callback_always: bool 

50 Should the callback be run after each force call (also in the 

51 linesearch) 

52 

53 alpha: float 

54 Initial guess for the Hessian (curvature of energy surface). A 

55 conservative value of 70.0 is the default, but number of needed 

56 steps to converge might be less if a lower value is used. However, 

57 a lower value also means risk of instability. 

58 

59 kwargs : dict, optional 

60 Extra arguments passed to 

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

62 

63 Examples 

64 -------- 

65 SciPy provides a number of optimizers. An interface module for a couple 

66 of these have been written for ASE. Most notable are the optimizers 

67 SciPyFminBFGS and SciPyFminCG. These can be imported as: 

68 

69 >>> from ase.optimize.sciopt import SciPyFminBFGS, SciPyFminCG 

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

71 >>> from ase import Atoms 

72 >>> system = Atoms( 

73 ... 'N2', 

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

75 ... calculator=EMT() 

76 ... ) 

77 >>> # The optimizers are called with the regular syntax, e.g.: 

78 >>> dyn = SciPyFminBFGS(system) 

79 >>> dyn.run(fmax=0.05) # doctest:+ELLIPSIS 

80 Step Time Energy fmax 

81 SciPyFminBFGS: 0 ... 0.440344 3.251800 

82 SciPyFminBFGS: 1 ... 0.264361 0.347497 

83 SciPyFminBFGS: 2 ... 0.262860 0.080535 

84 SciPyFminBFGS: 3 ... 0.262777 0.001453 

85 ... 

86 """ 

87 restart = None 

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

89 self.force_calls = 0 

90 self.callback_always = callback_always 

91 self.H0 = alpha 

92 self.max_steps = 0 

93 

94 def x0(self): 

95 """Return x0 in a way SciPy can use 

96 

97 This class is mostly usable for subclasses wanting to redefine the 

98 parameters (and the objective function)""" 

99 return self.optimizable.get_x() 

100 

101 def f(self, x): 

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

103 self.optimizable.set_x(x) 

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

105 return self.optimizable.get_value() / self.H0 

106 

107 def fprime(self, x): 

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

109 self.optimizable.set_x(x) 

110 self.force_calls += 1 

111 

112 if self.callback_always: 

113 self.callback(x) 

114 

115 # Remember that forces are minus the gradient! 

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

117 return self.optimizable.get_gradient() / self.H0 

118 

119 def callback(self, x): 

120 """Callback function to be run after each iteration by SciPy 

121 

122 This should also be called once before optimization starts, as SciPy 

123 optimizers only calls it after each iteration, while ase optimizers 

124 call something similar before as well. 

125 

126 :meth:`callback`() can raise a :exc:`Converged` exception to signal the 

127 optimisation is complete. This will be silently ignored by 

128 :meth:`run`(). 

129 """ 

130 if self.nsteps < self.max_steps: 

131 self.nsteps += 1 

132 gradient = self.optimizable.get_gradient() 

133 self.log(gradient) 

134 self.call_observers() 

135 if self.gradient_converged(gradient): 

136 raise Converged 

137 

138 def run(self, fmax=0.05, steps=100000000): 

139 self.fmax = fmax 

140 

141 try: 

142 # As SciPy does not log the zeroth iteration, we do that manually 

143 if self.nsteps == 0: 

144 gradient = self.optimizable.get_gradient() 

145 self.log(gradient) 

146 self.call_observers() 

147 

148 self.max_steps = steps + self.nsteps 

149 

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

151 self.call_fmin(fmax / self.H0, steps) 

152 except Converged: 

153 pass 

154 gradient = self.optimizable.get_gradient() 

155 return self.gradient_converged(gradient) 

156 

157 def dump(self, data): 

158 pass 

159 

160 def load(self): 

161 pass 

162 

163 def call_fmin(self, fmax, steps): 

164 raise NotImplementedError 

165 

166 

167class SciPyFminCG(SciPyOptimizer): 

168 """Non-linear (Polak-Ribiere) conjugate gradient algorithm""" 

169 

170 def call_fmin(self, fmax, steps): 

171 output = opt.fmin_cg( 

172 self.f, 

173 self.x0(), 

174 fprime=self.fprime, 

175 # args=(), 

176 gtol=fmax * 0.1, # Should never be reached 

177 norm=np.inf, 

178 # epsilon= 

179 maxiter=steps, 

180 full_output=1, 

181 disp=0, 

182 # retall=0, 

183 callback=self.callback, 

184 ) 

185 warnflag = output[-1] 

186 if warnflag == 2: 

187 raise OptimizerConvergenceError( 

188 'Warning: Desired error not necessarily achieved ' 

189 'due to precision loss' 

190 ) 

191 

192 

193class SciPyFminBFGS(SciPyOptimizer): 

194 """Quasi-Newton method (Broydon-Fletcher-Goldfarb-Shanno)""" 

195 

196 def call_fmin(self, fmax, steps): 

197 output = opt.fmin_bfgs( 

198 self.f, 

199 self.x0(), 

200 fprime=self.fprime, 

201 # args=(), 

202 gtol=fmax * 0.1, # Should never be reached 

203 norm=np.inf, 

204 # epsilon=1.4901161193847656e-08, 

205 maxiter=steps, 

206 full_output=1, 

207 disp=0, 

208 # retall=0, 

209 callback=self.callback, 

210 ) 

211 warnflag = output[-1] 

212 if warnflag == 2: 

213 raise OptimizerConvergenceError( 

214 'Warning: Desired error not necessarily achieved ' 

215 'due to precision loss' 

216 ) 

217 

218 

219class SciPyGradientlessOptimizer(Optimizer): 

220 """General interface for gradient less SciPy optimizers 

221 

222 Only the call to the optimizer is still needed 

223 

224 Note: If you redefine x0() and f(), you don't even need an atoms object. 

225 Redefining these also allows you to specify an arbitrary objective 

226 function. 

227 

228 XXX: This is still a work in progress 

229 """ 

230 

231 def __init__( 

232 self, 

233 atoms: Atoms, 

234 logfile: IO | str = '-', 

235 trajectory: str | None = None, 

236 callback_always: bool = False, 

237 **kwargs, 

238 ): 

239 """Initialize object 

240 

241 Parameters 

242 ---------- 

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

244 The Atoms object to relax. 

245 

246 trajectory: str 

247 Trajectory file used to store optimisation path. 

248 

249 logfile: file object or str 

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

251 Use '-' for stdout. 

252 

253 callback_always: bool 

254 Should the callback be run after each force call (also in the 

255 linesearch) 

256 

257 alpha: float 

258 Initial guess for the Hessian (curvature of energy surface). A 

259 conservative value of 70.0 is the default, but number of needed 

260 steps to converge might be less if a lower value is used. However, 

261 a lower value also means risk of instability. 

262 

263 kwargs : dict, optional 

264 Extra arguments passed to 

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

266 

267 """ 

268 restart = None 

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

270 self.function_calls = 0 

271 self.callback_always = callback_always 

272 

273 def x0(self): 

274 """Return x0 in a way SciPy can use 

275 

276 This class is mostly usable for subclasses wanting to redefine the 

277 parameters (and the objective function)""" 

278 return self.optimizable.get_x().reshape(-1) 

279 

280 def f(self, x): 

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

282 self.optimizable.set_x(x) 

283 self.function_calls += 1 

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

285 return self.optimizable.get_value() 

286 

287 def callback(self, x): 

288 """Callback function to be run after each iteration by SciPy 

289 

290 This should also be called once before optimization starts, as SciPy 

291 optimizers only calls it after each iteration, while ase optimizers 

292 call something similar before as well. 

293 """ 

294 # We can't assume that forces are available! 

295 # f = self.optimizable.get_gradient().reshape(-1, 3) 

296 # self.log(f) 

297 self.call_observers() 

298 # if self.converged(f): 

299 # raise Converged 

300 self.nsteps += 1 

301 

302 def run(self, ftol=0.01, xtol=0.01, steps=100000000): 

303 self.xtol = xtol 

304 self.ftol = ftol 

305 # As SciPy does not log the zeroth iteration, we do that manually 

306 self.callback(None) 

307 try: 

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

309 self.call_fmin(xtol, ftol, steps) 

310 except Converged: 

311 pass 

312 return self.converged() 

313 

314 def dump(self, data): 

315 pass 

316 

317 def load(self): 

318 pass 

319 

320 def call_fmin(self, xtol, ftol, steps): 

321 raise NotImplementedError 

322 

323 

324class SciPyFmin(SciPyGradientlessOptimizer): 

325 """Nelder-Mead Simplex algorithm 

326 

327 Uses only function calls. 

328 

329 XXX: This is still a work in progress 

330 """ 

331 

332 def call_fmin(self, xtol, ftol, steps): 

333 opt.fmin( 

334 self.f, 

335 self.x0(), 

336 # args=(), 

337 xtol=xtol, 

338 ftol=ftol, 

339 maxiter=steps, 

340 # maxfun=None, 

341 # full_output=1, 

342 disp=0, 

343 # retall=0, 

344 callback=self.callback, 

345 ) 

346 

347 

348class SciPyFminPowell(SciPyGradientlessOptimizer): 

349 """Powell's (modified) level set method 

350 

351 Uses only function calls. 

352 

353 XXX: This is still a work in progress 

354 """ 

355 

356 def __init__(self, *args, **kwargs): 

357 """Parameters: 

358 

359 direc: float 

360 How much to change x to initially. Defaults to 0.04. 

361 """ 

362 direc = kwargs.pop('direc', None) 

363 super().__init__(*args, **kwargs) 

364 

365 if direc is None: 

366 self.direc = np.eye(len(self.x0()), dtype=float) * 0.04 

367 else: 

368 self.direc = np.eye(len(self.x0()), dtype=float) * direc 

369 

370 def call_fmin(self, xtol, ftol, steps): 

371 opt.fmin_powell( 

372 self.f, 

373 self.x0(), 

374 # args=(), 

375 xtol=xtol, 

376 ftol=ftol, 

377 maxiter=steps, 

378 # maxfun=None, 

379 # full_output=1, 

380 disp=0, 

381 # retall=0, 

382 callback=self.callback, 

383 direc=self.direc, 

384 )