Coverage for ase/optimize/ode.py: 87.37%
95 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1from typing import IO
3import numpy as np
5from ase import Atoms
6from ase.optimize.sciopt import OptimizerConvergenceError, SciPyOptimizer
7from ase.utils import deprecate_positionals
10def ode12r(
11 f,
12 X0,
13 h=None,
14 verbose=1,
15 fmax=1e-6,
16 maxtol=1e3,
17 steps=100,
18 rtol=1e-1,
19 C1=1e-2,
20 C2=2.0,
21 hmin=1e-10,
22 extrapolate=3,
23 callback=None,
24 apply_precon=None,
25 converged=None,
26 residual=None,
27):
28 """
29 Adaptive ODE solver, which uses 1st and 2nd order approximations to
30 estimate local error and choose a new step length.
32 This optimizer is described in detail in:
34 S. Makri, C. Ortner and J. R. Kermode, J. Chem. Phys.
35 150, 094109 (2019)
36 https://dx.doi.org/10.1063/1.5064465
38 Parameters
39 ----------
41 f : function
42 function returning driving force on system
43 X0 : 1-dimensional array
44 initial value of degrees of freedom
45 h : float
46 step size, if None an estimate is used based on ODE12
47 verbose: int
48 verbosity level. 0=no output, 1=log output (default), 2=debug output.
49 fmax : float
50 convergence tolerance for residual force
51 maxtol: float
52 terminate if reisdual exceeds this value
53 rtol : float
54 relative tolerance
55 C1 : float
56 sufficient contraction parameter
57 C2 : float
58 residual growth control (Inf means there is no control)
59 hmin : float
60 minimal allowed step size
61 extrapolate : int
62 extrapolation style (3 seems the most robust)
63 callback : function
64 optional callback function to call after each update step
65 apply_precon: function
66 apply a apply_preconditioner to the optimisation
67 converged: function
68 alternative function to check convergence, rather than
69 using a simple norm of the forces.
70 residual: function
71 compute the residual from the current forces
73 Returns
74 -------
76 X: array
77 final value of degrees of freedom
78 """
80 X = X0
81 Fn = f(X)
83 if callback is None:
85 def callback(X):
86 pass
88 if residual is None:
90 def residual(F, X):
91 return np.linalg.norm(F, np.inf)
93 Rn = residual(Fn, X)
95 if apply_precon is None:
97 def apply_precon(F, X):
98 return F, residual(F, X)
100 Fp, Rp = apply_precon(Fn, X)
102 def log(*args):
103 if verbose >= 1:
104 print(*args)
106 def debug(*args):
107 if verbose >= 2:
108 print(*args)
110 if converged is None:
112 def converged(F, X):
113 return residual(F, X) <= fmax
115 if converged(Fn, X):
116 log('ODE12r terminates successfully after 0 iterations')
117 return X
118 if Rn >= maxtol:
119 raise OptimizerConvergenceError(
120 f'ODE12r: Residual {Rn} is too large at iteration 0'
121 )
123 # computation of the initial step
124 r = residual(Fp, X) # pick the biggest force
125 if h is None:
126 h = 0.5 * rtol**0.5 / r # Chose a stepsize based on that force
127 h = max(h, hmin) # Make sure the step size is not too big
129 for nit in range(1, steps + 1):
130 Xnew = X + h * Fp # Pick a new position
131 Fn_new = f(Xnew) # Calculate the new forces at this position
132 Rn_new = residual(Fn_new, Xnew)
133 Fp_new, Rp_new = apply_precon(Fn_new, Xnew)
135 e = 0.5 * h * (Fp_new - Fp) # Estimate the area under the forces curve
136 err = np.linalg.norm(e, np.inf) # Error estimate
138 # Accept step if residual decreases sufficiently and/or error acceptable
139 accept = (Rp_new <= Rp * (1 - C1 * h)) or (
140 (Rp_new <= Rp * C2) and err <= rtol
141 )
143 # Pick an extrapolation scheme for the system & find new increment
144 y = Fp - Fp_new
145 if extrapolate == 1: # F(xn + h Fp)
146 h_ls = h * (Fp @ y) / (y @ y)
147 elif extrapolate == 2: # F(Xn + h Fp)
148 h_ls = h * (Fp @ Fp_new) / (Fp @ y + 1e-10)
149 elif extrapolate == 3: # min | F(Xn + h Fp) |
150 h_ls = h * (Fp @ y) / (y @ y + 1e-10)
151 else:
152 raise ValueError(
153 f'invalid extrapolate value: {extrapolate}. Must be 1, 2 or 3'
154 )
155 if np.isnan(h_ls) or h_ls < hmin: # Rejects if increment is too small
156 h_ls = np.inf
158 h_err = h * 0.5 * np.sqrt(rtol / err)
160 # Accept the step and do the update
161 if accept:
162 X = Xnew
163 Rn = Rn_new
164 Fn = Fn_new
165 Fp = Fp_new
166 Rp = Rp_new
167 callback(X)
169 # We check the residuals again
170 if Rn >= maxtol:
171 raise OptimizerConvergenceError(
172 f'ODE12r: Residual {Rn} is too '
173 f'large at iteration number {nit}'
174 )
176 if converged(Fn, X):
177 log(f'ODE12r: terminates successfully after {nit} iterations.')
178 return X
180 # Compute a new step size.
181 # Based on the extrapolation and some other heuristics
182 h = max(
183 0.25 * h, min(4 * h, h_err, h_ls)
184 ) # Log steep-size analytic results
186 debug(f'ODE12r: accept: new h = {h}, |F| = {Rp}')
187 debug(f'ODE12r: hls = {h_ls}')
188 debug(f'ODE12r: herr = {h_err}')
189 else:
190 # Compute a new step size.
191 h = max(0.1 * h, min(0.25 * h, h_err, h_ls))
192 debug(f'ODE12r: reject: new h = {h}')
193 debug(f'ODE12r: |Fnew| = {Rp_new}')
194 debug(f'ODE12r: |Fold| = {Rp}')
195 debug(f'ODE12r: |Fnew|/|Fold| = {Rp_new / Rp}')
197 # abort if step size is too small
198 if abs(h) <= hmin:
199 raise OptimizerConvergenceError(
200 f'ODE12r terminates unsuccessfully Step size {h} too small'
201 )
204class ODE12r(SciPyOptimizer):
205 """
206 Optimizer based on adaptive ODE solver :func:`ode12r`
207 """
209 @deprecate_positionals(2)
210 def __init__(
211 self,
212 atoms: Atoms,
213 logfile: IO | str = '-',
214 trajectory: str | None = None,
215 callback_always: bool = False,
216 alpha: float = 1.0,
217 precon: str | None = None,
218 verbose: int = 0,
219 rtol: float = 1e-2,
220 **kwargs,
221 ):
222 super().__init__(
223 atoms,
224 logfile=logfile,
225 trajectory=trajectory,
226 callback_always=callback_always,
227 alpha=alpha,
228 **kwargs,
229 )
230 self._actual_atoms = atoms
231 from ase.optimize.precon.precon import make_precon # avoid circular dep
233 self.precon = make_precon(precon)
234 self.verbose = verbose
235 self.rtol = rtol
237 def apply_precon(self, Fn, X):
238 self.optimizable.set_x(X)
239 Fp = self.precon.apply(Fn, self._actual_atoms)
240 Rn = self.optimizable.gradient_norm(Fn)
241 return Fp, Rn
243 def call_fmin(self, fmax, steps):
244 ode12r(
245 lambda x: -self.fprime(x),
246 self.x0(),
247 fmax=fmax,
248 steps=steps,
249 verbose=self.verbose,
250 apply_precon=self.apply_precon,
251 callback=self.callback,
252 converged=lambda gradient, X: self.gradient_converged(gradient),
253 rtol=self.rtol,
254 )