Coverage for ase/mep/autoneb.py: 75.07%
341 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 os
2import shutil
3import types
4from contextlib import ExitStack
5from math import exp, log
6from pathlib import Path
7from typing import Any
9import numpy as np
11import ase.parallel as mpi
12from ase.calculators.singlepoint import SinglePointCalculator
13from ase.io import Trajectory, read
14from ase.mep.neb import NEB
15from ase.optimize import BFGS, FIRE
16from ase.utils import deprecated
19def _forbid_optimizer_string(args: list, kwargs: dict[str, Any]) -> bool:
20 """Replace optimizer string with Optimizer object."""
21 arg_position = 11
22 try:
23 if len(args) >= arg_position + 1 and isinstance(
24 args[arg_position], str
25 ):
26 args[11] = {'BFGS': BFGS, 'FIRE': FIRE}[args[arg_position]]
28 elif isinstance(kwargs.get('optimizer', None), str):
29 kwargs['optimizer'] = {'BFGS': BFGS, 'FIRE': FIRE}[
30 kwargs['optimizer']
31 ]
32 else:
33 return False
34 except KeyError as err:
35 msg = (
36 '"optimizer" must be "BFGS" or "FIRE" if string is passed, '
37 'but passing a string is deprecated. Use an Optimizer object '
38 'instead'
39 )
40 raise ValueError(msg) from err
42 return True
45class AutoNEB:
46 """AutoNEB object.
48 The AutoNEB algorithm streamlines the execution of NEB and CI-NEB
49 calculations following the algorithm described in:
51 E. L. Kolsbjerg, M. N. Groves, and B. Hammer, J. Chem. Phys,
52 145, 094107, 2016. (doi: 10.1063/1.4961868)
54 The user supplies at minimum the two end-points and possibly also some
55 intermediate images.
57 The stages are:
58 1) Define a set of images and name them sequentially.
59 Must at least have a relaxed starting and ending image
60 User can supply intermediate guesses which do not need to
61 have previously determined energies (probably from another
62 NEB calculation with a lower level of theory)
63 2) AutoNEB will first evaluate the user provided intermediate images
64 3) AutoNEB will then add additional images dynamically until n_max
65 is reached
66 4) A climbing image will attempt to locate the saddle point
67 5) All the images between the highest point and the starting point
68 are further relaxed to smooth the path
69 6) All the images between the highest point and the ending point are
70 further relaxed to smooth the path
72 Step 4 and 5-6 are optional steps!
74 Parameters
75 ----------
77 attach_calculators:
78 Function which adds valid calculators to the list of images supplied.
79 prefix: string or pathlib.Path
80 All files that the AutoNEB method reads and writes are prefixed with
81 prefix
82 n_simul: int
83 The number of relaxations run in parallel.
84 n_max: int
85 The number of images along the NEB path when done.
86 This number includes the two end-points.
87 Important: due to the dynamic adding of images around the peak n_max
88 must be updated if the NEB is restarted.
89 climb: boolean
90 Should a CI-NEB calculation be done at the top-point
91 fmax: float or list of floats
92 The maximum force along the NEB path
93 maxsteps: int
94 The maximum number of steps in each NEB relaxation.
95 If a list is given the first number of steps is used in the build-up
96 and final scan phase;
97 the second number of steps is used in the CI step after all images
98 have been inserted.
99 k: float
100 The spring constant along the NEB path
101 method: str (see neb.py)
102 Choice betweeen three method:
103 'aseneb', legacy ase NEB implementation
104 'improvedtangent', published NEB implementation
105 'eb', full spring force implementation (default)
106 optimizer: object
107 Optimizer object, defaults to FIRE
108 space_energy_ratio: float
109 The preference for new images to be added in a big energy gab
110 with a preference around the peak or in the biggest geometric gab.
111 A space_energy_ratio set to 1 will only considder geometric gabs
112 while one set to 0 will result in only images for energy
113 resolution.
115 Notes
116 -----
117 The AutoNEB method uses a fixed file-naming convention.
118 The initial images should have the naming prefix000.traj, prefix001.traj,
119 ... up until the final image in prefix00N.traj
120 Images are dynamically added in between the first and last image until
121 n_max images have been reached.
122 When doing the i'th NEB optimization a set of files
123 prefixXXXiter00i.traj exists with XXX ranging from 000 to the N images
124 currently in the NEB.
126 The most recent NEB path can always be monitored by:
128 ..code-block:: bash
130 $ ase-gui -n -1 neb???.traj
132 .. deprecated:: 3.22.0
133 Passing ``optimizer`` as a string is deprecated. Use an ``Optimizer``
134 object instead.
135 """
137 @deprecated(
138 "Passing 'optimizer' as a string is deprecated. "
139 "Use an 'Optimizer' object instead.",
140 callback=_forbid_optimizer_string,
141 )
142 def __init__(
143 self,
144 attach_calculators,
145 prefix,
146 n_simul,
147 n_max,
148 iter_folder='AutoNEB_iter',
149 fmax=0.025,
150 maxsteps=10000,
151 k=0.1,
152 climb=True,
153 method='eb',
154 optimizer=FIRE,
155 remove_rotation_and_translation=False,
156 space_energy_ratio=0.5,
157 world=None,
158 parallel=True,
159 smooth_curve=False,
160 interpolate_method='idpp',
161 ):
162 self.attach_calculators = attach_calculators
163 self.prefix = Path(prefix)
164 self.n_simul = n_simul
165 self.n_max = n_max
166 self.climb = climb
167 self.all_images = []
169 self.parallel = parallel
170 self.maxsteps = maxsteps
171 self.fmax = fmax
172 self.k = k
173 self.method = method
174 self.remove_rotation_and_translation = remove_rotation_and_translation
175 self.space_energy_ratio = space_energy_ratio
176 if interpolate_method not in ['idpp', 'linear']:
177 self.interpolate_method = 'idpp'
178 print(
179 'Interpolation method not implementet.',
180 'Using the IDPP method.',
181 )
182 else:
183 self.interpolate_method = interpolate_method
184 if world is None:
185 world = mpi.world
186 self.world = world
187 self.smooth_curve = smooth_curve
189 self.optimizer = optimizer
191 self.iter_folder = Path(self.prefix.parent) / iter_folder
192 self.iter_folder.mkdir(exist_ok=True)
194 def execute_one_neb(self, n_cur, to_run, climb=False, many_steps=False):
195 with ExitStack() as exitstack:
196 self._execute_one_neb(
197 exitstack, n_cur, to_run, climb=climb, many_steps=many_steps
198 )
200 def iter_trajpath(self, i, iiter):
201 """When doing the i'th NEB optimization a set of files
202 prefixXXXiter00i.traj exists with XXX ranging from 000 to the N images
203 currently in the NEB."""
204 return self.iter_folder / (
205 self.prefix.name + f'{i:03d}iter{iiter:03d}.traj'
206 )
208 def _execute_one_neb(
209 self, exitstack, n_cur, to_run, climb=False, many_steps=False
210 ):
211 """Internal method which executes one NEB optimization."""
213 closelater = exitstack.enter_context
215 self.iteration += 1
216 # First we copy around all the images we are not using in this
217 # neb (for reproducability purposes)
218 if self.world.rank == 0:
219 for i in range(n_cur):
220 if i not in to_run[1:-1]:
221 filename = '%s%03d.traj' % (self.prefix, i)
222 with Trajectory(
223 filename, mode='w', atoms=self.all_images[i]
224 ) as traj:
225 traj.write()
226 filename_ref = self.iter_trajpath(i, self.iteration)
227 if os.path.isfile(filename):
228 shutil.copy2(filename, filename_ref)
229 if self.world.rank == 0:
230 print('Now starting iteration %d on ' % self.iteration, to_run)
231 # Attach calculators to all the images we will include in the NEB
232 self.attach_calculators([self.all_images[i] for i in to_run[1:-1]])
233 neb = NEB(
234 [self.all_images[i] for i in to_run],
235 k=[self.k[i] for i in to_run[0:-1]],
236 method=self.method,
237 parallel=self.parallel,
238 remove_rotation_and_translation=self.remove_rotation_and_translation,
239 climb=climb,
240 )
242 # Do the actual NEB calculation
243 logpath = (
244 self.iter_folder
245 / f'{self.prefix.name}_log_iter{self.iteration:03d}.log'
246 )
247 qn = closelater(self.optimizer(neb, logfile=logpath))
249 # Find the ranks which are masters for each their calculation
250 if self.parallel:
251 nneb = to_run[0]
252 nim = len(to_run) - 2
253 n = self.world.size // nim # number of cpu's per image
254 j = 1 + self.world.rank // n # my image number
255 assert nim * n == self.world.size
256 traj = closelater(
257 Trajectory(
258 '%s%03d.traj' % (self.prefix, j + nneb),
259 'w',
260 self.all_images[j + nneb],
261 master=(self.world.rank % n == 0),
262 )
263 )
264 filename_ref = self.iter_trajpath(j + nneb, self.iteration)
265 trajhist = closelater(
266 Trajectory(
267 filename_ref,
268 'w',
269 self.all_images[j + nneb],
270 master=(self.world.rank % n == 0),
271 )
272 )
273 qn.attach(traj)
274 qn.attach(trajhist)
275 else:
276 num = 1
277 for i, j in enumerate(to_run[1:-1]):
278 filename_ref = self.iter_trajpath(j, self.iteration)
279 trajhist = closelater(
280 Trajectory(filename_ref, 'w', self.all_images[j])
281 )
282 qn.attach(seriel_writer(trajhist, i, num).write)
284 traj = closelater(
285 Trajectory(
286 '%s%03d.traj' % (self.prefix, j),
287 'w',
288 self.all_images[j],
289 )
290 )
291 qn.attach(seriel_writer(traj, i, num).write)
292 num += 1
294 if isinstance(self.maxsteps, (list, tuple)) and many_steps:
295 steps = self.maxsteps[1]
296 elif isinstance(self.maxsteps, (list, tuple)) and not many_steps:
297 steps = self.maxsteps[0]
298 else:
299 steps = self.maxsteps
301 if isinstance(self.fmax, (list, tuple)) and many_steps:
302 fmax = self.fmax[1]
303 elif isinstance(self.fmax, (list, tuple)) and not many_steps:
304 fmax = self.fmax[0]
305 else:
306 fmax = self.fmax
307 qn.run(fmax=fmax, steps=steps)
309 # Remove the calculators and replace them with single
310 # point calculators and update all the nodes for
311 # preperration for next iteration
312 neb.distribute = types.MethodType(store_E_and_F_in_spc, neb)
313 neb.distribute()
315 def run(self):
316 """Run the AutoNEB optimization algorithm."""
317 n_cur = self.__initialize__()
318 while len(self.all_images) < self.n_simul + 2:
319 if isinstance(self.k, (float, int)):
320 self.k = [self.k] * (len(self.all_images) - 1)
321 if self.world.rank == 0:
322 print('Now adding images for initial run')
323 # Insert a new image where the distance between two images is
324 # the largest
325 spring_lengths = []
326 for j in range(n_cur - 1):
327 spring_vec = (
328 self.all_images[j + 1].get_positions()
329 - self.all_images[j].get_positions()
330 )
331 spring_lengths.append(np.linalg.norm(spring_vec))
332 jmax = np.argmax(spring_lengths)
334 if self.world.rank == 0:
335 print('Max length between images is at ', jmax)
337 # The interpolation used to make initial guesses
338 # If only start and end images supplied make all img at ones
339 if len(self.all_images) == 2:
340 n_between = self.n_simul
341 else:
342 n_between = 1
344 toInterpolate = [self.all_images[jmax]]
345 for _ in range(n_between):
346 toInterpolate += [toInterpolate[0].copy()]
347 toInterpolate += [self.all_images[jmax + 1]]
349 neb = NEB(toInterpolate)
350 neb.interpolate(method=self.interpolate_method)
352 tmp = self.all_images[: jmax + 1]
353 tmp += toInterpolate[1:-1]
354 tmp.extend(self.all_images[jmax + 1 :])
356 self.all_images = tmp
358 # Expect springs to be in equilibrium
359 k_tmp = self.k[:jmax]
360 k_tmp += [self.k[jmax] * (n_between + 1)] * (n_between + 1)
361 k_tmp.extend(self.k[jmax + 1 :])
362 self.k = k_tmp
364 # Run the NEB calculation with the new image included
365 n_cur += n_between
367 # Determine if any images do not have a valid energy yet
368 energies = self.get_energies()
370 n_non_valid_energies = len([e for e in energies if e != e])
372 if self.world.rank == 0:
373 print('Start of evaluation of the initial images')
375 while n_non_valid_energies != 0:
376 if isinstance(self.k, (float, int)):
377 self.k = [self.k] * (len(self.all_images) - 1)
379 # First do one run since some energie are non-determined
380 to_run, climb_safe = self.which_images_to_run_on()
381 self.execute_one_neb(n_cur, to_run, climb=False)
383 energies = self.get_energies()
384 n_non_valid_energies = len([e for e in energies if e != e])
386 if self.world.rank == 0:
387 print('Finished initialisation phase.')
389 # Then add one image at a time until we have n_max images
390 while n_cur < self.n_max:
391 if isinstance(self.k, (float, int)):
392 self.k = [self.k] * (len(self.all_images) - 1)
393 # Insert a new image where the distance between two images
394 # is the largest OR where a higher energy reselution is needed
395 if self.world.rank == 0:
396 print(
397 '****Now adding another image until n_max is reached',
398 f'({n_cur}/{self.n_max})****',
399 )
400 spring_lengths = []
401 for j in range(n_cur - 1):
402 spring_vec = (
403 self.all_images[j + 1].get_positions()
404 - self.all_images[j].get_positions()
405 )
406 spring_lengths.append(np.linalg.norm(spring_vec))
408 total_vec = (
409 self.all_images[0].get_positions()
410 - self.all_images[-1].get_positions()
411 )
412 tl = np.linalg.norm(total_vec)
414 fR = max(spring_lengths) / tl
416 e = self.get_energies()
417 ed = []
418 emin = min(e)
419 enorm = max(e) - emin
420 for j in range(n_cur - 1):
421 delta_E = (
422 (e[j + 1] - e[j]) * (e[j + 1] + e[j] - 2 * emin) / 2 / enorm
423 )
424 ed.append(abs(delta_E))
426 gR = max(ed) / enorm
428 if fR / gR > self.space_energy_ratio:
429 jmax = np.argmax(spring_lengths)
430 t = 'spring length!'
431 else:
432 jmax = np.argmax(ed)
433 t = 'energy difference between neighbours!'
435 if self.world.rank == 0:
436 print(
437 f'Adding image between {jmax} and',
438 f'{jmax + 1}. New image point is selected',
439 'on the basis of the biggest ' + t,
440 )
442 toInterpolate = [self.all_images[jmax]]
443 toInterpolate += [toInterpolate[0].copy()]
444 toInterpolate += [self.all_images[jmax + 1]]
446 neb = NEB(toInterpolate)
447 neb.interpolate(method=self.interpolate_method)
449 tmp = self.all_images[: jmax + 1]
450 tmp += toInterpolate[1:-1]
451 tmp.extend(self.all_images[jmax + 1 :])
453 self.all_images = tmp
455 # Expect springs to be in equilibrium
456 k_tmp = self.k[:jmax]
457 k_tmp += [self.k[jmax] * 2] * 2
458 k_tmp.extend(self.k[jmax + 1 :])
459 self.k = k_tmp
461 # Run the NEB calculation with the new image included
462 n_cur += 1
463 to_run, climb_safe = self.which_images_to_run_on()
465 self.execute_one_neb(n_cur, to_run, climb=False)
467 if self.world.rank == 0:
468 print('n_max images has been reached')
470 # Do a single climb around the top-point if requested
471 if self.climb:
472 if isinstance(self.k, (float, int)):
473 self.k = [self.k] * (len(self.all_images) - 1)
474 if self.world.rank == 0:
475 print('****Now doing the CI-NEB calculation****')
476 to_run, climb_safe = self.which_images_to_run_on()
478 assert climb_safe, 'climb_safe should be true at this point!'
479 self.execute_one_neb(n_cur, to_run, climb=True, many_steps=True)
481 if not self.smooth_curve:
482 return self.all_images
484 # If a smooth_curve is requsted ajust the springs to follow two
485 # gaussian distributions
486 e = self.get_energies()
487 peak = self.get_highest_energy_index()
488 k_max = 10
490 d1 = np.linalg.norm(
491 self.all_images[peak].get_positions()
492 - self.all_images[0].get_positions()
493 )
494 d2 = np.linalg.norm(
495 self.all_images[peak].get_positions()
496 - self.all_images[-1].get_positions()
497 )
498 l1 = -(d1**2) / log(0.2)
499 l2 = -(d2**2) / log(0.2)
501 x1 = []
502 x2 = []
503 for i in range(peak):
504 v = (
505 self.all_images[i].get_positions()
506 + self.all_images[i + 1].get_positions()
507 ) / 2 - self.all_images[0].get_positions()
508 x1.append(np.linalg.norm(v))
510 for i in range(peak, len(self.all_images) - 1):
511 v = (
512 self.all_images[i].get_positions()
513 + self.all_images[i + 1].get_positions()
514 ) / 2 - self.all_images[0].get_positions()
515 x2.append(np.linalg.norm(v))
516 k_tmp = []
517 for x in x1:
518 k_tmp.append(k_max * exp(-((x - d1) ** 2) / l1))
519 for x in x2:
520 k_tmp.append(k_max * exp(-((x - d1) ** 2) / l2))
522 self.k = k_tmp
523 # Roll back to start from the top-point
524 if self.world.rank == 0:
525 print('Now moving from top to start')
526 highest_energy_index = self.get_highest_energy_index()
527 nneb = highest_energy_index - self.n_simul - 1
528 while nneb >= 0:
529 self.execute_one_neb(
530 n_cur, range(nneb, nneb + self.n_simul + 2), climb=False
531 )
532 nneb -= 1
534 # Roll forward from the top-point until the end
535 nneb = self.get_highest_energy_index()
537 if self.world.rank == 0:
538 print('Now moving from top to end')
539 while nneb <= self.n_max - self.n_simul - 2:
540 self.execute_one_neb(
541 n_cur, range(nneb, nneb + self.n_simul + 2), climb=False
542 )
543 nneb += 1
544 return self.all_images
546 def __initialize__(self):
547 """Load files from the filesystem."""
548 if not os.path.isfile(f'{self.prefix}000.traj'):
549 raise OSError(
550 f'No file with name {self.prefix}000.traj',
551 'was found. Should contain initial image',
552 )
554 # Find the images that exist
555 index_exists = [
556 i
557 for i in range(self.n_max)
558 if os.path.isfile('%s%03d.traj' % (self.prefix, i))
559 ]
561 n_cur = index_exists[-1] + 1
563 if self.world.rank == 0:
564 print(
565 'The NEB initially has %d images ' % len(index_exists),
566 '(including the end-points)',
567 )
568 if len(index_exists) == 1:
569 raise Exception('Only a start point exists')
571 for i in range(len(index_exists)):
572 if i != index_exists[i]:
573 raise Exception(
574 'Files must be ordered sequentially', 'without gaps.'
575 )
576 if self.world.rank == 0:
577 for i in index_exists:
578 filename_ref = self.iter_trajpath(i, 0)
579 if os.path.isfile(filename_ref):
580 try:
581 os.rename(filename_ref, str(filename_ref) + '.bak')
582 except OSError:
583 pass
584 filename = '%s%03d.traj' % (self.prefix, i)
585 try:
586 shutil.copy2(filename, filename_ref)
587 except OSError:
588 pass
589 # Wait for file system on all nodes is syncronized
590 self.world.barrier()
591 # And now lets read in the configurations
592 for i in range(n_cur):
593 if i in index_exists:
594 filename = '%s%03d.traj' % (self.prefix, i)
595 newim = read(filename)
596 self.all_images.append(newim)
597 else:
598 self.all_images.append(self.all_images[0].copy())
600 self.iteration = 0
601 return n_cur
603 def get_energies(self):
604 """Utility method to extract all energies and insert np.NaN at
605 invalid images."""
606 energies = []
607 for a in self.all_images:
608 try:
609 energies.append(a.get_potential_energy())
610 except RuntimeError:
611 energies.append(np.nan)
612 return energies
614 def get_energies_one_image(self, image):
615 """Utility method to extract energy of an image and return np.NaN
616 if invalid."""
617 try:
618 energy = image.get_potential_energy()
619 except RuntimeError:
620 energy = np.nan
621 return energy
623 def get_highest_energy_index(self):
624 """Find the index of the image with the highest energy."""
625 energies = self.get_energies()
626 valid_entries = [(i, e) for i, e in enumerate(energies) if e == e]
627 highest_energy_index = max(valid_entries, key=lambda x: x[1])[0]
628 return highest_energy_index
630 def which_images_to_run_on(self):
631 """Determine which set of images to do a NEB at.
632 The priority is to first include all images without valid energies,
633 secondly include the highest energy image."""
634 n_cur = len(self.all_images)
635 energies = self.get_energies()
636 # Find out which image is the first one missing the energy and
637 # which is the last one missing the energy
638 first_missing = n_cur
639 last_missing = 0
640 n_missing = 0
641 for i in range(1, n_cur - 1):
642 if energies[i] != energies[i]:
643 n_missing += 1
644 first_missing = min(first_missing, i)
645 last_missing = max(last_missing, i)
647 highest_energy_index = self.get_highest_energy_index()
649 nneb = highest_energy_index - 1 - self.n_simul // 2
650 nneb = max(nneb, 0)
651 nneb = min(nneb, n_cur - self.n_simul - 2)
652 nneb = min(nneb, first_missing - 1)
653 nneb = max(nneb + self.n_simul, last_missing) - self.n_simul
654 to_use = list(range(nneb, nneb + self.n_simul + 2))
656 while self.get_energies_one_image(
657 self.all_images[to_use[0]]
658 ) != self.get_energies_one_image(self.all_images[to_use[0]]):
659 to_use[0] -= 1
660 while self.get_energies_one_image(
661 self.all_images[to_use[-1]]
662 ) != self.get_energies_one_image(self.all_images[to_use[-1]]):
663 to_use[-1] += 1
665 return to_use, (highest_energy_index in to_use[1:-1])
668class seriel_writer:
669 def __init__(self, traj, i, num):
670 self.traj = traj
671 self.i = i
672 self.num = num
674 def write(self):
675 if self.num % (self.i + 1) == 0:
676 self.traj.write()
679def store_E_and_F_in_spc(self):
680 """Collect the energies and forces on all nodes and store as
681 single point calculators"""
682 # Make sure energies and forces are known on all nodes
683 self.get_forces()
684 images = self.images
685 if self.parallel:
686 energy = np.empty(1)
687 forces = np.empty((self.natoms, 3))
689 for i in range(1, self.nimages - 1):
690 # Determine which node is the leading for image i
691 root = (i - 1) * self.world.size // (self.nimages - 2)
692 # If on this node, extract the calculated numbers
693 if self.world.rank == root:
694 forces = images[i].get_forces()
695 energy[0] = images[i].get_potential_energy()
696 # Distribute these numbers to other nodes
697 self.world.broadcast(energy, root)
698 self.world.broadcast(forces, root)
699 # On all nodes, remove the calculator, keep only energy
700 # and force in single point calculator
701 self.images[i].calc = SinglePointCalculator(
702 self.images[i], energy=energy[0], forces=forces
703 )