Coverage for ase/optimize/fire2.py: 96.15%
78 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
1# ######################################
2# Implementation of FIRE2.0 and ABC-FIRE
4# The FIRE2.0 algorithm is implemented using the integrator euler semi implicit
5# as described in the paper:
6# J. Guénolé, W.G. Nöhring, A. Vaid, F. Houllé, Z. Xie, A. Prakash,
7# E. Bitzek,
8# Assessment and optimization of the fast inertial relaxation engine (fire)
9# for energy minimization in atomistic simulations and its
10# implementation in lammps,
11# Comput. Mater. Sci. 175 (2020) 109584.
12# https://doi.org/10.1016/j.commatsci.2020.109584.
13# This implementation does not include N(p<0), initialdelay
14#
15# ABC-Fire is implemented as described in the paper:
16# S. Echeverri Restrepo, P. Andric,
17# ABC-FIRE: Accelerated Bias-Corrected Fast Inertial Relaxation Engine,
18# Comput. Mater. Sci. 218 (2023) 111978.
19# https://doi.org/10.1016/j.commatsci.2022.111978.
20#######################################
22from collections.abc import Callable
23from typing import IO
25import numpy as np
27from ase import Atoms
28from ase.optimize.optimize import Optimizer
29from ase.utils import deprecate_positionals
32class FIRE2(Optimizer):
33 @deprecate_positionals(2)
34 def __init__(
35 self,
36 atoms: Atoms,
37 restart: str | None = None,
38 logfile: IO | str = '-',
39 trajectory: str | None = None,
40 dt: float = 0.1,
41 maxstep: float = 0.2,
42 dtmax: float = 1.0,
43 dtmin: float = 2e-3,
44 Nmin: int = 20,
45 finc: float = 1.1,
46 fdec: float = 0.5,
47 astart: float = 0.25,
48 fa: float = 0.99,
49 position_reset_callback: Callable | None = None,
50 use_abc: bool | None = False,
51 **kwargs,
52 ):
53 """
55 Parameters
56 ----------
57 atoms: :class:`~ase.Atoms`
58 The Atoms object to relax.
60 restart: str
61 JSON file used to store hessian matrix. If set, file with
62 such a name will be searched and hessian matrix stored will
63 be used, if the file exists.
65 logfile: file object or str
66 If *logfile* is a string, a file with that name will be opened.
67 Use '-' for stdout.
69 trajectory: str
70 Trajectory file used to store optimisation path.
72 dt: float
73 Initial time step. Defualt value is 0.1
75 maxstep: float
76 Used to set the maximum distance an atom can move per
77 iteration (default value is 0.2). Note that for ABC-FIRE the
78 check is done independently for each cartesian direction.
80 dtmax: float
81 Maximum time step. Default value is 1.0
83 dtmin: float
84 Minimum time step. Default value is 2e-3
86 Nmin: int
87 Number of steps to wait after the last time the dot product of
88 the velocity and force is negative (P in The FIRE article) before
89 increasing the time step. Default value is 20.
91 finc: float
92 Factor to increase the time step. Default value is 1.1
94 fdec: float
95 Factor to decrease the time step. Default value is 0.5
97 astart: float
98 Initial value of the parameter a. a is the Coefficient for
99 mixing the velocity and the force. Called alpha in the FIRE article.
100 Default value 0.25.
102 fa: float
103 Factor to decrease the parameter alpha. Default value is 0.99
105 position_reset_callback: function(atoms, r, e, e_last)
106 Function that takes current *atoms* object, an array of position
107 *r* that the optimizer will revert to, current energy *e* and
108 energy of last step *e_last*. This is only called if e > e_last.
110 use_abc: bool
111 If True, the Accelerated Bias-Corrected FIRE algorithm is
112 used (ABC-FIRE).
113 Default value is False.
115 kwargs : dict, optional
116 Extra arguments passed to
117 :class:`~ase.optimize.optimize.Optimizer`.
119 Examples
120 --------
122 >>> from ase import Atoms
123 >>> from ase.optimize import FIRE2
124 >>> from ase.calculators.emt import EMT
125 ...
126 >>> system = Atoms(
127 ... 'N2',
128 ... positions = [(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)],
129 ... calculator=EMT()
130 ... )
131 >>> fire_parameters = {
132 ... 'dt': 0.5,
133 ... 'maxstep': 0.2,
134 ... 'dtmax': 1.0,
135 ... 'Nmin': 20,
136 ... 'finc': 1.1,
137 ... 'fdec': 0.5,
138 ... 'astart': 0.25,
139 ... 'fa': 0.99,
140 ... }
141 >>> dyn = FIRE2(system, use_abc=True, **fire_parameters)
142 >>> dyn.run(fmax=0.05) # doctest:+ELLIPSIS
143 Step Time Energy fmax
144 FIRE2: 0 ... 0.440344 3.251800
145 FIRE2: 1 ... 2.859671 21.028202
146 FIRE2: 2 ... 0.875141 5.281651
147 FIRE2: 3 ... 2.859671 21.028202
148 FIRE2: 4 ... 0.668117 4.546505
149 FIRE2: 5 ... 0.311649 1.823901
150 FIRE2: 6 ... 0.262793 0.035743
151 ...
152 """
153 super().__init__(atoms, restart, logfile, trajectory, **kwargs)
155 self.dt = dt
157 self.Nsteps = 0
159 if maxstep is not None:
160 self.maxstep = maxstep
161 else:
162 self.maxstep = self.defaults['maxstep']
164 self.dtmax = dtmax
165 self.dtmin = dtmin
166 self.Nmin = Nmin
167 self.finc = finc
168 self.fdec = fdec
169 self.astart = astart
170 self.fa = fa
171 self.a = astart
172 self.position_reset_callback = position_reset_callback
173 self.use_abc = use_abc
175 def initialize(self):
176 self.v = None
178 def read(self):
179 self.v, self.dt = self.load()
181 def step(self, f=None):
182 gradient = -self._get_gradient(f)
183 optimizable = self.optimizable
185 if self.v is None:
186 self.v = np.zeros(optimizable.ndofs())
187 else:
188 vf = np.vdot(gradient, self.v)
189 if vf > 0.0:
190 self.Nsteps += 1
191 if self.Nsteps > self.Nmin:
192 self.dt = min(self.dt * self.finc, self.dtmax)
193 self.a *= self.fa
194 else:
195 self.Nsteps = 0
196 self.dt = max(self.dt * self.fdec, self.dtmin)
197 self.a = self.astart
199 dr = -0.5 * self.dt * self.v
200 r = optimizable.get_x()
201 optimizable.set_x(r + dr)
202 self.v[:] *= 0.0
204 # euler semi implicit
205 gradient = -optimizable.get_gradient()
206 self.v += self.dt * gradient
208 if self.use_abc:
209 self.a = max(self.a, 1e-10)
210 abc_multiplier = 1.0 / (1.0 - (1.0 - self.a) ** (self.Nsteps + 1))
211 v_mix = (1.0 - self.a) * self.v + self.a * gradient / np.sqrt(
212 np.vdot(gradient, gradient)
213 ) * np.sqrt(np.vdot(self.v, self.v))
214 self.v = abc_multiplier * v_mix
216 def clip_velocity(vel):
217 max_velocity = self.maxstep / self.dt
218 return vel.clip(-max_velocity, max_velocity)
220 def old_clip_velocity(v):
221 # Original implementation of clip_velocity(), can we remove?
222 # Let's remove it in 2026 unless assertion crashes etc.
223 v = v.reshape(-1, 3)
224 v_tmp = []
225 for car_dir in range(3):
226 v_i = np.where(
227 np.abs(v[:, car_dir]) * self.dt > self.maxstep,
228 (self.maxstep / self.dt)
229 * (v[:, car_dir] / np.abs(v[:, car_dir])),
230 v[:, car_dir],
231 )
232 v_tmp.append(v_i)
233 return np.array(v_tmp).T.ravel()
235 # Verifying if the maximum distance an atom
236 # moved is larger than maxstep, for ABC-FIRE the check
237 # is done independently for each cartesian direction
238 #
239 # Make sure old and new clip_velocity() agree:
240 v1 = clip_velocity(self.v)
241 if np.all(self.v) and len(self.v) % 3 == 0:
242 v2 = old_clip_velocity(self.v)
243 assert abs(v1 - v2).max() < 1e-12
244 self.v = v1
245 else:
246 self.v = (1.0 - self.a) * self.v + self.a * gradient / np.sqrt(
247 np.vdot(gradient, gradient)
248 ) * np.sqrt(np.vdot(self.v, self.v))
250 dr = self.dt * self.v
252 # Verifying if the maximum distance an atom moved
253 # step is larger than maxstep, for FIRE2.
254 if not self.use_abc:
255 normdr = np.sqrt(np.vdot(dr, dr))
256 if normdr > self.maxstep:
257 dr = self.maxstep * dr / normdr
259 r = optimizable.get_x()
260 optimizable.set_x(r + dr)
262 self.dump((self.v, self.dt))