Coverage for ase/md/contour_exploration.py: 96.27%
161 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.optimize import Dynamics
9def subtract_projection(a, b):
10 """returns new vector that removes vector a's projection vector b. Is
11 also equivalent to the vector rejection."""
12 aout = a - np.vdot(a, b) / np.vdot(b, b) * b
13 return aout
16def normalize(a):
17 """Makes a unit vector out of a vector"""
18 return a / np.linalg.norm(a)
21class ContourExploration(Dynamics):
22 def __init__(
23 self,
24 atoms: Atoms,
25 maxstep: float = 0.5,
26 parallel_drift: float = 0.1,
27 energy_target: float | None = None,
28 angle_limit: float | None = 20.0,
29 potentiostat_step_scale: float | None = None,
30 remove_translation: bool = False,
31 use_frenet_serret: bool = True,
32 initialization_step_scale: float = 1e-2,
33 use_target_shift: bool = True,
34 target_shift_previous_steps: int = 10,
35 use_tangent_curvature: bool = False,
36 rng=np.random,
37 force_consistent: bool | None = None,
38 trajectory: str | None = None,
39 logfile: IO | str | None = None,
40 append_trajectory: bool = False,
41 loginterval: int = 1,
42 ):
43 """Contour Exploration object.
45 Parameters
46 ----------
47 atoms: :class:`~ase.Atoms`
48 The Atoms object to operate on. Atomic velocities are required for
49 the method. If the atoms object does not contain velocities,
50 random ones will be applied.
52 maxstep: float
53 Used to set the maximum distance an atom can move per
54 iteration (default value is 0.5 Å).
56 parallel_drift: float
57 The fraction of the update step that is parallel to the contour but
58 in a random direction. Used to break symmetries.
60 energy_target: float
61 The total system potential energy for that the potentiostat attepts
62 to maintain. (defaults the initial potential energy)
64 angle_limit: float or None
65 Limits the stepsize to a maximum change of direction angle using the
66 curvature. Gives a scale-free means of tuning the stepsize on the
67 fly. Typically less than 30 degrees gives reasonable results but
68 lower angle limits result in higher potentiostatic accuracy. Units
69 of degrees. (default 20°)
71 potentiostat_step_scale: float or None
72 Scales the size of the potentiostat step. The potentiostat step is
73 determined by linear extrapolation from the current potential energy
74 to the target_energy with the current forces. A
75 potentiostat_step_scale > 1.0 overcorrects and < 1.0
76 undercorrects. By default, a simple heuristic is used to selected
77 the valued based on the parallel_drift. (default None)
79 remove_translation: boolean
80 When True, the net momentum is removed at each step. Improves
81 potentiostatic accuracy slightly for bulk systems but should not be
82 used with constraints. (default False)
84 use_frenet_serret: Bool
85 Controls whether or not the Taylor expansion of the Frenet-Serret
86 formulas for curved path extrapolation are used. Required for using
87 angle_limit based step scalling. (default True)
89 initialization_step_scale: float
90 Controls the scale of the initial step as a multiple of maxstep.
91 (default 1e-2)
93 use_target_shift: boolean
94 Enables shifting of the potentiostat target to compensate for
95 systematic undercorrection or overcorrection by the potentiostat.
96 Uses the average of the *target_shift_previous_steps* to prevent
97 coupled occilations. (default True)
99 target_shift_previous_steps: int
100 The number of pevious steps to average when using use_target_shift.
101 (default 10)
103 use_tangent_curvature: boolean
104 Use the velocity unit tangent rather than the contour normals from
105 forces to compute the curvature. Usually not as accurate.
106 (default False)
108 rng: a random number generator
109 Lets users control the random number generator for the
110 parallel_drift vector. (default numpy.random)
112 force_consistent: boolean
113 (default None)
115 trajectory: Trajectory object or str (optional)
116 Attach trajectory object. If *trajectory* is a string a
117 Trajectory will be constructed. Default: None.
119 logfile: file object or str (optional)
120 If *logfile* is a string, a file with that name will be opened.
121 Use '-' for stdout. Default: None.
123 loginterval: int (optional)
124 Only write a log line for every *loginterval* time steps.
125 Default: 1
127 append_trajectory: boolean
128 Defaults to False, which causes the trajectory file to be
129 overwriten each time the dynamics is restarted from scratch.
130 If True, the new structures are appended to the trajectory
131 file instead.
133 Physical background and limitations
134 -----------------------------------
136 Contour Exploration evolves the system along constant potential energy
137 contours on the potential energy surface. The method uses
138 curvature-based extrapolation and a potentiostat to correct for
139 potential energy errors. It is similar to molecular dynamics but with a
140 potentiostat rather than a thermostat. Without changes in kinetic
141 energy, it is more useful to automatically scale step sizes to the
142 curvature of the potential energy contour via an ``angle_limit`` while
143 enforcing a ``maxstep`` to ensure potentiostatic accuracy. [1] To
144 escape loops on the potential energy surface or to break symmetries, a
145 random drift vector parallel to the contour can be applied as a
146 fraction of the step size via ``parallel_drift``. Contour exploration
147 cannot be used at minima since the contour is a single point.
149 References
150 ----------
151 [1] :doi:`M. J. Waters and J. M. Rondinelli, J. Phys.: Condens. Matter
152 33, 445901 (2021). <10.1088/1361-648X/ac1af0>`
154 Example
155 --------
156 Contour exploration at the current potential energy. The atoms are
157 displaced first, because the method cannot be used at a minimum:
159 >>> from ase.build import bulk
160 >>> from ase.calculators.emt import EMT
161 >>> from ase.md.contour_exploration import ContourExploration
162 >>> atoms = bulk('Cu', cubic=True)
163 >>> atoms.rattle(stdev=0.05, seed=42)
164 >>> atoms.calc = EMT()
165 >>> dyn = ContourExploration(atoms)
166 >>> dyn.run(10)
167 False
168 """
170 if potentiostat_step_scale is None:
171 # a heuristic guess since most systems will overshoot when there is
172 # drift
173 self.potentiostat_step_scale = 1.1 + 0.6 * parallel_drift
174 else:
175 self.potentiostat_step_scale = potentiostat_step_scale
177 self.rng = rng
178 self.remove_translation = remove_translation
179 self.use_frenet_serret = use_frenet_serret
180 self.use_tangent_curvature = use_tangent_curvature
181 self.initialization_step_scale = initialization_step_scale
182 self.maxstep = maxstep
183 self.angle_limit = angle_limit
184 self.parallel_drift = parallel_drift
185 self.use_target_shift = use_target_shift
187 # These will be populated once self.step() is called, but could be set
188 # after instantiating with ce = ContourExploration(...) like so:
189 # ce.Nold = Nold
190 # ce.r_old = atoms_old.get_positions()
191 # ce.Told = Told
192 # to resume a previous contour trajectory.
194 self.T = None
195 self.Told = None
196 self.N = None
197 self.Nold = None
198 self.r_old = None
199 self.r = None
201 if energy_target is None:
202 self.energy_target = atoms.get_potential_energy(
203 force_consistent=True
204 )
205 else:
206 self.energy_target = energy_target
208 # Initizing the previous steps at the target energy slows
209 # target_shifting untill the system has had
210 # 'target_shift_previous_steps' steps to equilibrate and should prevent
211 # occilations. These need to be initialized before the initialize_old
212 # step to prevent a crash
213 self.previous_energies = np.full(
214 target_shift_previous_steps, self.energy_target
215 )
217 # these first two are purely for logging,
218 # auto scaling will still occur
219 # and curvature will still be found if use_frenet_serret == True
220 self.step_size = 0.0
221 self.curvature = 0
223 # loginterval exists for the MolecularDynamics class but not for
224 # the more general Dynamics class
225 Dynamics.__init__(
226 self,
227 atoms,
228 logfile,
229 trajectory, # loginterval,
230 append_trajectory=append_trajectory,
231 )
233 self._actual_atoms = atoms
235 # we need velocities or NaNs will be produced,
236 # if none are provided we make random ones
237 velocities = self._actual_atoms.get_velocities()
238 if np.linalg.norm(velocities) < 1e-6:
239 # we have to pass dimension since atoms are not yet stored
240 atoms.set_velocities(self.rand_vect())
242 # Required stuff for Dynamics
243 def todict(self):
244 return {
245 'type': 'contour-exploration',
246 'dyn-type': self.__class__.__name__,
247 'stepsize': self.step_size,
248 }
250 def run(self, steps=50):
251 """Call Dynamics.run and adjust max_steps"""
252 return Dynamics.run(self, steps=steps)
254 def log(self, gradient):
255 if self.logfile is not None:
256 # name = self.__class__.__name__
257 if self.nsteps == 0:
258 args = (
259 'Step',
260 'Energy_Target',
261 'Energy',
262 'Curvature',
263 'Step_Size',
264 'Energy_Deviation_per_atom',
265 )
266 msg = '# %4s %15s %15s %12s %12s %15s\n' % args
267 self.logfile.write(msg)
268 e = self._actual_atoms.get_potential_energy(force_consistent=True)
269 dev_per_atom = (e - self.energy_target) / len(self._actual_atoms)
270 args = (
271 self.nsteps,
272 self.energy_target,
273 e,
274 self.curvature,
275 self.step_size,
276 dev_per_atom,
277 )
278 msg = '%6d %15.6f %15.6f %12.6f %12.6f %24.9f\n' % args
279 self.logfile.write(msg)
281 def rand_vect(self):
282 """Returns a random (Natoms,3) vector"""
283 vect = self.rng.normal(size=(len(self._actual_atoms), 3))
284 return vect
286 def create_drift_unit_vector(self, N, T):
287 """Creates a random drift unit vector with no projection on N or T and
288 with out a net translation so systems don't wander"""
289 drift = self.rand_vect()
290 drift = subtract_projection(drift, N)
291 drift = subtract_projection(drift, T)
292 # removes net translation, so systems don't wander
293 drift = drift - drift.sum(axis=0) / len(self._actual_atoms)
294 D = normalize(drift)
295 return D
297 def compute_step_contributions(self, potentiostat_step_size):
298 """Computes the orthogonal component sizes of the step so that the net
299 step obeys the smaller of step_size or maxstep."""
300 if abs(potentiostat_step_size) < self.step_size:
301 delta_s_perpendicular = potentiostat_step_size
302 contour_step_size = np.sqrt(
303 self.step_size**2 - potentiostat_step_size**2
304 )
305 delta_s_parallel = (
306 np.sqrt(1 - self.parallel_drift**2) * contour_step_size
307 )
308 delta_s_drift = contour_step_size * self.parallel_drift
310 else:
311 # in this case all priority goes to potentiostat terms
312 delta_s_parallel = 0.0
313 delta_s_drift = 0.0
314 delta_s_perpendicular = (
315 np.sign(potentiostat_step_size) * self.step_size
316 )
318 return delta_s_perpendicular, delta_s_parallel, delta_s_drift
320 def _compute_update_without_fs(self, potentiostat_step_size, scale=1.0):
321 """Only uses the forces to compute an orthogonal update vector"""
323 # Without the use of curvature there is no way to estimate the
324 # limiting step size
325 self.step_size = self.maxstep * scale
327 delta_s_perpendicular, delta_s_parallel, delta_s_drift = (
328 self.compute_step_contributions(potentiostat_step_size)
329 )
331 dr_perpendicular = self.N * delta_s_perpendicular
332 dr_parallel = delta_s_parallel * self.T
334 D = self.create_drift_unit_vector(self.N, self.T)
335 dr_drift = D * delta_s_drift
337 dr = dr_parallel + dr_drift + dr_perpendicular
338 dr = self.step_size * normalize(dr)
339 return dr
341 def _compute_update_with_fs(self, potentiostat_step_size):
342 """Uses the Frenet–Serret formulas to perform curvature based
343 extrapolation to compute the update vector"""
344 # this should keep the dr clear of the constraints
345 # by using the actual change, not a velocity vector
346 delta_r = self.r - self.rold
347 delta_s = np.linalg.norm(delta_r)
348 # approximation of delta_s we use this incase an adaptive step_size
349 # algo get used
351 delta_T = self.T - self.Told
352 delta_N = self.N - self.Nold
353 dTds = delta_T / delta_s
354 dNds = delta_N / delta_s
355 if self.use_tangent_curvature:
356 curvature = np.linalg.norm(dTds)
357 # on a perfect trajectory, the normal can be computed this way,
358 # But the normal should always be tied to forces
359 # N = dTds / curvature
360 else:
361 # normals are better since they are fixed to the reality of
362 # forces. I see smaller forces and energy errors in bulk systems
363 # using the normals for curvature
364 curvature = np.linalg.norm(dNds)
365 self.curvature = curvature
367 if self.angle_limit is not None:
368 phi = np.pi / 180 * self.angle_limit
369 self.step_size = np.sqrt(2 - 2 * np.cos(phi)) / curvature
370 self.step_size = min(self.step_size, self.maxstep)
372 # now we can compute a safe step
373 delta_s_perpendicular, delta_s_parallel, delta_s_drift = (
374 self.compute_step_contributions(potentiostat_step_size)
375 )
377 N_guess = self.N + dNds * delta_s_parallel
378 T_guess = self.T + dTds * delta_s_parallel
379 # the extrapolation is good at keeping N_guess and T_guess
380 # orthogonal but not normalized:
381 N_guess = normalize(N_guess)
382 T_guess = normalize(T_guess)
384 dr_perpendicular = delta_s_perpendicular * (N_guess)
386 dr_parallel = (
387 delta_s_parallel
388 * self.T
389 * (1 - (delta_s_parallel * curvature) ** 2 / 6.0)
390 + self.N * (curvature / 2.0) * delta_s_parallel**2
391 )
393 D = self.create_drift_unit_vector(N_guess, T_guess)
394 dr_drift = D * delta_s_drift
396 # combine the components
397 dr = dr_perpendicular + dr_parallel + dr_drift
398 dr = self.step_size * normalize(dr)
399 # because we guess our orthonormalization directions,
400 # we renormalize to ensure a correct step size
401 return dr
403 def update_previous_energies(self, energy):
404 """Updates the energy history in self.previous_energies to include the
405 current energy."""
406 # np.roll shifts the values to keep nice sequential ordering.
407 self.previous_energies = np.roll(self.previous_energies, 1)
408 self.previous_energies[0] = energy
410 def compute_potentiostat_step_size(self, forces, energy):
411 """Computes the potentiostat step size by linear extrapolation of the
412 potential energy using the forces. The step size can be positive or
413 negative depending on whether or not the energy is too high or too low.
414 """
415 if self.use_target_shift:
416 target_shift = self.energy_target - np.mean(self.previous_energies)
417 else:
418 target_shift = 0.0
420 # deltaU is the potential error that will be corrected for
421 deltaU = energy - (self.energy_target + target_shift)
423 f_norm = np.linalg.norm(forces)
424 # can be positive or negative
425 potentiostat_step_size = (
426 deltaU / f_norm
427 ) * self.potentiostat_step_scale
428 return potentiostat_step_size
430 def step(self, f=None):
431 atoms = self._actual_atoms
432 if f is None:
433 f = atoms.get_forces()
435 # get the velocity vector and old kinetic energy for momentum rescaling
436 velocities = atoms.get_velocities()
437 KEold = atoms.get_kinetic_energy()
439 energy = atoms.get_potential_energy(force_consistent=True)
440 self.update_previous_energies(energy)
441 potentiostat_step_size = self.compute_potentiostat_step_size(f, energy)
443 self.N = normalize(f)
444 self.r = atoms.get_positions()
445 # remove velocity projection on forces
446 v_parallel = subtract_projection(velocities, self.N)
447 self.T = normalize(v_parallel)
449 if self.use_frenet_serret:
450 if self.Nold is not None and self.Told is not None:
451 dr = self._compute_update_with_fs(potentiostat_step_size)
452 else:
453 # we must have the old positions and vectors for an FS step
454 # if we don't, we can only do a small step
455 dr = self._compute_update_without_fs(
456 potentiostat_step_size, scale=self.initialization_step_scale
457 )
458 else: # of course we can run less accuratly without FS.
459 dr = self._compute_update_without_fs(potentiostat_step_size)
461 # now that dr is done, we check if there is translation
462 if self.remove_translation:
463 net_motion = dr.sum(axis=0) / len(atoms)
464 # print(net_motion)
465 dr = dr - net_motion
466 dr_unit = dr / np.linalg.norm(dr)
467 dr = dr_unit * self.step_size
469 # save old positions before update
470 self.Nold = self.N
471 self.rold = self.r
472 self.Told = self.T
474 # if we have constraints then this will do the first part of the
475 # RATTLE algorithm:
476 # If we can avoid using momenta, this will be simpler.
477 masses = atoms.get_masses()[:, np.newaxis]
478 atoms.set_positions(self.r + dr)
479 new_momenta = (atoms.get_positions() - self.r) * masses # / self.dt
481 # We need to store the momenta on the atoms before calculating
482 # the forces, as in a parallel Asap calculation atoms may
483 # migrate during force calculations, and the momenta need to
484 # migrate along with the atoms.
485 atoms.set_momenta(new_momenta, apply_constraint=False)
487 # Now we get the new forces!
488 f = atoms.get_forces(md=True)
490 # I don't really know if removing md=True from above will break
491 # compatibility with RATTLE, leaving it alone for now.
492 f_constrained = atoms.get_forces()
493 # but this projection needs the forces to be consistent with the
494 # constraints. We have to set the new velocities perpendicular so they
495 # get logged properly in the trajectory files.
496 vnew = subtract_projection(atoms.get_velocities(), f_constrained)
497 # using the md = True forces like this:
498 # vnew = subtract_projection(atoms.get_velocities(), f)
499 # will not work with constraints
500 atoms.set_velocities(vnew)
502 # rescaling momentum to maintain constant kinetic energy.
503 KEnew = atoms.get_kinetic_energy()
504 Ms = np.sqrt(KEold / KEnew) # Ms = Momentum_scale
505 atoms.set_momenta(Ms * atoms.get_momenta())
507 # Normally this would be the second part of RATTLE
508 # will be done here like this:
509 # atoms.set_momenta(atoms.get_momenta() + 0.5 * self.dt * f)
510 return f