Coverage for ase/optimize/precon/lbfgs.py: 86.17%

188 statements  

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

1import time 

2import warnings 

3from math import sqrt 

4 

5import numpy as np 

6 

7from ase.filters import UnitCellFilter 

8from ase.optimize.optimize import Optimizer 

9from ase.optimize.precon.precon import make_precon 

10from ase.utils import deprecate_positionals 

11from ase.utils.linesearch import LineSearch 

12from ase.utils.linesearcharmijo import LineSearchArmijo 

13 

14 

15class PreconLBFGS(Optimizer): 

16 """Preconditioned version of the Limited memory BFGS optimizer, to 

17 be used as a drop-in replacement for ase.optimize.lbfgs.LBFGS for systems 

18 where a good preconditioner is available. 

19 

20 In the standard bfgs and lbfgs algorithms, the inverse of Hessian matrix 

21 is a (usually fixed) diagonal matrix. By contrast, PreconLBFGS, 

22 updates the hessian after each step with a general "preconditioner". 

23 By default, the ase.optimize.precon.Exp preconditioner is applied. 

24 This preconditioner is well-suited for large condensed phase structures, 

25 in particular crystalline. For systems outside this category, 

26 PreconLBFGS with Exp preconditioner may yield unpredictable results. 

27 

28 In time this implementation is expected to replace 

29 ase.optimize.lbfgs.LBFGS. 

30 

31 See this article for full details: D. Packwood, J. R. Kermode, L. Mones, 

32 N. Bernstein, J. Woolley, N. Gould, C. Ortner, and G. Csanyi, A universal 

33 preconditioner for simulating condensed phase materials 

34 J. Chem. Phys. 144, 164109 (2016), DOI: https://doi.org/10.1063/1.4947024 

35 """ 

36 

37 # CO : added parameters rigid_units and rotation_factors 

38 @deprecate_positionals(2) 

39 def __init__( 

40 self, 

41 atoms, 

42 restart=None, 

43 logfile='-', 

44 trajectory=None, 

45 maxstep=None, 

46 memory=100, 

47 damping=1.0, 

48 alpha=70.0, 

49 precon='auto', 

50 variable_cell=False, 

51 use_armijo=True, 

52 c1=0.23, 

53 c2=0.46, 

54 a_min=None, 

55 rigid_units=None, 

56 rotation_factors=None, 

57 Hinv=None, 

58 **kwargs, 

59 ): 

60 """ 

61 

62 Parameters 

63 ---------- 

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

65 The Atoms object to relax. 

66 

67 restart: str 

68 Pickle file used to store vectors for updating the inverse of 

69 Hessian matrix. If set, file with such a name will be searched 

70 and information stored will be used, if the file exists. 

71 

72 logfile: file object or str 

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

74 Use '-' for stdout. 

75 

76 trajectory: str 

77 Trajectory file used to store optimisation path. 

78 

79 maxstep: float 

80 How far is a single atom allowed to move. This is useful for DFT 

81 calculations where wavefunctions can be reused if steps are small. 

82 Default is 0.04 Angstrom. 

83 

84 memory: int 

85 Number of steps to be stored. Default value is 100. Three numpy 

86 arrays of this length containing floats are stored. 

87 

88 damping: float 

89 The calculated step is multiplied with this number before added to 

90 the positions. 

91 

92 alpha: float 

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

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

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

96 a lower value also means risk of instability. 

97 

98 precon: ase.optimize.precon.Precon instance or compatible. 

99 Apply the given preconditioner during optimization. Defaults to 

100 'auto', which will choose the `Exp` preconditioner unless the system 

101 is too small (< 100 atoms) in which case a standard LBFGS fallback 

102 is used. To enforce use of the `Exp` preconditioner, use `precon = 

103 'Exp'`. Other options include 'C1', 'Pfrommer' and 'FF' - see the 

104 corresponding classes in the `ase.optimize.precon` module for more 

105 details. Pass precon=None or precon='ID' to disable preconditioning. 

106 

107 use_armijo: boolean 

108 Enforce only the Armijo condition of sufficient decrease of 

109 of the energy, and not the second Wolff condition for the forces. 

110 Often significantly faster than full Wolff linesearch. 

111 Defaults to True. 

112 

113 c1: float 

114 c1 parameter for the line search. Default is c1=0.23. 

115 

116 c2: float 

117 c2 parameter for the line search. Default is c2=0.46. 

118 

119 a_min: float 

120 minimal value for the line search step parameter. Default is 

121 a_min=1e-8 (use_armijo=False) or 1e-10 (use_armijo=True). 

122 Higher values can be useful to avoid performing many 

123 line searches for comparatively small changes in geometry. 

124 

125 variable_cell: bool 

126 If True, wrap atoms in UnitCellFilter to 

127 relax both postions and cell. Default is False. 

128 

129 rigid_units: each I = rigid_units[i] is a list of indices, which 

130 describes a subsystem of atoms that forms a (near-)rigid unit 

131 If rigid_units is not None, then special search-paths are 

132 are created to take the rigidness into account 

133 

134 rotation_factors: list of scalars; acceleration factors deteriming 

135 the rate of rotation as opposed to the rate of stretch in the 

136 rigid units 

137 

138 kwargs : dict, optional 

139 Extra arguments passed to 

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

141 

142 """ 

143 if variable_cell: 

144 atoms = UnitCellFilter(atoms) 

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

146 

147 self._actual_atoms = atoms 

148 

149 # default preconditioner 

150 # TODO: introduce a heuristic for different choices of preconditioners 

151 if precon == 'auto': 

152 if len(atoms) < 100: 

153 precon = None 

154 warnings.warn( 

155 'The system is likely too small to benefit from ' 

156 'the standard preconditioner, hence it is ' 

157 'disabled. To re-enable preconditioning, call ' 

158 '`PreconLBFGS` by explicitly providing the ' 

159 'kwarg `precon`' 

160 ) 

161 else: 

162 precon = 'Exp' 

163 

164 if maxstep is not None: 

165 if maxstep > 1.0: 

166 raise ValueError( 

167 'You are using a much too large value for ' 

168 + 'the maximum step size: %.1f Angstrom' % maxstep 

169 ) 

170 self.maxstep = maxstep 

171 else: 

172 self.maxstep = 0.04 

173 

174 self.memory = memory 

175 self.H0 = 1.0 / alpha # Initial approximation of inverse Hessian 

176 # 1./70. is to emulate the behaviour of BFGS 

177 # Note that this is never changed! 

178 self.Hinv = Hinv 

179 self.damping = damping 

180 self.p = None 

181 

182 # construct preconditioner if passed as a string 

183 self.precon = make_precon(precon) 

184 self.use_armijo = use_armijo 

185 self.c1 = c1 

186 self.c2 = c2 

187 self.a_min = a_min 

188 if self.a_min is None: 

189 self.a_min = 1e-10 if use_armijo else 1e-8 

190 

191 # CO 

192 self.rigid_units = rigid_units 

193 self.rotation_factors = rotation_factors 

194 

195 def reset_hessian(self): 

196 """ 

197 Throw away history of the Hessian 

198 """ 

199 self._just_reset_hessian = True 

200 self.s = [] 

201 self.y = [] 

202 self.rho = [] # Store also rho, to avoid calculating the dot product 

203 # again and again 

204 

205 def initialize(self): 

206 """Initialize everything so no checks have to be done in step""" 

207 self.iteration = 0 

208 self.reset_hessian() 

209 self.r0 = None 

210 self.f0 = None 

211 self.e0 = None 

212 self.e1 = None 

213 self.task = 'START' 

214 self.load_restart = False 

215 

216 def read(self): 

217 """Load saved arrays to reconstruct the Hessian""" 

218 ( 

219 self.iteration, 

220 self.s, 

221 self.y, 

222 self.rho, 

223 self.r0, 

224 self.f0, 

225 self.e0, 

226 self.task, 

227 ) = self.load() 

228 self.load_restart = True 

229 

230 def step(self, f=None): 

231 """Take a single step 

232 

233 Use the given forces, update the history and calculate the next step -- 

234 then take it""" 

235 r = self._actual_atoms.get_positions() 

236 if f is None: 

237 f = self._actual_atoms.get_forces() 

238 

239 previously_reset_hessian = self._just_reset_hessian 

240 self.update(r, f, self.r0, self.f0) 

241 

242 s = self.s 

243 y = self.y 

244 rho = self.rho 

245 H0 = self.H0 

246 

247 loopmax = np.min([self.memory, len(self.y)]) 

248 a = np.empty((loopmax,), dtype=np.float64) 

249 

250 # The algorithm itself: 

251 q = -f.reshape(-1) 

252 for i in range(loopmax - 1, -1, -1): 

253 a[i] = rho[i] * np.dot(s[i], q) 

254 q -= a[i] * y[i] 

255 

256 if self.precon is None: 

257 if self.Hinv is not None: 

258 z = np.dot(self.Hinv, q) 

259 else: 

260 z = H0 * q 

261 else: 

262 self.precon.make_precon(self._actual_atoms) 

263 z = self.precon.solve(q) 

264 

265 for i in range(loopmax): 

266 b = rho[i] * np.dot(y[i], z) 

267 z += s[i] * (a[i] - b) 

268 

269 self.p = -z.reshape((-1, 3)) 

270 ### 

271 

272 g = -f 

273 if self.e1 is not None: 

274 e = self.e1 

275 else: 

276 e = self.func(r) 

277 self.line_search(r, g, e, previously_reset_hessian) 

278 dr = (self.alpha_k * self.p).reshape(len(self._actual_atoms), -1) 

279 

280 if self.alpha_k != 0.0: 

281 self._actual_atoms.set_positions(r + dr) 

282 

283 self.iteration += 1 

284 self.r0 = r 

285 self.f0 = -g 

286 self.dump( 

287 ( 

288 self.iteration, 

289 self.s, 

290 self.y, 

291 self.rho, 

292 self.r0, 

293 self.f0, 

294 self.e0, 

295 self.task, 

296 ) 

297 ) 

298 

299 def update(self, r, f, r0, f0): 

300 """Update everything that is kept in memory 

301 

302 This function is mostly here to allow for replay_trajectory. 

303 """ 

304 if not self._just_reset_hessian: 

305 s0 = r.reshape(-1) - r0.reshape(-1) 

306 self.s.append(s0) 

307 

308 # We use the gradient which is minus the force! 

309 y0 = f0.reshape(-1) - f.reshape(-1) 

310 self.y.append(y0) 

311 

312 rho0 = 1.0 / np.dot(y0, s0) 

313 self.rho.append(rho0) 

314 self._just_reset_hessian = False 

315 

316 if len(self.y) > self.memory: 

317 self.s.pop(0) 

318 self.y.pop(0) 

319 self.rho.pop(0) 

320 

321 def replay_trajectory(self, traj): 

322 """Initialize history from old trajectory.""" 

323 if isinstance(traj, str): 

324 from ase.io.trajectory import Trajectory 

325 

326 traj = Trajectory(traj, 'r') 

327 r0 = None 

328 f0 = None 

329 # The last element is not added, as we get that for free when taking 

330 # the first qn-step after the replay 

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

332 r = traj[i].get_positions() 

333 f = traj[i].get_forces() 

334 self.update(r, f, r0, f0) 

335 r0 = r.copy() 

336 f0 = f.copy() 

337 self.iteration += 1 

338 self.r0 = r0 

339 self.f0 = f0 

340 

341 def func(self, x): 

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

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

344 potl = self._actual_atoms.get_potential_energy() 

345 return potl 

346 

347 def fprime(self, x): 

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

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

350 # Remember that forces are minus the gradient! 

351 return -self._actual_atoms.get_forces().reshape(-1) 

352 

353 def line_search(self, r, g, e, previously_reset_hessian): 

354 self.p = self.p.ravel() 

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

356 if p_size <= np.sqrt(len(self._actual_atoms) * 1e-10): 

357 self.p /= p_size / np.sqrt(len(self._actual_atoms) * 1e-10) 

358 g = g.ravel() 

359 r = r.ravel() 

360 

361 if self.use_armijo: 

362 try: 

363 # CO: modified call to ls.run 

364 # TODO: pass also the old slope to the linesearch 

365 # so that the RumPath can extract a better starting guess? 

366 # alternatively: we can adjust the rotation_factors 

367 # out using some extrapolation tricks? 

368 ls = LineSearchArmijo(self.func, c1=self.c1, tol=1e-14) 

369 step, func_val, _no_update = ls.run( 

370 r, 

371 self.p, 

372 a_min=self.a_min, 

373 func_start=e, 

374 func_prime_start=g, 

375 func_old=self.e0, 

376 rigid_units=self.rigid_units, 

377 rotation_factors=self.rotation_factors, 

378 maxstep=self.maxstep, 

379 ) 

380 self.e0 = e 

381 self.e1 = func_val 

382 self.alpha_k = step 

383 except (ValueError, RuntimeError): 

384 if not previously_reset_hessian: 

385 warnings.warn( 

386 'Armijo linesearch failed, resetting Hessian and ' 

387 'trying again' 

388 ) 

389 self.reset_hessian() 

390 self.alpha_k = 0.0 

391 else: 

392 raise RuntimeError( 

393 'Armijo linesearch failed after reset of Hessian, ' 

394 'aborting' 

395 ) 

396 

397 else: 

398 ls = LineSearch() 

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

400 self.func, 

401 self.fprime, 

402 r, 

403 self.p, 

404 g, 

405 e, 

406 self.e0, 

407 stpmin=self.a_min, 

408 maxstep=self.maxstep, 

409 c1=self.c1, 

410 c2=self.c2, 

411 stpmax=50.0, 

412 ) 

413 self.e1 = e 

414 if self.alpha_k is None: 

415 raise RuntimeError('Wolff lineSearch failed!') 

416 

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

418 if smax is None: 

419 smax = fmax 

420 self.smax = smax 

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

422 

423 def log(self, gradient): 

424 forces = self._actual_atoms.get_forces() 

425 if isinstance(self._actual_atoms, UnitCellFilter): 

426 natoms = len(self._actual_atoms.atoms) 

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

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

429 smax = sqrt((stress**2).max()) 

430 else: 

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

432 if self.e1 is not None: 

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

434 e = self.e1 

435 else: 

436 e = self._actual_atoms.get_potential_energy() 

437 T = time.localtime() 

438 if self.logfile is not None: 

439 name = self.__class__.__name__ 

440 if isinstance(self._actual_atoms, UnitCellFilter): 

441 self.logfile.write( 

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

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

444 ) 

445 

446 else: 

447 self.logfile.write( 

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

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

450 ) 

451 

452 def gradient_converged(self, gradient): 

453 """Did the optimization converge?""" 

454 # XXX ignoring gradient 

455 forces = self._actual_atoms.get_forces() 

456 if isinstance(self._actual_atoms, UnitCellFilter): 

457 natoms = len(self._actual_atoms.atoms) 

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

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

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

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

462 else: 

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

464 return fmax_sq < self.fmax**2