Coverage for ase/optimize/optimize.py: 93.91%

230 statements  

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

1"""Structure optimization.""" 

2 

3import time 

4import warnings 

5from collections.abc import Callable 

6from contextlib import contextmanager 

7from functools import cached_property 

8from os.path import isfile 

9from pathlib import Path 

10from typing import IO, Any 

11 

12from ase import Atoms 

13from ase.calculators.calculator import PropertyNotImplementedError 

14from ase.filters import UnitCellFilter 

15from ase.parallel import world 

16from ase.utils import IOContext 

17from ase.utils.abc import Optimizable 

18 

19DEFAULT_MAX_STEPS = 100_000_000 

20 

21 

22class RestartError(RuntimeError): 

23 pass 

24 

25 

26class OptimizableAtoms(Optimizable): 

27 def __init__(self, atoms): 

28 self.atoms = atoms 

29 

30 def get_x(self): 

31 return self.atoms.get_positions().ravel() 

32 

33 def set_x(self, x): 

34 self.atoms.set_positions(x.reshape(-1, 3)) 

35 

36 def get_gradient(self): 

37 return -self.atoms.get_forces().ravel() 

38 

39 @cached_property 

40 def _use_force_consistent_energy(self): 

41 # This boolean is in principle invalidated if the 

42 # calculator changes. This can lead to weird things 

43 # in multi-step optimizations. 

44 try: 

45 self.atoms.get_potential_energy(force_consistent=True) 

46 except PropertyNotImplementedError: 

47 # warnings.warn( 

48 # 'Could not get force consistent energy (\'free_energy\'). ' 

49 # 'Please make sure calculator provides \'free_energy\', even ' 

50 # 'if equal to the ordinary energy. ' 

51 # 'This will raise an error in future versions of ASE.', 

52 # FutureWarning) 

53 return False 

54 else: 

55 return True 

56 

57 def get_value(self): 

58 force_consistent = self._use_force_consistent_energy 

59 return self.atoms.get_potential_energy( 

60 force_consistent=force_consistent 

61 ) 

62 

63 def iterimages(self): 

64 # XXX document purpose of iterimages 

65 return self.atoms.iterimages() 

66 

67 def ndofs(self): 

68 return 3 * len(self.atoms) 

69 

70 

71class Log: 

72 def __init__(self, logfile, comm): 

73 self._logfile = logfile 

74 self._comm = comm 

75 

76 def write(self, msg): 

77 if self._logfile is None or self._comm.rank != 0: 

78 return 

79 

80 if hasattr(self._logfile, 'write'): 

81 self._logfile.write(msg) 

82 return 

83 

84 if self._logfile == '-': 

85 print(msg, end='') 

86 return 

87 

88 with open(self._logfile, mode='a') as fd: 

89 fd.write(msg) 

90 

91 def flush(self): 

92 warnings.warn( 

93 'Log flushes by default now. Please do not call ' 

94 'flush(). If you want a different flushing behaviour ' 

95 'please open logfile yourself and choose ' 

96 'buffering mode as appropriate. ' 

97 'This flush() method currently does nothing.', 

98 FutureWarning, 

99 ) 

100 

101 

102class BaseDynamics(IOContext): 

103 """Common superclass for optimization and MD. 

104 

105 This class implements logfile, trajectory, and observer handling. 

106 It should do as little as possible other than that. 

107 

108 We should try to remove the "atoms" parameter from this class, 

109 since Optimizers only require Optimizables. 

110 """ 

111 

112 def __init__( 

113 self, 

114 atoms: Atoms, 

115 logfile: IO | Path | str | None = None, 

116 trajectory: str | Path | None = None, 

117 append_trajectory: bool = False, 

118 master: bool | None = None, 

119 comm=world, 

120 *, 

121 loginterval: int = 1, 

122 ): 

123 self.atoms = atoms 

124 self.logfile = Log(logfile, comm=comm) 

125 self.observers: list[tuple[Callable, int, tuple, dict[str, Any]]] = [] 

126 self.nsteps = 0 

127 self.max_steps = 0 # to be updated in run or irun 

128 self.comm = comm 

129 

130 self._orig_trajectory = trajectory 

131 self._master = master 

132 

133 if trajectory is None or hasattr(trajectory, 'write'): 

134 # 'write' attribute is meant to check for a Trajectory 

135 # (could be BundleTrajectory). 

136 # There is no unified way to check for Trajectory. 

137 # In this case the trajectory is already open so we do not 

138 # open it. 

139 pass 

140 else: 

141 trajectory = Path(trajectory) 

142 if comm.rank == 0 and not append_trajectory: 

143 trajectory.unlink(missing_ok=True) 

144 

145 if trajectory is not None: 

146 self.attach( 

147 self._traj_write_image, 

148 interval=loginterval, 

149 description={'interval': loginterval}, 

150 ) 

151 

152 self.trajectory = trajectory 

153 

154 def todict(self) -> dict[str, Any]: 

155 raise NotImplementedError 

156 

157 @contextmanager 

158 def _opentraj(self): 

159 from ase.io.trajectory import Trajectory 

160 

161 assert self._orig_trajectory is not None 

162 

163 if hasattr(self._orig_trajectory, 'write'): 

164 # Already an open trajectory, we are not responsible for open/close 

165 yield self._orig_trajectory 

166 return 

167 

168 with Trajectory( 

169 self._orig_trajectory, 

170 master=self._master, 

171 mode='a', 

172 comm=self.comm, 

173 ) as traj: 

174 yield traj 

175 

176 def _traj_write_image(self, description: dict): 

177 with self._opentraj() as traj: 

178 # The description is only written when we write a header, 

179 # and we probably only write the header when we need to 

180 # (in append mode) but I am not sure about that. 

181 traj.set_description(self.todict() | description) 

182 traj.write(self.atoms.__ase_optimizable__()) 

183 

184 def _traj_is_empty(self): 

185 with self._opentraj() as traj: 

186 return len(traj) == 0 

187 

188 def _get_gradient(self, forces=None): 

189 if forces is not None: 

190 warnings.warn( 

191 'Please do not pass forces to step(). ' 

192 'This argument will be removed in ' 

193 'ase 3.28.0.' 

194 ) 

195 return -forces.ravel() 

196 return self.optimizable.get_gradient() 

197 

198 def get_number_of_steps(self): 

199 return self.nsteps 

200 

201 def insert_observer( 

202 self, function, position=0, interval=1, *args, **kwargs 

203 ): 

204 """Insert an observer. 

205 

206 This can be used for pre-processing before logging and dumping. 

207 

208 Examples 

209 -------- 

210 >>> from ase.build import bulk 

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

212 >>> from ase.optimize import BFGS 

213 ... 

214 ... 

215 >>> def update_info(atoms, opt): 

216 ... atoms.info["nsteps"] = opt.nsteps 

217 ... 

218 ... 

219 >>> atoms = bulk("Cu", cubic=True) * 2 

220 >>> atoms.rattle() 

221 >>> atoms.calc = EMT() 

222 >>> with BFGS(atoms, logfile=None, trajectory="opt.traj") as opt: 

223 ... opt.insert_observer(update_info, atoms=atoms, opt=opt) 

224 ... opt.run(fmax=0.05, steps=10) # doctest:+SKIP 

225 """ 

226 if not isinstance(function, Callable): 

227 function = function.write 

228 self.observers.insert(position, (function, interval, args, kwargs)) 

229 

230 def attach(self, function, interval=1, *args, **kwargs): 

231 """Attach callback function. 

232 

233 If *interval > 0*, at every *interval* steps, call *function* with 

234 arguments *args* and keyword arguments *kwargs*. 

235 

236 If *interval <= 0*, after step *interval*, call *function* with 

237 arguments *args* and keyword arguments *kwargs*. This is 

238 currently zero indexed.""" 

239 

240 if not isinstance(function, Callable): 

241 function = function.write 

242 self.observers.append((function, interval, args, kwargs)) 

243 

244 def call_observers(self): 

245 for function, interval, args, kwargs in self.observers: 

246 call = False 

247 # Call every interval iterations 

248 if interval > 0: 

249 if (self.nsteps % interval) == 0: 

250 call = True 

251 # Call only on iteration interval 

252 elif interval <= 0: 

253 if self.nsteps == abs(interval): 

254 call = True 

255 if call: 

256 function(*args, **kwargs) 

257 

258 

259class Dynamics(BaseDynamics): 

260 """Historical base-class for MD and structure optimization classes. 

261 

262 This inheritance level can probably be eliminated by merging it with 

263 Optimizer, since by now, the only significant thing it provides 

264 is the implementation of irun() suitable for optimizations. 

265 

266 This class is an implementation detail and may change or be removed. 

267 """ 

268 

269 def __init__(self, atoms: Atoms, *args, **kwargs): 

270 """Dynamics object. 

271 

272 Parameters 

273 ---------- 

274 atoms : Atoms object 

275 The Atoms object to operate on. 

276 

277 logfile : file object, Path, or str 

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

279 Use '-' for stdout. 

280 

281 trajectory : Trajectory object, str, or Path 

282 Attach a trajectory object. If *trajectory* is a string/Path, a 

283 Trajectory will be constructed. Use *None* for no trajectory. 

284 

285 append_trajectory : bool 

286 Defaults to False, which causes the trajectory file to be 

287 overwriten each time the dynamics is restarted from scratch. 

288 If True, the new structures are appended to the trajectory 

289 file instead. 

290 

291 master : bool 

292 Defaults to None, which causes only rank 0 to save files. If set to 

293 true, this rank will save files. 

294 

295 comm : Communicator object 

296 Communicator to handle parallel file reading and writing. 

297 

298 loginterval : int, default: 1 

299 Only write a log line for every *loginterval* time steps. 

300 """ 

301 super().__init__(atoms, *args, **kwargs) 

302 self.atoms = atoms 

303 self.optimizable = atoms.__ase_optimizable__() 

304 

305 def irun(self, steps=DEFAULT_MAX_STEPS): 

306 """Run dynamics algorithm as generator. 

307 

308 Parameters 

309 ---------- 

310 steps : int, default=DEFAULT_MAX_STEPS 

311 Number of dynamics steps to be run. 

312 

313 Yields 

314 ------ 

315 converged : bool 

316 True if the forces on atoms are converged. 

317 

318 Examples 

319 -------- 

320 This method allows, e.g., to run two optimizers or MD thermostats at 

321 the same time. 

322 #>>> opt1 = BFGS(atoms) 

323 #>>> opt2 = BFGS(StrainFilter(atoms)).irun() 

324 #>>> for _ in opt2: 

325 #... opt1.run() 

326 """ 

327 

328 # update the maximum number of steps 

329 self.max_steps = self.nsteps + steps 

330 

331 # compute the initial step 

332 gradient = self.optimizable.get_gradient() 

333 

334 # log the initial step 

335 if self.nsteps == 0: 

336 self.log(gradient) 

337 

338 # we write a trajectory file if it is None 

339 if self.trajectory is None: 

340 self.call_observers() 

341 # We do not write on restart w/ an existing trajectory file 

342 # present. This duplicates the same entry twice 

343 elif self._traj_is_empty(): 

344 self.call_observers() 

345 

346 # check convergence 

347 gradient = self.optimizable.get_gradient() 

348 is_converged = self.gradient_converged(gradient) 

349 yield is_converged 

350 

351 # run the algorithm until converged or max_steps reached 

352 while not is_converged and self.nsteps < self.max_steps: 

353 # compute the next step 

354 self.step() 

355 self.nsteps += 1 

356 

357 # log the step 

358 gradient = self.optimizable.get_gradient() 

359 self.log(gradient) 

360 self.call_observers() 

361 

362 # check convergence 

363 gradient = self.optimizable.get_gradient() 

364 is_converged = self.gradient_converged(gradient) 

365 yield is_converged 

366 

367 def run(self, steps=DEFAULT_MAX_STEPS): 

368 """Run dynamics algorithm. 

369 

370 This method will return when the forces on all individual 

371 atoms are less than *fmax* or when the number of steps exceeds 

372 *steps*. 

373 

374 Parameters 

375 ---------- 

376 steps : int, default=DEFAULT_MAX_STEPS 

377 Number of dynamics steps to be run. 

378 

379 Returns 

380 ------- 

381 converged : bool 

382 True if the forces on atoms are converged. 

383 """ 

384 

385 for converged in Dynamics.irun(self, steps=steps): 

386 pass 

387 return converged 

388 

389 def gradient_converged(self, gradient): 

390 """ " a dummy function as placeholder for a real criterion, e.g. in 

391 Optimizer""" 

392 return False 

393 

394 def log(self, *args, **kwargs): 

395 """a dummy function as placeholder for a real logger, e.g. in 

396 Optimizer""" 

397 return True 

398 

399 def step(self): 

400 """this needs to be implemented by subclasses""" 

401 raise RuntimeError('step not implemented.') 

402 

403 

404class Optimizer(Dynamics): 

405 """Base-class for all structure optimization classes.""" 

406 

407 # default maxstep for all optimizers 

408 defaults = {'maxstep': 0.2} 

409 _deprecated = object() 

410 

411 def __init__( 

412 self, 

413 atoms: Atoms, 

414 restart: str | Path | None = None, 

415 logfile: IO | str | Path | None = None, 

416 trajectory: str | Path | None = None, 

417 append_trajectory: bool = False, 

418 **kwargs, 

419 ): 

420 """ 

421 

422 Parameters 

423 ---------- 

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

425 The Atoms object to relax. 

426 

427 restart: str | Path | None 

428 Filename for restart file. Default value is *None*. 

429 

430 logfile: file object, Path, or str 

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

432 Use '-' for stdout. 

433 

434 trajectory: Trajectory object, Path, or str 

435 Attach trajectory object. If *trajectory* is a string a 

436 Trajectory will be constructed. Use *None* for no 

437 trajectory. 

438 

439 append_trajectory: bool 

440 Appended to the trajectory file instead of overwriting it. 

441 

442 kwargs : dict, optional 

443 Extra arguments passed to :class:`~ase.optimize.optimize.Dynamics`. 

444 

445 """ 

446 super().__init__( 

447 atoms=atoms, 

448 logfile=logfile, 

449 trajectory=trajectory, 

450 append_trajectory=append_trajectory, 

451 **kwargs, 

452 ) 

453 

454 self.restart = restart 

455 

456 self.fmax = None 

457 

458 if restart is None or not isfile(restart): 

459 self.initialize() 

460 else: 

461 self.read() 

462 self.comm.barrier() 

463 

464 def read(self): 

465 raise NotImplementedError 

466 

467 def todict(self): 

468 description = { 

469 'type': 'optimization', 

470 'optimizer': self.__class__.__name__, 

471 'restart': None if self.restart is None else str(self.restart), 

472 } 

473 # add custom attributes from subclasses 

474 for attr in ('maxstep', 'alpha', 'max_steps', 'fmax'): 

475 if hasattr(self, attr): 

476 description.update({attr: getattr(self, attr)}) 

477 return description 

478 

479 def initialize(self): 

480 pass 

481 

482 def irun(self, fmax=0.05, steps=DEFAULT_MAX_STEPS): 

483 """Run optimizer as generator. 

484 

485 Parameters 

486 ---------- 

487 fmax : float 

488 Convergence criterion of the forces on atoms. 

489 steps : int, default=DEFAULT_MAX_STEPS 

490 Number of optimizer steps to be run. 

491 

492 Yields 

493 ------ 

494 converged : bool 

495 True if the forces on atoms are converged. 

496 """ 

497 self.fmax = fmax 

498 return Dynamics.irun(self, steps=steps) 

499 

500 def run(self, fmax=0.05, steps=DEFAULT_MAX_STEPS): 

501 """Run optimizer. 

502 

503 Parameters 

504 ---------- 

505 fmax : float 

506 Convergence criterion of the forces on atoms. 

507 steps : int, default=DEFAULT_MAX_STEPS 

508 Number of optimizer steps to be run. 

509 

510 Returns 

511 ------- 

512 converged : bool 

513 True if the forces on atoms are converged. 

514 """ 

515 self.fmax = fmax 

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

517 

518 def converged(self, forces=None, *, gradient=None): 

519 """Did the optimization converge?""" 

520 if gradient is not None: 

521 warnings.warn( 

522 'The gradient keyword will be removed in 3.29.0', FutureWarning 

523 ) 

524 elif forces is not None: 

525 gradient = -forces.ravel() 

526 else: 

527 gradient = self.optimizable.get_gradient() 

528 return self.gradient_converged(gradient) 

529 

530 def gradient_converged(self, gradient): 

531 assert gradient.ndim == 1 

532 return self.optimizable.converged(gradient, self.fmax) 

533 

534 def log(self, gradient): 

535 fmax = self.optimizable.gradient_norm(gradient) 

536 e = self.optimizable.get_value() 

537 T = time.localtime() 

538 if self.logfile is not None: 

539 name = self.__class__.__name__ 

540 if self.nsteps == 0: 

541 args = (' ' * len(name), 'Step', 'Time', 'Energy', 'fmax') 

542 msg = '%s %4s %8s %15s %12s\n' % args 

543 self.logfile.write(msg) 

544 

545 args = (name, self.nsteps, T[3], T[4], T[5], e, fmax) 

546 msg = '%s: %3d %02d:%02d:%02d %15.6f %15.6f\n' % args 

547 self.logfile.write(msg) 

548 

549 def dump(self, data): 

550 from ase.io.jsonio import write_json 

551 

552 if self.comm.rank == 0 and self.restart is not None: 

553 with open(self.restart, 'w') as fd: 

554 write_json(fd, data) 

555 

556 def replay_trajectory(self, traj): 

557 """Reinitialize optimizer state from existing optimization trajectory. 

558 

559 Raises TypeError if optimizer class does not support it.""" 

560 from contextlib import ExitStack 

561 

562 from ase.io.trajectory import Trajectory 

563 

564 if not hasattr(self, '_replay_trajectory'): 

565 raise TypeError( 

566 'This optimizer does not provide _replay_trajectory()' 

567 ) 

568 

569 with ExitStack() as stack: 

570 if isinstance(traj, str): 

571 traj = stack.enter_context(Trajectory(traj, 'r')) 

572 

573 return self._replay_trajectory(traj) 

574 

575 def load(self): 

576 from ase.io.jsonio import read_json 

577 

578 with open(self.restart) as fd: 

579 try: 

580 from ase.optimize import BFGS 

581 

582 if not isinstance(self, BFGS) and isinstance( 

583 self.atoms, UnitCellFilter 

584 ): 

585 warnings.warn( 

586 'WARNING: restart function is untested and may result ' 

587 'in unintended behavior. Namely orig_cell is not ' 

588 'loaded in the UnitCellFilter. Please test on your own' 

589 ' to ensure consistent results.' 

590 ) 

591 return read_json(fd, always_array=False) 

592 except Exception as ex: 

593 msg = ( 

594 'Could not decode restart file as JSON. ' 

595 'You may need to delete the restart file ' 

596 f'{self.restart}' 

597 ) 

598 raise RestartError(msg) from ex