Coverage for ase/optimize/bfgs.py: 95.24%
84 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
1import warnings
2from pathlib import Path
3from typing import IO
5import numpy as np
7from ase import Atoms
8from ase._4.optimize.bfgs import BFGSMethod
9from ase.optimize.optimize import Optimizer, UnitCellFilter
10from ase.utils import deprecate_positionals
13class BFGS(Optimizer):
14 # default parameters
15 defaults = {**Optimizer.defaults, 'alpha': 70.0}
17 @deprecate_positionals(2)
18 def __init__(
19 self,
20 atoms: Atoms,
21 restart: str | Path | None = None,
22 logfile: IO | str | Path | None = '-',
23 trajectory: str | Path | None = None,
24 append_trajectory: bool = False,
25 maxstep: float | None = None,
26 alpha: float | None = None,
27 **kwargs,
28 ):
29 """BFGS optimizer.
31 Parameters
32 ----------
33 atoms: :class:`~ase.Atoms`
34 The Atoms object to relax.
36 restart: str | Path | None
37 JSON file used to store hessian matrix. If set, file with
38 such a name will be searched and hessian matrix stored will
39 be used, if the file exists.
41 trajectory: str or Path
42 Trajectory file used to store optimisation path.
44 logfile: file object, Path, or str
45 If *logfile* is a string, a file with that name will be opened.
46 Use '-' for stdout.
48 maxstep: float
49 Used to set the maximum distance an atom can move per
50 iteration (default value is 0.2 Å).
52 alpha: float
53 Initial guess for the Hessian (curvature of energy surface). A
54 conservative value of 70.0 is the default, but number of needed
55 steps to converge might be less if a lower value is used. However,
56 a lower value also means risk of instability.
58 kwargs : dict, optional
59 Extra arguments passed to
60 :class:`~ase.optimize.optimize.Optimizer`.
62 Examples
63 --------
64 The BFGS object is one of the minimizers in the ASE package. The below
65 script uses BFGS to optimize the structure of a water molecule,
66 starting with the experimental geometry:
68 >>> from ase import Atoms
69 >>> from ase.optimize import BFGS
70 >>> from ase.calculators.emt import EMT
71 >>> import numpy as np
72 >>> d = 0.9575
73 >>> t = np.pi / 180 * 104.51
74 >>> system = Atoms('H2O',
75 ... positions=[(d, 0, 0),
76 ... (d * np.cos(t), d * np.sin(t), 0),
77 ... (0, 0, 0)],
78 ... calculator=EMT())
79 >>> dyn = BFGS(system)
80 >>> dyn.run(fmax=0.05) # doctest:+ELLIPSIS, +NORMALIZE_WHITESPACE
81 Step Time Energy fmax
82 BFGS: 0 ... 2.769632 8.609090
83 BFGS: 1 ... 1.930507 1.641499
84 BFGS: 2 ... 1.884227 0.535354
85 BFGS: 3 ... 1.879314 0.049628
86 ...
88 The columns are the solver name, step number, clock time, potential
89 energy (eV), and maximum force (eV/Å).
90 """
91 if maxstep is None:
92 self.maxstep = self.defaults['maxstep']
93 else:
94 self.maxstep = maxstep
96 if self.maxstep > 1.0:
97 warnings.warn(
98 'You are using a *very* large value for '
99 'the maximum step size: %.1f Å' % self.maxstep
100 )
102 self.alpha = alpha
103 if self.alpha is None:
104 self.alpha = self.defaults['alpha']
106 self.state = None
108 super().__init__(
109 atoms=atoms,
110 restart=restart,
111 logfile=logfile,
112 trajectory=trajectory,
113 append_trajectory=append_trajectory,
114 **kwargs,
115 )
117 def initialize(self):
118 # initial hessian
119 self.H0 = np.eye(self.optimizable.ndofs()) * self.alpha
120 self.state = None
122 self.pos0 = None
123 self.forces0 = None
125 @property
126 def H(self):
127 return self.state.hessian
129 def read(self):
130 data = self.load()
131 H, self.pos0, self.forces0, self.maxstep = data[:4]
132 if len(data) == 5:
133 self.atoms.orig_cell = data[4]
134 else:
135 assert len(data) == 4
136 self.state = BFGSMethod(H)
138 def step(self, gradient=None):
139 gradient = self._get_gradient(gradient)
140 optimizable = self.optimizable
142 pos = optimizable.get_x()
143 dpos, steplengths = self.prepare_step(pos, gradient)
144 dpos = self.determine_step(dpos, steplengths)
145 optimizable.set_x(pos + dpos)
146 if isinstance(self.atoms, UnitCellFilter):
147 self.dump(
148 (
149 self.state.hessian,
150 self.pos0,
151 self.forces0,
152 self.maxstep,
153 self.atoms.orig_cell,
154 )
155 )
156 else:
157 self.dump(
158 (self.state.hessian, self.pos0, self.forces0, self.maxstep)
159 )
161 def prepare_step(self, pos, gradient):
162 pos = pos.ravel()
163 gradient = gradient.ravel()
164 self.update(pos, -gradient, self.pos0, self.forces0)
166 # XXX Here we are calling gradient_norm() on some positions.
167 # Should there be a general norm concept
168 self.pos0 = pos
169 self.forces0 = -gradient.copy()
170 dpos = self.state.compute_step(gradient)
171 steplengths = self.optimizable.gradient_norm(dpos)
172 return dpos, steplengths
174 def determine_step(self, dpos, steplengths):
175 """Determine step to take according to maxstep
177 Normalize all steps as the largest step. This way
178 we still move along the direction.
179 """
180 maxsteplength = np.max(steplengths)
181 if maxsteplength >= self.maxstep:
182 scale = self.maxstep / maxsteplength
183 # FUTURE: Log this properly
184 # msg = '\n** scale step by {:.3f} to be shorter than {}'.format(
185 # scale, self.maxstep
186 # )
187 # print(msg, flush=True)
189 dpos *= scale
190 return dpos
192 def update(self, pos, forces, pos0, forces0):
193 if self.state is None:
194 self.state = BFGSMethod(self.H0)
195 return
197 # We'll want to work with gradients in the future,
198 # but (awkwardly) this method gets 'forces' for backwards compatibility
199 self.state.update(pos, -forces, pos0, -forces0)
201 def _replay_trajectory(self, traj):
202 """Initialize Hessian from old trajectory."""
203 self.state = None
204 atoms = traj[0]
205 pos0 = atoms.get_positions().ravel()
206 forces0 = atoms.get_forces().ravel()
207 for atoms in traj:
208 pos = atoms.get_positions().ravel()
209 forces = atoms.get_forces().ravel()
210 self.update(pos, forces, pos0, forces0)
211 pos0 = pos
212 forces0 = forces
214 self.pos0 = pos0
215 self.forces0 = forces0
218class oldBFGS(BFGS):
219 def determine_step(self, dpos, steplengths):
220 """Old BFGS behaviour for scaling step lengths
222 This keeps the behaviour of truncating individual steps. Some might
223 depend of this as some absurd kind of stimulated annealing to find the
224 global minimum.
225 """
226 dpos /= np.maximum(steplengths / self.maxstep, 1.0).reshape(-1, 1)
227 return dpos