Coverage for ase/optimize/fire.py: 93.10%
87 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 collections.abc import Callable
2from typing import IO, Any
4import numpy as np
6from ase import Atoms
7from ase.optimize.optimize import Optimizer
8from ase.utils import deprecate_positionals, deprecated
11def _forbid_maxmove(args: list, kwargs: dict[str, Any]) -> bool:
12 """Set maxstep with maxmove if not set."""
13 maxstep_index = 6
14 maxmove_index = 7
16 def _pop_arg(name: str) -> Any:
17 to_pop = None
18 if len(args) > maxmove_index:
19 to_pop = args[maxmove_index]
20 args[maxmove_index] = None
22 elif name in kwargs:
23 to_pop = kwargs[name]
24 del kwargs[name]
25 return to_pop
27 if len(args) > maxstep_index and args[maxstep_index] is None:
28 value = args[maxstep_index] = _pop_arg('maxmove')
29 elif kwargs.get('maxstep', None) is None:
30 value = kwargs['maxstep'] = _pop_arg('maxmove')
31 else:
32 return False
34 return value is not None
37class FIRE(Optimizer):
38 @deprecated(
39 'Use of `maxmove` is deprecated. Use `maxstep` instead.',
40 category=FutureWarning,
41 callback=_forbid_maxmove,
42 )
43 @deprecate_positionals(2)
44 def __init__(
45 self,
46 atoms: Atoms,
47 restart: str | None = None,
48 logfile: IO | str = '-',
49 trajectory: str | None = None,
50 dt: float = 0.1,
51 maxstep: float | None = None,
52 maxmove: float | None = None,
53 dtmax: float = 1.0,
54 Nmin: int = 5,
55 finc: float = 1.1,
56 fdec: float = 0.5,
57 astart: float = 0.1,
58 fa: float = 0.99,
59 a: float = 0.1,
60 downhill_check: bool = False,
61 position_reset_callback: Callable | None = None,
62 **kwargs,
63 ):
64 """
66 Parameters
67 ----------
68 atoms: :class:`~ase.Atoms`
69 The Atoms object to relax.
71 restart: str
72 JSON file used to store hessian matrix. If set, file with
73 such a name will be searched and hessian matrix stored will
74 be used, if the file exists.
76 logfile: file object or str
77 If *logfile* is a string, a file with that name will be opened.
78 Use '-' for stdout.
80 trajectory: str
81 Trajectory file used to store optimisation path.
83 dt: float
84 Initial time step. Defualt value is 0.1
86 maxstep: float
87 Used to set the maximum distance an atom can move per
88 iteration (default value is 0.2).
90 dtmax: float
91 Maximum time step. Default value is 1.0
93 Nmin: int
94 Number of steps to wait after the last time the dot product of
95 the velocity and force is negative (P in The FIRE article) before
96 increasing the time step. Default value is 5.
98 finc: float
99 Factor to increase the time step. Default value is 1.1
101 fdec: float
102 Factor to decrease the time step. Default value is 0.5
104 astart: float
105 Initial value of the parameter a. a is the Coefficient for
106 mixing the velocity and the force. Called alpha in the FIRE article.
107 Default value 0.1.
109 fa: float
110 Factor to decrease the parameter alpha. Default value is 0.99
112 a: float
113 Coefficient for mixing the velocity and the force. Called
114 alpha in the FIRE article. Default value 0.1.
116 downhill_check: bool
117 Downhill check directly compares potential energies of subsequent
118 steps of the FIRE algorithm rather than relying on the current
119 product v*f that is positive if the FIRE dynamics moves downhill.
120 This can detect numerical issues where at large time steps the step
121 is uphill in energy even though locally v*f is positive, i.e. the
122 algorithm jumps over a valley because of a too large time step.
124 position_reset_callback: function(atoms, r, e, e_last)
125 Function that takes current *atoms* object, an array of position
126 *r* that the optimizer will revert to, current energy *e* and
127 energy of last step *e_last*. This is only called if e > e_last.
129 kwargs : dict, optional
130 Extra arguments passed to
131 :class:`~ase.optimize.optimize.Optimizer`.
133 .. deprecated:: 3.19.3
134 Use of ``maxmove`` is deprecated; please use ``maxstep``.
136 Examples
137 --------
139 >>> from ase import Atoms
140 >>> from ase.optimize import FIRE
141 >>> from ase.calculators.emt import EMT
142 ...
143 >>> system = Atoms(
144 ... 'N2',
145 ... positions = [(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)],
146 ... calculator=EMT()
147 ... )
148 >>> dyn = FIRE(system, dtmax = 1.0, dt = 2.0)
149 >>> dyn.run(fmax=0.05) # doctest:+ELLIPSIS
150 Step Time Energy fmax
151 FIRE: 0 ... 0.440344 3.251800
152 FIRE: 1 ... 1.076992 10.112458
153 FIRE: 2 ... 0.440344 3.251800
154 FIRE: 3 ... 1.076992 10.112458
155 FIRE: 4 ... 0.440344 3.251800
156 FIRE: 5 ... 0.262779 0.013728
157 ...
158 """
159 super().__init__(atoms, restart, logfile, trajectory, **kwargs)
161 self.dt = dt
163 self.Nsteps = 0
165 if maxstep is not None:
166 self.maxstep = maxstep
167 else:
168 self.maxstep = self.defaults['maxstep']
170 self.dtmax = dtmax
171 self.Nmin = Nmin
172 self.finc = finc
173 self.fdec = fdec
174 self.astart = astart
175 self.fa = fa
176 self.a = a
177 self.downhill_check = downhill_check
178 self.position_reset_callback = position_reset_callback
180 def initialize(self):
181 self.vel = None
183 def read(self):
184 self.vel, self.dt = self.load()
186 def step(self, f=None):
187 gradient = -self._get_gradient(f)
188 # (XXX This is the negative gradient)
189 optimizable = self.optimizable
191 if self.vel is None:
192 self.vel = np.zeros(optimizable.ndofs())
193 if self.downhill_check:
194 self.e_last = optimizable.get_value()
195 self.r_last = optimizable.get_x()
196 self.vel_last = self.vel.copy()
197 else:
198 is_uphill = False
199 if self.downhill_check:
200 e = optimizable.get_value()
201 # Check if the energy actually decreased
202 if e > self.e_last:
203 # If not, reset to old positions...
204 if self.position_reset_callback is not None:
205 self.position_reset_callback(
206 optimizable, self.r_last, e, self.e_last
207 )
208 optimizable.set_x(self.r_last)
209 is_uphill = True
210 self.e_last = optimizable.get_value()
211 self.r_last = optimizable.get_x()
212 self.vel_last = self.vel.copy()
214 vf = np.vdot(gradient, self.vel)
215 grad2 = np.vdot(gradient, gradient)
216 if vf > 0.0 and not is_uphill:
217 self.vel = (
218 1.0 - self.a
219 ) * self.vel + self.a * gradient / np.sqrt(grad2) * np.sqrt(
220 np.vdot(self.vel, self.vel)
221 )
222 if self.Nsteps > self.Nmin:
223 self.dt = min(self.dt * self.finc, self.dtmax)
224 self.a *= self.fa
225 self.Nsteps += 1
226 else:
227 self.vel[:] *= 0.0
228 self.a = self.astart
229 self.dt *= self.fdec
230 self.Nsteps = 0
232 self.vel += self.dt * gradient
233 dr = self.dt * self.vel
234 normdr = np.sqrt(np.vdot(dr, dr))
235 if normdr > self.maxstep:
236 dr = self.maxstep * dr / normdr
237 r = optimizable.get_x()
238 optimizable.set_x(r + dr)
239 self.dump((self.vel, self.dt))