Coverage for ase/mep/neb.py: 85.58%
624 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 sys
2import time
3import warnings
4from abc import ABC, abstractmethod
5from functools import cached_property
6from threading import Thread
8import numpy as np
9import numpy.typing as npt
10from scipy.integrate import cumulative_trapezoid
11from scipy.interpolate import CubicSpline
13import ase.parallel
14from ase.build import minimize_rotation_and_translation
15from ase.calculators.calculator import Calculator, all_properties, compare_atoms
16from ase.calculators.singlepoint import SinglePointCalculator
17from ase.geometry import find_mic
18from ase.optimize import MDMin
19from ase.optimize.ode import ode12r
20from ase.optimize.optimize import DEFAULT_MAX_STEPS, Optimizer
21from ase.optimize.precon import Precon, PreconImages
22from ase.optimize.sciopt import OptimizerConvergenceError
23from ase.utils import deprecated
24from ase.utils.abc import Optimizable
25from ase.utils.forcecurve import fit_images
28class Spring:
29 def __init__(self, atoms1, atoms2, energy1, energy2, k):
30 self.atoms1 = atoms1
31 self.atoms2 = atoms2
32 self.energy1 = energy1
33 self.energy2 = energy2
34 self.k = k
36 def _find_mic(self):
37 pos1 = self.atoms1.get_positions()
38 pos2 = self.atoms2.get_positions()
39 # XXX If we want variable cells we will need to edit this.
40 mic, _ = find_mic(pos2 - pos1, self.atoms1.cell, self.atoms1.pbc)
41 return mic
43 @cached_property
44 def t(self):
45 return self._find_mic()
47 @cached_property
48 def nt(self):
49 return np.linalg.norm(self.t)
52class NEBState:
53 def __init__(self, neb, images, energies):
54 self.neb = neb
55 self.images = images
56 self.energies = energies
58 def spring(self, i):
59 return Spring(
60 self.images[i],
61 self.images[i + 1],
62 self.energies[i],
63 self.energies[i + 1],
64 self.neb.k[i],
65 )
67 @cached_property
68 def imax(self):
69 return 1 + np.argsort(self.energies[1:-1])[-1]
71 @property
72 def emax(self):
73 return self.energies[self.imax]
75 @cached_property
76 def eqlength(self):
77 images = self.images
78 beeline = (
79 images[self.neb.nimages - 1].get_positions()
80 - images[0].get_positions()
81 )
82 beelinelength = np.linalg.norm(beeline)
83 return beelinelength / (self.neb.nimages - 1)
85 @cached_property
86 def nimages(self):
87 return len(self.images)
89 @property
90 def precon(self):
91 return self.neb.precon
94class NEBMethod(ABC):
95 def __init__(self, neb):
96 self.neb = neb
98 @abstractmethod
99 def get_tangent(self, state, spring1, spring2, i): ...
101 @abstractmethod
102 def add_image_force(
103 self, state, tangential_force, tangent, imgforce, spring1, spring2, i
104 ): ...
106 def adjust_positions(self, positions):
107 return positions
110class ImprovedTangentMethod(NEBMethod):
111 """
112 Tangent estimates are improved according to Eqs. 8-11 in paper I.
113 Tangents are weighted at extrema to ensure smooth transitions between
114 the positive and negative tangents.
115 """
117 def get_tangent(self, state, spring1, spring2, i):
118 energies = state.energies
119 if energies[i + 1] > energies[i] > energies[i - 1]:
120 tangent = spring2.t.copy()
121 elif energies[i + 1] < energies[i] < energies[i - 1]:
122 tangent = spring1.t.copy()
123 else:
124 deltavmax = max(
125 abs(energies[i + 1] - energies[i]),
126 abs(energies[i - 1] - energies[i]),
127 )
128 deltavmin = min(
129 abs(energies[i + 1] - energies[i]),
130 abs(energies[i - 1] - energies[i]),
131 )
132 if energies[i + 1] > energies[i - 1]:
133 tangent = spring2.t * deltavmax + spring1.t * deltavmin
134 else:
135 tangent = spring2.t * deltavmin + spring1.t * deltavmax
136 # Normalize the tangent vector
137 norm = np.linalg.norm(tangent)
138 tangent /= norm if norm > 0 else 1.0
139 return tangent
141 def add_image_force(
142 self, state, tangential_force, tangent, imgforce, spring1, spring2, i
143 ):
144 imgforce -= tangential_force * tangent
145 # Improved parallel spring force (formula 12 of paper I)
146 imgforce += (spring2.nt * spring2.k - spring1.nt * spring1.k) * tangent
149class ASENEBMethod(NEBMethod):
150 """
151 Standard NEB implementation in ASE. The tangent of each image is
152 estimated from the spring closest to the saddle point in each
153 spring pair.
154 """
156 def get_tangent(self, state, spring1, spring2, i):
157 imax = self.neb.imax
158 if i < imax:
159 tangent = spring2.t
160 elif i > imax:
161 tangent = spring1.t
162 else:
163 tangent = spring1.t + spring2.t
164 return tangent
166 def add_image_force(
167 self, state, tangential_force, tangent, imgforce, spring1, spring2, i
168 ):
169 # Magnitude for normalizing. Ensure it is not 0
170 tangent_mag = np.vdot(tangent, tangent) or 1
171 factor = tangent / tangent_mag
172 imgforce -= tangential_force * factor
173 imgforce -= (
174 np.vdot(spring1.t * spring1.k - spring2.t * spring2.k, tangent)
175 * factor
176 )
179class FullSpringMethod(NEBMethod):
180 """
181 Elastic band method. The full spring force is included.
182 """
184 def get_tangent(self, state, spring1, spring2, i):
185 # Tangents are bisections of spring-directions
186 # (formula C8 of paper III)
187 tangent = spring1.t / spring1.nt + spring2.t / spring2.nt
188 tangent /= np.linalg.norm(tangent)
189 return tangent
191 def add_image_force(
192 self, state, tangential_force, tangent, imgforce, spring1, spring2, i
193 ):
194 imgforce -= tangential_force * tangent
195 energies = state.energies
196 # Spring forces
197 # Eqs. C1, C5, C6 and C7 in paper III)
198 f1 = -(spring1.nt - state.eqlength) * spring1.t / spring1.nt * spring1.k
199 f2 = (spring2.nt - state.eqlength) * spring2.t / spring2.nt * spring2.k
200 if self.neb.climb and abs(i - self.neb.imax) == 1:
201 deltavmax = max(
202 abs(energies[i + 1] - energies[i]),
203 abs(energies[i - 1] - energies[i]),
204 )
205 deltavmin = min(
206 abs(energies[i + 1] - energies[i]),
207 abs(energies[i - 1] - energies[i]),
208 )
209 imgforce += (f1 + f2) * deltavmin / deltavmax
210 else:
211 imgforce += f1 + f2
214class BaseSplineMethod(NEBMethod):
215 """
216 Base class for SplineNEB and String methods
218 Can optionally be preconditioned, as described in the following article:
220 S. Makri, C. Ortner and J. R. Kermode, J. Chem. Phys.
221 150, 094109 (2019)
222 https://dx.doi.org/10.1063/1.5064465
223 """
225 def __init__(self, neb):
226 NEBMethod.__init__(self, neb)
228 def get_tangent(self, state, spring1, spring2, i):
229 return state.precon.get_tangent(i)
231 def add_image_force(
232 self, state, tangential_force, tangent, imgforce, spring1, spring2, i
233 ):
234 # project out tangential component (Eqs 6 and 7 in Paper IV)
235 imgforce -= tangential_force * tangent
238class SplineMethod(BaseSplineMethod):
239 """
240 NEB using spline interpolation, plus optional preconditioning
241 """
243 def add_image_force(
244 self, state, tangential_force, tangent, imgforce, spring1, spring2, i
245 ):
246 super().add_image_force(
247 state, tangential_force, tangent, imgforce, spring1, spring2, i
248 )
249 eta = state.precon.get_spring_force(i, spring1.k, spring2.k, tangent)
250 imgforce += eta
253class StringMethod(BaseSplineMethod):
254 """
255 String method using spline interpolation, plus optional preconditioning
256 """
258 def adjust_positions(self, positions):
259 # fit cubic spline to positions, reinterpolate to equispace images
260 # note this uses the preconditioned distance metric.
261 fit = self.neb.spline_fit(positions)
262 new_s = np.linspace(0.0, 1.0, self.neb.nimages)
263 new_positions = fit.x(new_s[1:-1]).reshape(-1, 3)
264 return new_positions
267def get_neb_method(neb, method):
268 if method == 'eb':
269 return FullSpringMethod(neb)
270 elif method == 'aseneb':
271 return ASENEBMethod(neb)
272 elif method == 'improvedtangent':
273 return ImprovedTangentMethod(neb)
274 elif method == 'spline':
275 return SplineMethod(neb)
276 elif method == 'string':
277 return StringMethod(neb)
278 else:
279 raise ValueError(f'Bad method: {method}')
282class NEBOptimizable(Optimizable):
283 def __init__(self, neb):
284 self.neb = neb
286 def get_gradient(self):
287 return -self.neb.get_forces().ravel()
289 def get_value(self):
290 return self.neb.get_potential_energy()
292 def get_x(self):
293 return self.neb.get_positions().ravel()
295 def set_x(self, x):
296 self.neb.set_positions(x.reshape(-1, 3))
298 def ndofs(self):
299 return 3 * len(self.neb)
301 def iterimages(self):
302 return self.neb.iterimages()
305class NEB:
306 def __init__(
307 self,
308 images: list[ase.Atoms],
309 k: float | list[float] = 0.1,
310 climb: bool = False,
311 parallel: bool = False,
312 remove_rotation_and_translation: bool = False,
313 world=None,
314 method: str | None = None,
315 allow_shared_calculator: bool = False,
316 precon: str | None = None,
317 ):
318 """Nudged elastic band.
320 Paper I:
322 G. Henkelman and H. Jonsson, Chem. Phys, 113, 9978 (2000).
323 :doi:`10.1063/1.1323224`
325 Paper II:
327 G. Henkelman, B. P. Uberuaga, and H. Jonsson, Chem. Phys,
328 113, 9901 (2000).
329 :doi:`10.1063/1.1329672`
331 Paper III:
333 E. L. Kolsbjerg, M. N. Groves, and B. Hammer, J. Chem. Phys,
334 145, 094107 (2016)
335 :doi:`10.1063/1.4961868`
337 Paper IV:
339 S. Makri, C. Ortner and J. R. Kermode, J. Chem. Phys.
340 150, 094109 (2019)
341 https://dx.doi.org/10.1063/1.5064465
343 Parameters
344 ----------
345 images: list of Atoms objects
346 Images defining path from initial to final state.
347 k: float or list of floats
348 Spring constant(s) in eV/Ang. One number or one for each spring.
349 climb: bool
350 Use a climbing image (default is no climbing image).
351 parallel: bool
352 Distribute images over processors.
353 remove_rotation_and_translation: bool
354 TRUE actives NEB-TR for removing translation and
355 rotation during NEB. By default applied non-periodic
356 systems
357 method: string of method
358 Choice betweeen five methods:
360 * aseneb: legacy ase NEB implementation
361 * improvedtangent: Paper I NEB implementation (default)
362 * eb: Paper III full spring force implementation
363 * spline: Paper IV spline interpolation (supports precon)
364 * string: Paper IV string method (supports precon)
366 Defaults to 'improvedtangent' (with a warning if not specified).
368 .. versionchanged:: 3.27.1
369 The default changes from ``aseneb`` to ``improvedtangent``.
371 allow_shared_calculator: bool
372 Allow images to share the same calculator between them.
373 Incompatible with parallelisation over images.
374 precon: string, :class:`ase.optimize.precon.Precon` instance or list of
375 instances. If present, enable preconditioing as in Paper IV. This is
376 possible using the 'spline' or 'string' methods only.
377 Default is no preconditioning (precon=None), which is converted to
378 a list of :class:`ase.precon.precon.IdentityPrecon` instances.
379 """
381 self.images = images
382 self.climb = climb
383 self.parallel = parallel
384 self.allow_shared_calculator = allow_shared_calculator
386 for img in images:
387 if len(img) != self.natoms:
388 raise ValueError('Images have different numbers of atoms')
389 if np.any(img.pbc != images[0].pbc):
390 raise ValueError('Images have different boundary conditions')
391 if np.any(
392 img.get_atomic_numbers() != images[0].get_atomic_numbers()
393 ):
394 raise ValueError('Images have atoms in different orders')
395 # check periodic cell directions
396 cell_ok = True
397 for pbc, vc, vc0 in zip(img.pbc, img.cell, images[0].cell):
398 if pbc and np.any(np.abs(vc - vc0) > 1e-8):
399 cell_ok = False
400 if not cell_ok:
401 raise NotImplementedError(
402 'Variable cell in periodic directions '
403 'is not implemented yet for NEB'
404 )
406 self.emax = np.nan
408 self.remove_rotation_and_translation = remove_rotation_and_translation
410 if method is None:
411 warnings.warn(
412 "The default method has changed from 'aseneb' to "
413 "'improvedtangent'. The 'aseneb' method is an unpublished, "
414 'custom implementation that is not recommended as it '
415 'frequently results in very poor bands. Please explicitly set '
416 "method='improvedtangent' to silence this warning, or set "
417 "method='aseneb' if you strictly require the old behavior "
418 '(results may vary). '
419 'See: https://gitlab.com/ase/ase/-/merge_requests/3952',
420 UserWarning,
421 )
422 method = 'improvedtangent'
424 if method in ['aseneb', 'eb', 'improvedtangent', 'spline', 'string']:
425 self.method = method
426 else:
427 raise NotImplementedError(method)
429 if precon is not None and method not in ['spline', 'string']:
430 raise NotImplementedError(f'no precon implemented: {method}')
431 self.precon = precon
433 self.neb_method = get_neb_method(self, method)
434 if isinstance(k, (float, int)):
435 k = [k] * (self.nimages - 1)
436 self.k = list(k)
438 if world is None:
439 world = ase.parallel.world
440 self.world = world
442 if parallel:
443 if self.allow_shared_calculator:
444 raise RuntimeError(
445 'Cannot use shared calculators in parallel in NEB.'
446 )
447 self._results = None # placeholder of `calc.results` for all images
448 self.energies = None # ndarray of shape (nimages,)
449 self.residuals = None # ndarray of shape (nimages,)
451 @property
452 @deprecated('Please use `images[i].get_forces(apply_constraint=False)`.')
453 def real_forces(self):
454 # TODO: to be removed in ASE 3.31.0 or later
455 forces = np.full((self.nimages, self.natoms, 3), np.nan)
456 for i in range(self.nimages):
457 forces[i] = self._results[i]['forces']
458 return forces
460 def __ase_optimizable__(self):
461 return NEBOptimizable(self)
463 @property
464 def natoms(self):
465 return len(self.images[0])
467 @property
468 def nimages(self):
469 return len(self.images)
471 @staticmethod
472 def freeze_results_on_image(atoms: ase.Atoms, **results_to_include):
473 atoms.calc = SinglePointCalculator(atoms=atoms, **results_to_include)
475 def interpolate(self, method='linear', mic=False, apply_constraint=None):
476 """Interpolate the positions of the interior images between the
477 initial state (image 0) and final state (image -1).
479 method: str
480 Method by which to interpolate: 'linear' or 'idpp'.
481 linear provides a standard straight-line interpolation, while
482 idpp uses an image-dependent pair potential.
483 mic: bool
484 Use the minimum-image convention when interpolating.
485 apply_constraint: bool
486 Controls if the constraints attached to the images
487 are ignored or applied when setting the interpolated positions.
488 Default value is None, in this case the resulting constrained
489 positions (apply_constraint=True) are compared with unconstrained
490 positions (apply_constraint=False),
491 if the positions are not the same
492 the user is required to specify the desired behaviour
493 by setting up apply_constraint keyword argument to False or True.
494 """
495 if self.remove_rotation_and_translation:
496 minimize_rotation_and_translation(self.images[0], self.images[-1])
498 interpolate(self.images, mic, apply_constraint=apply_constraint)
500 if method == 'idpp':
501 idpp_interpolate(images=self, traj=None, log=None, mic=mic)
503 @deprecated(
504 "Please use NEB's interpolate(method='idpp') method or "
505 'directly call the idpp_interpolate function from ase.mep'
506 )
507 def idpp_interpolate(
508 self,
509 traj='idpp.traj',
510 log='idpp.log',
511 fmax=0.1,
512 optimizer=MDMin,
513 mic=False,
514 steps=100,
515 ):
516 """
517 .. deprecated:: 3.23.0
518 Please use :class:`~ase.mep.NEB`'s ``interpolate(method='idpp')``
519 method
520 """
521 idpp_interpolate(
522 self,
523 traj=traj,
524 log=log,
525 fmax=fmax,
526 optimizer=optimizer,
527 mic=mic,
528 steps=steps,
529 )
531 def get_positions(self):
532 positions = np.empty(((self.nimages - 2) * self.natoms, 3))
533 n1 = 0
534 for image in self.images[1:-1]:
535 n2 = n1 + self.natoms
536 positions[n1:n2] = image.get_positions()
537 n1 = n2
538 return positions
540 def set_positions(self, positions, adjust_positions=True):
541 if adjust_positions:
542 # optional reparameterisation step: some NEB methods need to adjust
543 # positions e.g. string method does this to equispace the images)
544 positions = self.neb_method.adjust_positions(positions)
545 n1 = 0
546 for image in self.images[1:-1]:
547 n2 = n1 + self.natoms
548 image.set_positions(positions[n1:n2])
549 n1 = n2
551 def get_forces(self):
552 """Evaluate and return the forces."""
553 images = self.images
555 if not self.allow_shared_calculator:
556 calculators = [
557 image.calc for image in images if image.calc is not None
558 ]
559 if len(set(calculators)) != len(calculators):
560 msg = (
561 'One or more NEB images share the same calculator. '
562 'Each image must have its own calculator. '
563 'You may wish to use the ase.mep.SingleCalculatorNEB '
564 'class instead, although using separate calculators '
565 'is recommended.'
566 )
567 raise ValueError(msg)
569 forces = np.empty(((self.nimages - 2), self.natoms, 3))
570 energies = np.empty(self.nimages)
571 results = [{} for _ in range(self.nimages)]
573 if self.remove_rotation_and_translation:
574 for i in range(1, self.nimages):
575 minimize_rotation_and_translation(images[i - 1], images[i])
577 if self.method != 'aseneb':
578 for i in (0, -1):
579 # Call `get_forces` to store forces needed by `NEBTools`.
580 images[i].get_forces()
581 results[i] = _filter_results(images[i])
582 energies[i] = images[i].get_potential_energy()
584 self._evaluate_images(energies, forces, results)
586 # if this is the first force call, we need to build the preconditioners
587 if self.precon is None or isinstance(self.precon, (str, Precon, list)):
588 self.precon = PreconImages(self.precon, images)
590 # apply preconditioners to transform forces
591 # for the default IdentityPrecon this does not change their values
592 precon_forces = self.precon.apply(forces, index=slice(1, -1))
594 # Save for later use in iterimages:
595 self.energies = energies
596 self._results = results
598 state = NEBState(self, images, energies)
600 # Can we get rid of self.energies, self.imax, self.emax etc.?
601 self.imax = state.imax
602 self.emax = state.emax
604 spring1 = state.spring(0)
606 self.residuals = []
607 for i in range(1, self.nimages - 1):
608 spring2 = state.spring(i)
609 tangent = self.neb_method.get_tangent(state, spring1, spring2, i)
611 # Get overlap between full PES-derived force and tangent
612 tangential_force = np.vdot(forces[i - 1], tangent)
614 # from now on we use the preconditioned forces (equal for precon=ID)
615 imgforce = precon_forces[i - 1]
617 if i == self.imax and self.climb:
618 """The climbing image, imax, is not affected by the spring
619 forces. This image feels the full PES-derived force,
620 but the tangential component is inverted:
621 see Eq. 5 in paper II."""
622 if self.method == 'aseneb':
623 tangent_mag = np.vdot(tangent, tangent) # For normalizing
624 imgforce -= 2 * tangential_force / tangent_mag * tangent
625 else:
626 imgforce -= 2 * tangential_force * tangent
627 else:
628 self.neb_method.add_image_force(
629 state,
630 tangential_force,
631 tangent,
632 imgforce,
633 spring1,
634 spring2,
635 i,
636 )
637 # compute the residual - with ID precon, this is just max force
638 residual = self.precon.get_residual(i, imgforce)
639 self.residuals.append(residual)
641 spring1 = spring2
643 return precon_forces.reshape((-1, 3))
645 def _evaluate_images(
646 self,
647 energies: npt.NDArray[np.float64],
648 forces: npt.NDArray[np.float64],
649 results: list[dict],
650 ) -> None:
651 if not self.parallel:
652 self._evaluate_images_serial(energies, forces, results)
653 elif self.world.size == 1:
654 self._evaluate_images_threaded(energies, forces, results)
655 else:
656 self._evaluate_images_mpi(energies, forces, results)
658 def _evaluate_images_serial(
659 self,
660 energies: npt.NDArray[np.float64],
661 forces: npt.NDArray[np.float64],
662 results: list[dict],
663 ) -> None:
664 images = self.images
665 # Do all images - one at a time:
666 for i in range(1, self.nimages - 1):
667 forces[i - 1] = images[i].get_forces()
668 energies[i] = images[i].get_potential_energy()
669 results[i] = _filter_results(images[i])
671 def _evaluate_images_threaded(
672 self,
673 energies: npt.NDArray[np.float64],
674 forces: npt.NDArray[np.float64],
675 results: list[dict],
676 ) -> None:
677 images = self.images
679 def run(i: int) -> None:
680 forces[i - 1] = images[i].get_forces()
681 energies[i] = images[i].get_potential_energy()
682 results[i] = _filter_results(images[i])
684 threads = [
685 Thread(target=run, args=(i,)) for i in range(1, self.nimages - 1)
686 ]
687 for thread in threads:
688 thread.start()
689 for thread in threads:
690 thread.join()
692 def _evaluate_images_mpi(
693 self,
694 energies: npt.NDArray[np.float64],
695 forces: npt.NDArray[np.float64],
696 results: list[dict],
697 ) -> None:
698 images = self.images
699 # Parallelize over images:
700 i = self.world.rank * (self.nimages - 2) // self.world.size + 1
701 try:
702 forces[i - 1] = images[i].get_forces()
703 energies[i] = images[i].get_potential_energy()
704 results[i] = _filter_results(images[i])
705 except Exception:
706 # Make sure other images also fail:
707 error = self.world.sum_scalar(1.0)
708 raise
709 else:
710 error = self.world.sum_scalar(0.0)
711 if error:
712 raise RuntimeError('Parallel NEB failed!')
714 for i in range(1, self.nimages - 1):
715 root = (i - 1) * self.world.size // (self.nimages - 2)
716 self.world.broadcast(energies[i : i + 1], root)
717 self.world.broadcast(forces[i - 1], root)
718 self.world.broadcast(results[i], root)
720 def get_residual(self):
721 """Return residual force along the band.
723 Typically this the maximum force component on any image. For
724 non-trivial preconditioners, the appropriate preconditioned norm
725 is used to compute the residual.
726 """
727 if self.residuals is None:
728 raise RuntimeError('get_residual() called before get_forces()')
729 return np.max(self.residuals)
731 def get_potential_energy(self):
732 """Return the maximum potential energy along the band."""
733 return self.emax
735 def set_calculators(self, calculators):
736 """Set new calculators to the images.
738 Parameters
739 ----------
740 calculators : Calculator / list(Calculator)
741 calculator(s) to attach to images
742 - single calculator, only if allow_shared_calculator=True
743 list of calculators if length:
744 - length nimages, set to all images
745 - length nimages-2, set to non-end images only
746 """
748 if not isinstance(calculators, list):
749 if self.allow_shared_calculator:
750 calculators = [calculators] * self.nimages
751 else:
752 raise RuntimeError(
753 'Cannot set shared calculator to NEB '
754 'with allow_shared_calculator=False'
755 )
757 n = len(calculators)
758 if n == self.nimages:
759 for i in range(self.nimages):
760 self.images[i].calc = calculators[i]
761 elif n == self.nimages - 2:
762 for i in range(1, self.nimages - 1):
763 self.images[i].calc = calculators[i - 1]
764 else:
765 raise RuntimeError(
766 'len(calculators)=%d does not fit to len(images)=%d'
767 % (n, self.nimages)
768 )
770 def __len__(self):
771 # Corresponds to number of optimizable degrees of freedom, i.e.
772 # virtual atom count for the optimization algorithm.
773 return (self.nimages - 2) * self.natoms
775 def iterimages(self):
776 # Allows trajectory to convert NEB into several images
777 for i, atoms in enumerate(self.images):
778 if i == 0 or i == self.nimages - 1:
779 yield atoms
780 else:
781 atoms = atoms.copy()
782 self.freeze_results_on_image(atoms, **self._results[i])
783 yield atoms
785 def spline_fit(self, positions=None, norm='precon'):
786 """
787 Fit a cubic spline to this NEB
789 Args:
790 norm (str, optional): Norm to use: 'precon' (default) or 'euclidean'
792 Returns
793 -------
794 fit: ase.precon.precon.SplineFit instance
795 """
796 if norm == 'precon':
797 if self.precon is None or isinstance(self.precon, str):
798 self.precon = PreconImages(self.precon, self.images)
799 precon = self.precon
800 # if this is the first call, we need to build the preconditioners
801 elif norm == 'euclidean':
802 precon = PreconImages('ID', self.images)
803 else:
804 raise ValueError(f'unsupported norm {norm}')
805 return precon.spline_fit(positions)
807 def integrate_forces(self, spline_points=1000, bc_type='not-a-knot'):
808 """Use spline fit to integrate forces along MEP to approximate
809 energy differences using the virtual work approach.
811 Args:
812 spline_points (int, optional): Number of points. Defaults to 1000.
813 bc_type (str, optional): Boundary conditions, default 'not-a-knot'.
815 Returns
816 -------
817 s: reaction coordinate in range [0, 1], with `spline_points` entries
818 E: result of integrating forces, on the same grid as `s`.
819 F: projected forces along MEP
820 """
821 # note we use standard Euclidean rather than preconditioned norm
822 # to compute the virtual work
823 fit = self.spline_fit(norm='euclidean')
824 forces = np.array(
825 [image.get_forces().reshape(-1) for image in self.images]
826 )
827 f = CubicSpline(fit.s, forces, bc_type=bc_type)
829 s = np.linspace(0.0, 1.0, spline_points, endpoint=True)
830 dE = f(s) * fit.dx_ds(s)
831 F = dE.sum(axis=1)
832 E = -cumulative_trapezoid(F, s, initial=0.0)
833 return s, E, F
836def _filter_results(atoms: ase.Atoms) -> dict:
837 return {k: v for k, v in atoms.calc.results.items() if k in all_properties}
840class DyNEB(NEB):
841 def __init__(
842 self,
843 *args,
844 fmax: float = 0.05,
845 scale_fmax: float = 0.0,
846 **kwargs,
847 ) -> None:
848 r"""Subclass of :class:`~ase.mep.neb.NEB` that allows for scaled and
849 dynamic optimizations of images [Lindgren2019]_.
851 This method does not perform
852 force calls on images that are below the convergence criterion.
853 The convergence criteria can be scaled with a displacement metric
854 to focus the optimization on the saddle point region.
856 .. [Lindgren2019]
857 P. Lindgren, G. Kastlunger and A. A. Peterson,
858 Scaled and Dynamic Optimizations of Nudged Elastic Bands,
859 J. Chem. Theory Comput. 15, 11, 5787-5793 (2019).
860 :doi:`10.1021/acs.jctc.9b00633`
862 Parameters
863 ----------
864 fmax : float, default: 0.05
865 Reference force convergence criterion.
866 This must be identical to the `fmax` of the optimizer.
867 scale_fmax : float, default: 0.0
868 Scale convergence criteria along band based on the distance between
869 an image and the image with the highest potential energy. This
870 keyword determines how rapidly the convergence criteria are scaled.
871 :math:`\alpha_\mathrm{s}` in Eq. (2) in [Lindgren2019]_.
872 *args, **kwargs
873 Additional arguments passed to :class:`~ase.mep.neb.NEB`.
875 Notes
876 -----
877 :class:`DyNEB` only works in series.
879 .. versionremoved :: 3.30.0
881 The `dynamic_relaxation` argument is removed.
882 This class now always performs DyNEB [Lindgren2019]_.
884 """
885 super().__init__(*args, **kwargs)
886 self.fmax = fmax
887 self.scale_fmax = scale_fmax
889 def set_positions(self, positions):
890 """Update atomic positions but only for unconverged images."""
891 n1 = 0
892 for i, image in enumerate(self.images[1:-1]):
893 if self.parallel:
894 msg = (
895 'Dynamic relaxation does not work efficiently '
896 'when parallelizing over images. Try AutoNEB '
897 'routine for freezing images in parallel.'
898 )
899 raise ValueError(msg)
901 forces_dyn = self._fmax_all()
902 if forces_dyn[i] < self.fmax:
903 n1 += self.natoms
904 else:
905 n2 = n1 + self.natoms
906 image.set_positions(positions[n1:n2])
907 n1 = n2
909 def _fmax_all(self) -> list[float]:
910 """Store maximum force acting on each image in list.
912 This is used in `set_positions`.
913 """
914 n = self.natoms
915 forces = self.get_forces()
916 fmax_images = [
917 np.sqrt((forces[n * i : n + n * i] ** 2).sum(axis=1)).max()
918 for i in range(self.nimages - 2)
919 ]
920 return fmax_images
922 def get_forces(self) -> npt.NDArray[np.float64]:
923 """Get NEB forces with applying the scaled convergence criteria.
925 For each image, if the forces are below the convergence criteria,
926 they are replaced with zero.
927 The keyword `scale_fmax` determines the rate of convergence scaling.
928 For non-zero `scale_fmax`, the convergence criteria become looser for
929 the images further away from the saddle point to focus optimization on
930 the saddle-point region.
931 """
932 forces = super().get_forces()
933 n = self.natoms
934 for i in range(self.nimages - 2):
935 n1 = n * i
936 n2 = n1 + n
937 force = np.sqrt((forces[n1:n2] ** 2.0).sum(axis=1)).max()
938 n_imax = (self.imax - 1) * n # Image with highest energy.
940 positions = self.get_positions()
941 pos_imax = positions[n_imax : n_imax + n]
943 """Scale convergence criteria based on distance between an
944 image and the image with the highest potential energy."""
945 rel_pos = np.sqrt(((positions[n1:n2] - pos_imax) ** 2).sum())
946 if force < self.fmax * (1.0 + rel_pos * self.scale_fmax):
947 if i == self.imax - 1:
948 # Keep forces at saddle point for the log file.
949 pass
950 else:
951 # Set forces to zero before they are sent to optimizer.
952 forces[n1:n2, :] = 0.0
953 return forces
956class NEBOptimizer(Optimizer):
957 """
958 This optimizer applies an adaptive ODE solver to a NEB
960 Details of the adaptive ODE solver are described in paper IV
961 """
963 def __init__(
964 self,
965 neb,
966 restart=None,
967 logfile='-',
968 trajectory=None,
969 master=None,
970 append_trajectory=False,
971 method='ODE',
972 alpha=0.01,
973 verbose=0,
974 rtol=0.1,
975 C1=1e-2,
976 C2=2.0,
977 ):
979 super().__init__(
980 atoms=neb,
981 restart=restart,
982 logfile=logfile,
983 trajectory=trajectory,
984 master=master,
985 append_trajectory=append_trajectory,
986 )
987 self.neb = neb
989 method = method.lower()
990 methods = ['ode', 'static', 'krylov']
991 if method not in methods:
992 raise ValueError(f'method must be one of {methods}')
993 self.method = method
995 self.alpha = alpha
996 self.verbose = verbose
997 self.rtol = rtol
998 self.C1 = C1
999 self.C2 = C2
1001 def force_function(self, X):
1002 positions = X.reshape((self.neb.nimages - 2) * self.neb.natoms, 3)
1003 self.neb.set_positions(positions)
1004 forces = self.neb.get_forces().reshape(-1)
1005 return forces
1007 def get_residual(self, F=None, X=None):
1008 return self.neb.get_residual()
1010 def log(self):
1011 fmax = self.get_residual()
1012 T = time.localtime()
1013 if self.logfile is not None:
1014 name = f'{self.__class__.__name__}[{self.method}]'
1015 if self.nsteps == 0:
1016 args = (' ' * len(name), 'Step', 'Time', 'fmax')
1017 msg = '%s %4s %8s %12s\n' % args
1018 self.logfile.write(msg)
1020 args = (name, self.nsteps, T[3], T[4], T[5], fmax)
1021 msg = '%s: %3d %02d:%02d:%02d %12.4f\n' % args
1022 self.logfile.write(msg)
1024 def callback(self, X, F=None):
1025 self.log()
1026 self.call_observers()
1027 self.nsteps += 1
1029 def run_ode(self, fmax):
1030 try:
1031 ode12r(
1032 self.force_function,
1033 self.neb.get_positions().reshape(-1),
1034 fmax=fmax,
1035 rtol=self.rtol,
1036 C1=self.C1,
1037 C2=self.C2,
1038 steps=self.max_steps,
1039 verbose=self.verbose,
1040 callback=self.callback,
1041 residual=self.get_residual,
1042 )
1043 return True
1044 except OptimizerConvergenceError:
1045 return False
1047 def run_static(self, fmax):
1048 X = self.neb.get_positions().reshape(-1)
1049 for _ in range(self.max_steps):
1050 F = self.force_function(X)
1051 if self.neb.get_residual() <= fmax:
1052 return True
1053 X += self.alpha * F
1054 self.callback(X)
1055 return False
1057 def run(self, fmax=0.05, steps=DEFAULT_MAX_STEPS, method=None):
1058 """
1059 Optimize images to obtain the minimum energy path
1061 Parameters
1062 ----------
1063 fmax - desired force tolerance
1064 steps - maximum number of steps
1065 """
1066 self.max_steps = steps
1067 if method is None:
1068 method = self.method
1069 if method == 'ode':
1070 return self.run_ode(fmax)
1071 elif method == 'static':
1072 return self.run_static(fmax)
1073 else:
1074 raise ValueError(f'unknown method: {self.method}')
1077class IDPP(Calculator):
1078 """Image dependent pair potential.
1080 See:
1081 Improved initial guess for minimum energy path calculations.
1082 Søren Smidstrup, Andreas Pedersen, Kurt Stokbro and Hannes Jónsson
1083 Chem. Phys. 140, 214106 (2014)
1084 """
1086 implemented_properties = ['energy', 'forces']
1088 def __init__(self, target, mic):
1089 Calculator.__init__(self)
1090 self.target = target
1091 self.mic = mic
1093 def calculate(self, atoms, properties, system_changes):
1094 Calculator.calculate(self, atoms, properties, system_changes)
1096 P = atoms.get_positions()
1097 d = []
1098 D = []
1099 for p in P:
1100 Di = P - p
1101 if self.mic:
1102 Di, di = find_mic(Di, atoms.get_cell(), atoms.get_pbc())
1103 else:
1104 di = np.sqrt((Di**2).sum(1))
1105 d.append(di)
1106 D.append(Di)
1107 d = np.array(d)
1108 D = np.array(D)
1110 dd = d - self.target
1111 d.ravel()[:: len(d) + 1] = 1 # avoid dividing by zero
1112 d4 = d**4
1113 e = 0.5 * (dd**2 / d4).sum()
1114 f = -2 * ((dd * (1 - 2 * dd / d) / d**5)[..., np.newaxis] * D).sum(0)
1115 self.results = {'energy': e, 'forces': f}
1118@deprecated(
1119 'SingleCalculatorNEB is deprecated. '
1120 'Please use NEB(allow_shared_calculator=True) instead.'
1121)
1122class SingleCalculatorNEB(NEB):
1123 """
1124 .. deprecated:: 3.23.0
1125 Please use ``NEB(allow_shared_calculator=True)`` instead
1126 """
1128 def __init__(self, images, *args, **kwargs):
1129 kwargs['allow_shared_calculator'] = True
1130 super().__init__(images, *args, **kwargs)
1133def interpolate(
1134 images,
1135 mic=False,
1136 interpolate_cell=False,
1137 use_scaled_coord=False,
1138 apply_constraint=None,
1139):
1140 """Given a list of images, linearly interpolate the positions of the
1141 interior images.
1143 mic: bool
1144 Map movement into the unit cell by using the minimum image convention.
1145 interpolate_cell: bool
1146 Interpolate the three cell vectors linearly just like the atomic
1147 positions. Not implemented for NEB calculations!
1148 use_scaled_coord: bool
1149 Use scaled/internal/fractional coordinates instead of real ones for the
1150 interpolation. Not implemented for NEB calculations!
1151 apply_constraint: bool
1152 Controls if the constraints attached to the images
1153 are ignored or applied when setting the interpolated positions.
1154 Default value is None, in this case the resulting constrained positions
1155 (apply_constraint=True) are compared with unconstrained positions
1156 (apply_constraint=False), if the positions are not the same
1157 the user is required to specify the desired behaviour
1158 by setting up apply_constraint keyword argument to False or True.
1159 """
1160 if use_scaled_coord:
1161 pos1 = images[0].get_scaled_positions(wrap=mic)
1162 pos2 = images[-1].get_scaled_positions(wrap=mic)
1163 else:
1164 pos1 = images[0].get_positions()
1165 pos2 = images[-1].get_positions()
1166 d = pos2 - pos1
1167 if not use_scaled_coord and mic:
1168 d = find_mic(d, images[0].get_cell(), images[0].pbc)[0]
1169 d /= len(images) - 1.0
1170 if interpolate_cell:
1171 cell1 = images[0].get_cell()
1172 cell2 = images[-1].get_cell()
1173 cell_diff = cell2 - cell1
1174 cell_diff /= len(images) - 1.0
1175 for i in range(1, len(images) - 1):
1176 # first the new cell, otherwise scaled positions are wrong
1177 if interpolate_cell:
1178 images[i].set_cell(cell1 + i * cell_diff)
1179 new_pos = pos1 + i * d
1180 if use_scaled_coord:
1181 images[i].set_scaled_positions(new_pos)
1182 else:
1183 if apply_constraint is None:
1184 unconstrained_image = images[i].copy()
1185 unconstrained_image.set_positions(
1186 new_pos, apply_constraint=False
1187 )
1188 images[i].set_positions(new_pos, apply_constraint=True)
1189 if not np.allclose(
1190 unconstrained_image.positions, images[i].positions
1191 ):
1192 raise RuntimeError(
1193 f'Constraints in image {i}\n'
1194 'affect the interpolation results.\n'
1195 'Please specify if you want to\n'
1196 'apply or ignore the constraints\n'
1197 'during the interpolation\n'
1198 'with the apply_constraint argument.'
1199 )
1200 else:
1201 images[i].set_positions(
1202 new_pos, apply_constraint=apply_constraint
1203 )
1206def idpp_interpolate(
1207 images,
1208 traj='idpp.traj',
1209 log='idpp.log',
1210 fmax=0.1,
1211 optimizer=MDMin,
1212 mic=False,
1213 steps=100,
1214):
1215 """Interpolate using the IDPP method. 'images' can either be a plain
1216 list of images or an NEB object (containing a list of images)."""
1217 if hasattr(images, 'interpolate'):
1218 neb = images
1219 else:
1220 neb = NEB(images)
1222 d1 = neb.images[0].get_all_distances(mic=mic)
1223 d2 = neb.images[-1].get_all_distances(mic=mic)
1224 d = (d2 - d1) / (neb.nimages - 1)
1225 real_calcs = []
1226 for i, image in enumerate(neb.images):
1227 real_calcs.append(image.calc)
1228 image.calc = IDPP(d1 + i * d, mic=mic)
1230 with optimizer(neb, trajectory=traj, logfile=log) as opt:
1231 opt.run(fmax=fmax, steps=steps)
1233 for image, calc in zip(neb.images, real_calcs):
1234 image.calc = calc
1237class NEBTools:
1238 """Class to make many of the common tools for NEB analysis available to
1239 the user. Useful for scripting the output of many jobs. Initialize with
1240 list of images which make up one or more band of the NEB relaxation."""
1242 def __init__(self, images):
1243 self.images = images
1245 @deprecated(
1246 'NEBTools.get_fit() is deprecated. '
1247 'Please use ase.utils.forcecurve.fit_images(images).'
1248 )
1249 def get_fit(self):
1250 """
1251 .. deprecated:: 3.23.0
1252 Please use ``ase.utils.forcecurve.fit_images(images)``
1253 """
1254 return fit_images(self.images)
1256 def get_barrier(self, fit=True, raw=False):
1257 """Returns the barrier estimate from the NEB, along with the
1258 Delta E of the elementary reaction. If fit=True, the barrier is
1259 estimated based on the interpolated fit to the images; if
1260 fit=False, the barrier is taken as the maximum-energy image
1261 without interpolation. Set raw=True to get the raw energy of the
1262 transition state instead of the forward barrier."""
1263 forcefit = fit_images(self.images)
1264 energies = forcefit.energies
1265 fit_energies = forcefit.fit_energies
1266 dE = energies[-1] - energies[0]
1267 if fit:
1268 barrier = max(fit_energies)
1269 else:
1270 barrier = max(energies)
1271 if raw:
1272 barrier += self.images[0].get_potential_energy()
1273 return barrier, dE
1275 def get_fmax(self, **kwargs):
1276 """Returns fmax, as used by optimizers with NEB."""
1277 neb = NEB(self.images, **kwargs)
1278 forces = neb.get_forces()
1279 return np.sqrt((forces**2).sum(axis=1).max())
1281 def plot_band(self, ax=None):
1282 """Plots the NEB band on matplotlib axes object 'ax'. If ax=None
1283 returns a new figure object."""
1284 forcefit = fit_images(self.images)
1285 ax = forcefit.plot(ax=ax)
1286 return ax.figure
1288 def plot_bands(
1289 self, constant_x=False, constant_y=False, nimages=None, label='nebplots'
1290 ):
1291 """Given a trajectory containing many steps of a NEB, makes
1292 plots of each band in the series in a single PDF.
1294 constant_x: bool
1295 Use the same x limits on all plots.
1296 constant_y: bool
1297 Use the same y limits on all plots.
1298 nimages: int
1299 Number of images per band. Guessed if not supplied.
1300 label: str
1301 Name for the output file. .pdf will be appended.
1302 """
1303 from matplotlib import pyplot
1304 from matplotlib.backends.backend_pdf import PdfPages
1306 if nimages is None:
1307 nimages = _guess_nimages(self.images)
1308 nebsteps = len(self.images) // nimages
1309 if constant_x or constant_y:
1310 sys.stdout.write('Scaling axes.\n')
1311 sys.stdout.flush()
1312 # Plot all to one plot, then pull its x and y range.
1313 fig, ax = pyplot.subplots()
1314 for index in range(nebsteps):
1315 images = self.images[index * nimages : (index + 1) * nimages]
1316 NEBTools(images).plot_band(ax=ax)
1317 xlim = ax.get_xlim()
1318 ylim = ax.get_ylim()
1319 pyplot.close(fig) # Reference counting "bug" in pyplot.
1320 with PdfPages(label + '.pdf') as pdf:
1321 for index in range(nebsteps):
1322 sys.stdout.write(
1323 '\rProcessing band {:10d} / {:10d}'.format(index, nebsteps)
1324 )
1325 sys.stdout.flush()
1326 fig, ax = pyplot.subplots()
1327 images = self.images[index * nimages : (index + 1) * nimages]
1328 NEBTools(images).plot_band(ax=ax)
1329 if constant_x:
1330 ax.set_xlim(xlim)
1331 if constant_y:
1332 ax.set_ylim(ylim)
1333 pdf.savefig(fig)
1334 pyplot.close(fig) # Reference counting "bug" in pyplot.
1335 sys.stdout.write('\n')
1338def _guess_nimages(images: list[ase.Atoms]) -> int:
1339 """Guess the number of images per band from a trajectory.
1341 The guess is based on the (reasonable) assumption that the image at the
1342 first end point does not change during the NEB simulation.
1343 The function should also work for symmetric cases and for single-band cases.
1344 """
1345 for index, atoms in enumerate(images[1:], start=1):
1346 if not compare_atoms(atoms, images[0]):
1347 return index
1348 return len(images) # only one band in the trajectory
1351class NEBtools(NEBTools):
1352 @deprecated('NEBtools has been renamed; please use NEBTools.')
1353 def __init__(self, images):
1354 """
1355 .. deprecated:: 3.23.0
1356 Please use :class:`~ase.mep.NEBTools`.
1357 """
1358 NEBTools.__init__(self, images)
1361@deprecated('Please use NEBTools.plot_band_from_fit.')
1362def plot_band_from_fit(s, E, Sfit, Efit, lines, ax=None):
1363 """
1364 .. deprecated:: 3.23.0
1365 Please use :meth:`NEBTools.plot_band_from_fit`.
1366 """
1367 NEBTools.plot_band_from_fit(s, E, Sfit, Efit, lines, ax=None)