Coverage for ase/optimize/minimahopping.py: 57.31%
499 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
3import numpy as np
5from ase import io, units
6from ase.md import MDLogger, VelocityVerlet, thermalize_momenta
7from ase.optimize import QuasiNewton
8from ase.parallel import paropen, world
11class MinimaHopping:
12 """Implements the minima hopping method of global optimization outlined
13 by S. Goedecker, J. Chem. Phys. 120: 9911 (2004). Initialize with an
14 ASE atoms object. Optional parameters are fed through keywords.
15 To run multiple searches in parallel, specify the minima_traj keyword,
16 and have each run point to the same path.
17 """
19 _default_settings = {
20 'T0': 1000.0, # K, initial MD 'temperature'
21 'beta1': 1.1, # temperature adjustment parameter
22 'beta2': 1.1, # temperature adjustment parameter
23 'beta3': 1.0 / 1.1, # temperature adjustment parameter
24 'Ediff0': 0.5, # eV, initial energy acceptance threshold
25 'alpha1': 0.98, # energy threshold adjustment parameter
26 'alpha2': 1.0 / 0.98, # energy threshold adjustment parameter
27 'mdmin': 2, # criteria to stop MD simulation (no. of minima)
28 'logfile': 'hop.log', # text log
29 'minima_threshold': 0.5, # A, threshold for identical configs
30 'timestep': 1.0, # fs, timestep for MD simulations
31 'optimizer': QuasiNewton, # local optimizer to use
32 'minima_traj': 'minima.traj', # storage file for minima list
33 'fmax': 0.05, # eV/A, max force for optimizations
34 'rng': None,
35 }
37 def __init__(self, atoms, comm=world, **kwargs):
38 """Initialize with an ASE atoms object and keyword arguments."""
39 self._atoms = atoms
40 for key in kwargs:
41 if key not in self._default_settings:
42 raise RuntimeError(f'Unknown keyword: {key}')
43 for k, v in self._default_settings.items():
44 setattr(self, f'_{k}', kwargs.pop(k, v))
46 # when a MD sim. has passed a local minimum:
47 self._passedminimum = PassedMinimum()
49 # Misc storage.
50 self._previous_optimum = None
51 self._previous_energy = None
52 self._temperature = self._T0
53 self._Ediff = self._Ediff0
54 self.comm = comm
56 def __call__(self, totalsteps=None, maxtemp=None):
57 """Run the minima hopping algorithm. Can specify stopping criteria
58 with total steps allowed or maximum searching temperature allowed.
59 If neither is specified, runs indefinitely (or until stopped by
60 batching software)."""
61 self._startup()
62 while True:
63 if totalsteps and self._counter >= totalsteps:
64 self._log(
65 'msg',
66 'Run terminated. Step #%i reached of '
67 '%i allowed. Increase totalsteps if resuming.'
68 % (self._counter, totalsteps),
69 )
70 return
71 if maxtemp and self._temperature >= maxtemp:
72 self._log(
73 'msg',
74 'Run terminated. Temperature is %.2f K;'
75 ' max temperature allowed %.2f K.'
76 % (self._temperature, maxtemp),
77 )
78 return
80 self._previous_optimum = self._atoms.copy()
81 self._previous_energy = self._atoms.get_potential_energy()
82 self._molecular_dynamics()
83 self._optimize()
84 self._counter += 1
85 self._check_results()
87 def _startup(self):
88 """Initiates a run, and determines if running from previous data or
89 a fresh run."""
91 status = np.array(-1.0)
92 exists = self._read_minima()
93 if self.comm.rank == 0:
94 if not exists:
95 # Fresh run with new minima file.
96 status = np.array(0.0)
97 elif not os.path.exists(self._logfile):
98 # Fresh run with existing or shared minima file.
99 status = np.array(1.0)
100 else:
101 # Must be resuming from within a working directory.
102 status = np.array(2.0)
103 self.comm.barrier()
104 self.comm.broadcast(status, 0)
106 if status == 2.0:
107 self._resume()
108 else:
109 self._counter = 0
110 self._log('init')
111 self._log('msg', 'Performing initial optimization.')
112 if status == 1.0:
113 self._log(
114 'msg',
115 'Using existing minima file with %i prior '
116 'minima: %s' % (len(self._minima), self._minima_traj),
117 )
118 self._optimize()
119 self._check_results()
120 self._counter += 1
122 def _resume(self):
123 """Attempt to resume a run, based on information in the log
124 file. Note it will almost always be interrupted in the middle of
125 either a qn or md run or when exceeding totalsteps, so it only has
126 been tested in those cases currently."""
127 with paropen(self._logfile, 'r', comm=self.comm) as fd:
128 lines = fd.read().splitlines()
130 self._log('msg', 'Attempting to resume stopped run.')
131 self._log(
132 'msg',
133 'Using existing minima file with %i prior '
134 'minima: %s' % (len(self._minima), self._minima_traj),
135 )
136 mdcount, qncount = 0, 0
137 for line in lines:
138 if (line[:4] == 'par:') and ('Ediff' not in line):
139 self._temperature = float(line.split()[1])
140 self._Ediff = float(line.split()[2])
141 elif line[:18] == 'msg: Optimization:':
142 qncount = int(line[19:].split('qn')[1])
143 elif line[:24] == 'msg: Molecular dynamics:':
144 mdcount = int(line[25:].split('md')[1])
145 self._counter = max((mdcount, qncount))
146 if qncount == mdcount:
147 # Either stopped during local optimization or terminated due to
148 # max steps.
149 self._log('msg', 'Attempting to resume at qn%05i' % qncount)
150 if qncount > 0:
151 atoms = io.read('qn%05i.traj' % (qncount - 1), index=-1)
152 self._previous_optimum = atoms.copy()
153 self._previous_energy = atoms.get_potential_energy()
154 if os.path.getsize('qn%05i.traj' % qncount) > 0:
155 atoms = io.read('qn%05i.traj' % qncount, index=-1)
156 else:
157 atoms = io.read('md%05i.traj' % qncount, index=-3)
158 self._atoms.positions = atoms.get_positions()
159 fmax = np.sqrt((atoms.get_forces() ** 2).sum(axis=1).max())
160 if fmax < self._fmax:
161 # Stopped after a qn finished.
162 self._log(
163 'msg',
164 'qn%05i fmax already less than fmax=%.3f'
165 % (qncount, self._fmax),
166 )
167 self._counter += 1
168 return
169 self._optimize()
170 self._counter += 1
171 if qncount > 0:
172 self._check_results()
173 else:
174 self._record_minimum()
175 self._log('msg', 'Found a new minimum.')
176 self._log('msg', 'Accepted new minimum.')
177 self._log('par')
178 elif qncount < mdcount:
179 # Probably stopped during molecular dynamics.
180 self._log('msg', 'Attempting to resume at md%05i.' % mdcount)
181 atoms = io.read('qn%05i.traj' % qncount, index=-1)
182 self._previous_optimum = atoms.copy()
183 self._previous_energy = atoms.get_potential_energy()
184 self._molecular_dynamics(resume=mdcount)
185 self._optimize()
186 self._counter += 1
187 self._check_results()
189 def _check_results(self):
190 """Adjusts parameters and positions based on outputs."""
192 # No prior minima found?
193 self._read_minima()
194 if len(self._minima) == 0:
195 self._log('msg', 'Found a new minimum.')
196 self._log('msg', 'Accepted new minimum.')
197 self._record_minimum()
198 self._log('par')
199 return
200 # Returned to starting position?
201 if self._previous_optimum:
202 compare = ComparePositions(translate=False)
203 dmax = compare(self._atoms, self._previous_optimum)
204 self._log('msg', 'Max distance to last minimum: %.3f A' % dmax)
205 if dmax < self._minima_threshold:
206 self._log('msg', 'Re-found last minimum.')
207 self._temperature *= self._beta1
208 self._log('par')
209 return
210 # In a previously found position?
211 unique, dmax_closest = self._unique_minimum_position()
212 self._log(
213 'msg', 'Max distance to closest minimum: %.3f A' % dmax_closest
214 )
215 if not unique:
216 self._temperature *= self._beta2
217 self._log('msg', 'Found previously found minimum.')
218 self._log('par')
219 if self._previous_optimum:
220 self._log('msg', 'Restoring last minimum.')
221 self._atoms.positions = self._previous_optimum.positions
222 return
223 # Must have found a unique minimum.
224 self._temperature *= self._beta3
225 self._log('msg', 'Found a new minimum.')
226 self._log('par')
227 if self._previous_energy is None or (
228 self._atoms.get_potential_energy()
229 < self._previous_energy + self._Ediff
230 ):
231 self._log('msg', 'Accepted new minimum.')
232 self._Ediff *= self._alpha1
233 self._log('par')
234 self._record_minimum()
235 else:
236 self._log(
237 'msg',
238 'Rejected new minimum due to energy. Restoring last minimum.',
239 )
240 self._atoms.positions = self._previous_optimum.positions
241 self._Ediff *= self._alpha2
242 self._log('par')
244 def _log(self, cat='msg', message=None):
245 """Records the message as a line in the log file."""
246 if cat == 'init':
247 if self.comm.rank == 0:
248 if os.path.exists(self._logfile):
249 raise RuntimeError(f'File exists: {self._logfile}')
250 with paropen(self._logfile, 'w', comm=self.comm) as fd:
251 fd.write(
252 'par: %12s %12s %12s\n' % ('T (K)', 'Ediff (eV)', 'mdmin')
253 )
254 fd.write(
255 'ene: %12s %12s %12s\n'
256 % ('E_current', 'E_previous', 'Difference')
257 )
258 return
259 with paropen(self._logfile, 'a', comm=self.comm) as fd:
260 if cat == 'msg':
261 line = f'msg: {message}'
262 elif cat == 'par':
263 line = 'par: %12.4f %12.4f %12i' % (
264 self._temperature,
265 self._Ediff,
266 self._mdmin,
267 )
268 elif cat == 'ene':
269 current = self._atoms.get_potential_energy()
270 if self._previous_optimum:
271 previous = self._previous_energy
272 line = 'ene: %12.5f %12.5f %12.5f' % (
273 current,
274 previous,
275 current - previous,
276 )
277 else:
278 line = 'ene: %12.5f' % current
279 fd.write(line + '\n')
281 def _optimize(self):
282 """Perform an optimization."""
283 self._atoms.set_momenta(np.zeros(self._atoms.get_momenta().shape))
284 with self._optimizer(
285 self._atoms,
286 trajectory='qn%05i.traj' % self._counter,
287 logfile='qn%05i.log' % self._counter,
288 ) as opt:
289 self._log('msg', 'Optimization: qn%05i' % self._counter)
290 opt.run(fmax=self._fmax)
291 self._log('ene')
293 def _record_minimum(self):
294 """Adds the current atoms configuration to the minima list."""
295 with io.Trajectory(self._minima_traj, 'a') as traj:
296 traj.write(self._atoms)
297 self._read_minima()
298 self._log('msg', 'Recorded minima #%i.' % (len(self._minima) - 1))
300 def _read_minima(self):
301 """Reads in the list of minima from the minima file."""
302 exists = os.path.exists(self._minima_traj)
303 if exists:
304 empty = os.path.getsize(self._minima_traj) == 0
305 if not empty:
306 with io.Trajectory(self._minima_traj, 'r') as traj:
307 self._minima = [atoms for atoms in traj]
308 else:
309 self._minima = []
310 return True
311 else:
312 self._minima = []
313 return False
315 def _molecular_dynamics(self, resume=None):
316 """Performs a molecular dynamics simulation, until mdmin is
317 exceeded. If resuming, the file number (md%05i) is expected."""
318 self._log('msg', 'Molecular dynamics: md%05i' % self._counter)
319 mincount = 0
320 energies, oldpositions = [], []
321 thermalized = False
322 if resume:
323 self._log('msg', 'Resuming MD from md%05i.traj' % resume)
324 if os.path.getsize('md%05i.traj' % resume) == 0:
325 self._log(
326 'msg',
327 'md%05i.traj is empty. Resuming from '
328 'qn%05i.traj.' % (resume, resume - 1),
329 )
330 atoms = io.read('qn%05i.traj' % (resume - 1), index=-1)
331 else:
332 with io.Trajectory('md%05i.traj' % resume, 'r') as images:
333 for atoms in images:
334 energies.append(atoms.get_potential_energy())
335 oldpositions.append(atoms.positions.copy())
336 passedmin = self._passedminimum(energies)
337 if passedmin:
338 mincount += 1
339 self._atoms.set_momenta(atoms.get_momenta())
340 thermalized = True
341 self._atoms.positions = atoms.get_positions()
342 self._log(
343 'msg', 'Starting MD with %i existing energies.' % len(energies)
344 )
345 if not thermalized:
346 thermalize_momenta(
347 self._atoms,
348 self._temperature,
349 exact_temperature=True,
350 rng=self._rng,
351 )
352 traj = io.Trajectory('md%05i.traj' % self._counter, 'a', self._atoms)
353 dyn = VelocityVerlet(self._atoms, timestep=self._timestep * units.fs)
354 log = MDLogger(
355 dyn,
356 self._atoms,
357 'md%05i.log' % self._counter,
358 header=True,
359 stress=False,
360 peratom=False,
361 )
363 with traj, dyn, log:
364 dyn.attach(log, interval=1)
365 dyn.attach(traj, interval=1)
366 while mincount < self._mdmin:
367 dyn.run(1)
368 energies.append(self._atoms.get_potential_energy())
369 passedmin = self._passedminimum(energies)
370 if passedmin:
371 mincount += 1
372 oldpositions.append(self._atoms.positions.copy())
373 # Reset atoms to minimum point.
374 self._atoms.positions = oldpositions[passedmin[0]]
376 def _unique_minimum_position(self):
377 """Identifies if the current position of the atoms, which should be
378 a local minima, has been found before."""
379 unique = True
380 dmax_closest = 99999.0
381 compare = ComparePositions(translate=True)
382 self._read_minima()
383 for minimum in self._minima:
384 dmax = compare(minimum, self._atoms)
385 if dmax < self._minima_threshold:
386 unique = False
387 if dmax < dmax_closest:
388 dmax_closest = dmax
389 return unique, dmax_closest
392class ComparePositions:
393 """Class that compares the atomic positions between two ASE atoms
394 objects. Returns the maximum distance that any atom has moved, assuming
395 all atoms of the same element are indistinguishable. If translate is
396 set to True, allows for arbitrary translations within the unit cell,
397 as well as translations across any periodic boundary conditions. When
398 called, returns the maximum displacement of any one atom."""
400 def __init__(self, translate=True):
401 self._translate = translate
403 def __call__(self, atoms1, atoms2):
404 atoms1 = atoms1.copy()
405 atoms2 = atoms2.copy()
406 if not self._translate:
407 dmax = self._indistinguishable_compare(atoms1, atoms2)
408 else:
409 dmax = self._translated_compare(atoms1, atoms2)
410 return dmax
412 def _translated_compare(self, atoms1, atoms2):
413 """Moves the atoms around and tries to pair up atoms, assuming any
414 atoms with the same symbol are indistinguishable, and honors
415 periodic boundary conditions (for example, so that an atom at
416 (0.1, 0., 0.) correctly is found to be close to an atom at
417 (7.9, 0., 0.) if the atoms are in an orthorhombic cell with
418 x-dimension of 8. Returns dmax, the maximum distance between any
419 two atoms in the optimal configuration."""
420 atoms1.set_constraint()
421 atoms2.set_constraint()
422 for index in range(3):
423 assert atoms1.pbc[index] == atoms2.pbc[index]
424 least = self._get_least_common(atoms1)
425 indices1 = [atom.index for atom in atoms1 if atom.symbol == least[0]]
426 indices2 = [atom.index for atom in atoms2 if atom.symbol == least[0]]
427 # Make comparison sets from atoms2, which contain repeated atoms in
428 # all pbc's and bring the atom listed in indices2 to (0,0,0)
429 comparisons = []
430 repeat = []
431 for bc in atoms2.pbc:
432 if bc:
433 repeat.append(3)
434 else:
435 repeat.append(1)
436 repeated = atoms2.repeat(repeat)
437 moved_cell = atoms2.cell * atoms2.pbc
438 for moved in moved_cell:
439 repeated.translate(-moved)
440 repeated.set_cell(atoms2.cell)
441 for index in indices2:
442 comparison = repeated.copy()
443 comparison.translate(-atoms2[index].position)
444 comparisons.append(comparison)
445 # Bring the atom listed in indices1 to (0,0,0) [not whole list]
446 standard = atoms1.copy()
447 standard.translate(-atoms1[indices1[0]].position)
448 # Compare the standard to the comparison sets.
449 dmaxes = []
450 for comparison in comparisons:
451 dmax = self._indistinguishable_compare(standard, comparison)
452 dmaxes.append(dmax)
453 return min(dmaxes)
455 def _get_least_common(self, atoms):
456 """Returns the least common element in atoms. If more than one,
457 returns the first encountered."""
458 symbols = [atom.symbol for atom in atoms]
459 least = ['', np.inf]
460 for element in set(symbols):
461 count = symbols.count(element)
462 if count < least[1]:
463 least = [element, count]
464 return least
466 def _indistinguishable_compare(self, atoms1, atoms2):
467 """Finds each atom in atoms1's nearest neighbor with the same
468 chemical symbol in atoms2. Return dmax, the farthest distance an
469 individual atom differs by."""
470 atoms2 = atoms2.copy() # allow deletion
471 atoms2.set_constraint()
472 dmax = 0.0
473 for atom1 in atoms1:
474 closest = [np.nan, np.inf]
475 for index, atom2 in enumerate(atoms2):
476 if atom2.symbol == atom1.symbol:
477 d = np.linalg.norm(atom1.position - atom2.position)
478 if d < closest[1]:
479 closest = [index, d]
480 if closest[1] > dmax:
481 dmax = closest[1]
482 del atoms2[closest[0]]
483 return dmax
486class PassedMinimum:
487 """Simple routine to find if a minimum in the potential energy surface
488 has been passed. In its default settings, a minimum is found if the
489 sequence ends with two downward points followed by two upward points.
490 Initialize with n_down and n_up, integer values of the number of up and
491 down points. If it has successfully determined it passed a minimum, it
492 returns the value (energy) of that minimum and the number of positions
493 back it occurred, otherwise returns None."""
495 def __init__(self, n_down=2, n_up=2):
496 self._ndown = n_down
497 self._nup = n_up
499 def __call__(self, energies):
500 if len(energies) < (self._nup + self._ndown + 1):
501 return None
502 status = True
503 index = -1
504 for _ in range(self._nup):
505 if energies[index] < energies[index - 1]:
506 status = False
507 index -= 1
508 for _ in range(self._ndown):
509 if energies[index] > energies[index - 1]:
510 status = False
511 index -= 1
512 if status:
513 return (-self._nup - 1), energies[-self._nup - 1]
516class MHPlot:
517 """Makes a plot summarizing the output of the MH algorithm from the
518 specified rundirectory. If no rundirectory is supplied, uses the
519 current directory."""
521 def __init__(self, rundirectory=None, logname='hop.log'):
522 if not rundirectory:
523 rundirectory = os.getcwd()
524 self._rundirectory = rundirectory
525 self._logname = logname
526 self._read_log()
527 self._fig, self._ax = self._makecanvas()
528 self._plot_data()
530 def get_figure(self):
531 """Returns the matplotlib figure object."""
532 return self._fig
534 def save_figure(self, filename):
535 """Saves the file to the specified path, with any allowed
536 matplotlib extension (e.g., .pdf, .png, etc.)."""
537 self._fig.savefig(filename)
539 def _read_log(self):
540 """Reads relevant parts of the log file."""
541 data = [] # format: [energy, status, temperature, ediff]
543 with open(os.path.join(self._rundirectory, self._logname)) as fd:
544 lines = fd.read().splitlines()
546 step_almost_over = False
547 step_over = False
548 for line in lines:
549 if line.startswith('msg: Molecular dynamics:'):
550 status = 'performing MD'
551 elif line.startswith('msg: Optimization:'):
552 status = 'performing QN'
553 elif line.startswith('ene:'):
554 status = 'local optimum reached'
555 energy = floatornan(line.split()[1])
556 elif line.startswith('msg: Accepted new minimum.'):
557 status = 'accepted'
558 step_almost_over = True
559 elif line.startswith('msg: Found previously found minimum.'):
560 status = 'previously found minimum'
561 step_almost_over = True
562 elif line.startswith('msg: Re-found last minimum.'):
563 status = 'previous minimum'
564 step_almost_over = True
565 elif line.startswith('msg: Rejected new minimum'):
566 status = 'rejected'
567 step_almost_over = True
568 elif line.startswith('par: '):
569 temperature = floatornan(line.split()[1])
570 ediff = floatornan(line.split()[2])
571 if step_almost_over:
572 step_over = True
573 step_almost_over = False
574 if step_over:
575 data.append([energy, status, temperature, ediff])
576 step_over = False
577 if data[-1][1] != status:
578 data.append([np.nan, status, temperature, ediff])
579 self._data = data
581 def _makecanvas(self):
582 from matplotlib import pyplot
583 from matplotlib.ticker import ScalarFormatter
585 fig = pyplot.figure(figsize=(6.0, 8.0))
586 lm, rm, bm, tm = 0.22, 0.02, 0.05, 0.04
587 vg1 = 0.01 # between adjacent energy plots
588 vg2 = 0.03 # between different types of plots
589 ratio = 2.0 # size of an energy plot to a parameter plot
590 figwidth = 1.0 - lm - rm
591 totalfigheight = 1.0 - bm - tm - vg1 - 2.0 * vg2
592 parfigheight = totalfigheight / (2.0 * ratio + 2)
593 epotheight = ratio * parfigheight
594 ax1 = fig.add_axes((lm, bm, figwidth, epotheight))
595 ax2 = fig.add_axes((lm, bm + epotheight + vg1, figwidth, epotheight))
596 for ax in [ax1, ax2]:
597 ax.yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
598 ediffax = fig.add_axes(
599 (lm, bm + 2.0 * epotheight + vg1 + vg2, figwidth, parfigheight)
600 )
601 tempax = fig.add_axes(
602 (
603 lm,
604 (bm + 2 * epotheight + vg1 + 2 * vg2 + parfigheight),
605 figwidth,
606 parfigheight,
607 )
608 )
609 for ax in [ax2, tempax, ediffax]:
610 ax.set_xticklabels([])
611 ax1.set_xlabel('step')
612 tempax.set_ylabel('$T$, K')
613 ediffax.set_ylabel(r'$E_\mathrm{diff}$, eV')
614 for ax in [ax1, ax2]:
615 ax.set_ylabel(r'$E_\mathrm{pot}$, eV')
616 ax = CombinedAxis(ax1, ax2, tempax, ediffax)
617 self._set_zoomed_range(ax)
618 ax1.spines['top'].set_visible(False)
619 ax2.spines['bottom'].set_visible(False)
620 return fig, ax
622 def _set_zoomed_range(self, ax):
623 """Try to intelligently set the range for the zoomed-in part of the
624 graph."""
625 energies = [line[0] for line in self._data if not np.isnan(line[0])]
626 dr = max(energies) - min(energies)
627 if dr == 0.0:
628 dr = 1.0
629 ax.set_ax1_range((min(energies) - 0.2 * dr, max(energies) + 0.2 * dr))
631 def _plot_data(self):
632 for step, line in enumerate(self._data):
633 self._plot_energy(step, line)
634 self._plot_qn(step, line)
635 self._plot_md(step, line)
636 self._plot_parameters()
637 self._ax.set_xlim(self._ax.ax1.get_xlim())
639 def _plot_energy(self, step, line):
640 """Plots energy and annotation for acceptance."""
641 energy, status = line[0], line[1]
642 if np.isnan(energy):
643 return
644 self._ax.plot(
645 [step, step + 0.5], [energy] * 2, '-', color='k', linewidth=2.0
646 )
647 if status == 'accepted':
648 self._ax.text(step + 0.51, energy, r'$\checkmark$')
649 elif status == 'rejected':
650 self._ax.text(step + 0.51, energy, r'$\Uparrow$', color='red')
651 elif status == 'previously found minimum':
652 self._ax.text(
653 step + 0.51,
654 energy,
655 r'$\hookleftarrow$',
656 color='red',
657 va='center',
658 )
659 elif status == 'previous minimum':
660 self._ax.text(
661 step + 0.51, energy, r'$\leftarrow$', color='red', va='center'
662 )
664 def _plot_md(self, step, line):
665 """Adds a curved plot of molecular dynamics trajectory."""
666 if step == 0:
667 return
668 energies = [self._data[step - 1][0]]
669 file = os.path.join(self._rundirectory, 'md%05i.traj' % step)
670 with io.Trajectory(file, 'r') as traj:
671 for atoms in traj:
672 energies.append(atoms.get_potential_energy())
673 xi = step - 1 + 0.5
674 if len(energies) > 2:
675 xf = xi + (step + 0.25 - xi) * len(energies) / (len(energies) - 2.0)
676 else:
677 xf = step
678 if xf > (step + 0.75):
679 xf = step
680 self._ax.plot(np.linspace(xi, xf, num=len(energies)), energies, '-k')
682 def _plot_qn(self, index, line):
683 """Plots a dashed vertical line for the optimization."""
684 if line[1] == 'performing MD':
685 return
686 file = os.path.join(self._rundirectory, 'qn%05i.traj' % index)
687 if os.path.getsize(file) == 0:
688 return
689 with io.Trajectory(file, 'r') as traj:
690 energies = [
691 traj[0].get_potential_energy(),
692 traj[-1].get_potential_energy(),
693 ]
694 if index > 0:
695 file = os.path.join(self._rundirectory, 'md%05i.traj' % index)
696 atoms = io.read(file, index=-3)
697 energies[0] = atoms.get_potential_energy()
698 self._ax.plot([index + 0.25] * 2, energies, ':k')
700 def _plot_parameters(self):
701 """Adds a plot of temperature and Ediff to the plot."""
702 steps, Ts, ediffs = [], [], []
703 for step, line in enumerate(self._data):
704 steps.extend([step + 0.5, step + 1.5])
705 Ts.extend([line[2]] * 2)
706 ediffs.extend([line[3]] * 2)
707 self._ax.tempax.plot(steps, Ts)
708 self._ax.ediffax.plot(steps, ediffs)
710 for ax in [self._ax.tempax, self._ax.ediffax]:
711 ylim = ax.get_ylim()
712 yrange = ylim[1] - ylim[0]
713 ax.set_ylim((ylim[0] - 0.1 * yrange, ylim[1] + 0.1 * yrange))
716def floatornan(value):
717 """Converts the argument into a float if possible, np.nan if not."""
718 try:
719 output = float(value)
720 except ValueError:
721 output = np.nan
722 return output
725class CombinedAxis:
726 """Helper class for MHPlot to plot on split y axis and adjust limits
727 simultaneously."""
729 def __init__(self, ax1, ax2, tempax, ediffax):
730 self.ax1 = ax1
731 self.ax2 = ax2
732 self.tempax = tempax
733 self.ediffax = ediffax
734 self._ymax = -np.inf
736 def set_ax1_range(self, ylim):
737 self._ax1_ylim = ylim
738 self.ax1.set_ylim(ylim)
740 def plot(self, *args, **kwargs):
741 self.ax1.plot(*args, **kwargs)
742 self.ax2.plot(*args, **kwargs)
743 # Re-adjust yrange
744 for yvalue in args[1]:
745 if yvalue > self._ymax:
746 self._ymax = yvalue
747 self.ax1.set_ylim(self._ax1_ylim)
748 self.ax2.set_ylim((self._ax1_ylim[1], self._ymax))
750 def set_xlim(self, *args):
751 self.ax1.set_xlim(*args)
752 self.ax2.set_xlim(*args)
753 self.tempax.set_xlim(*args)
754 self.ediffax.set_xlim(*args)
756 def text(self, *args, **kwargs):
757 y = args[1]
758 if y < self._ax1_ylim[1]:
759 ax = self.ax1
760 else:
761 ax = self.ax2
762 ax.text(*args, **kwargs)