Coverage for ase/mep/dimer.py: 71.72%

587 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1"""Minimum mode follower for finding saddle points in an unbiased way. 

2 

3There is, currently, only one implemented method: The Dimer method. 

4""" 

5 

6import sys 

7import time 

8import warnings 

9from math import atan, cos, degrees, pi, sin, sqrt, tan 

10from typing import Any 

11 

12import numpy as np 

13 

14from ase.calculators.singlepoint import SinglePointCalculator 

15from ase.optimize.optimize import OptimizableAtoms, Optimizer 

16from ase.parallel import world 

17from ase.utils import IOContext 

18 

19# Handy vector methods 

20norm = np.linalg.norm 

21 

22 

23class DimerOptimizable(OptimizableAtoms): 

24 def __init__(self, dimeratoms): 

25 self.dimeratoms = dimeratoms 

26 super().__init__(dimeratoms) 

27 

28 def converged(self, forces, fmax): 

29 forces_converged = super().converged(forces, fmax) 

30 return forces_converged and self.dimeratoms.get_curvature() < 0.0 

31 

32 

33def normalize(vector): 

34 """Create a unit vector along *vector*""" 

35 return vector / norm(vector) 

36 

37 

38def parallel_vector(vector, base): 

39 """Extract the components of *vector* that are parallel to *base*""" 

40 return np.vdot(vector, base) * base 

41 

42 

43def perpendicular_vector(vector, base): 

44 """Remove the components of *vector* that are parallel to *base*""" 

45 return vector - parallel_vector(vector, base) 

46 

47 

48def rotate_vectors(v1i, v2i, angle): 

49 """Rotate vectors *v1i* and *v2i* by *angle*""" 

50 cAng = cos(angle) 

51 sAng = sin(angle) 

52 v1o = v1i * cAng + v2i * sAng 

53 v2o = v2i * cAng - v1i * sAng 

54 # Ensure the length of the input and output vectors is equal 

55 return normalize(v1o) * norm(v1i), normalize(v2o) * norm(v2i) 

56 

57 

58class DimerEigenmodeSearch: 

59 """An implementation of the Dimer's minimum eigenvalue mode search. 

60 

61 This class implements the rotational part of the dimer saddle point 

62 searching method. 

63 

64 Parameters 

65 ---------- 

66 

67 atoms: MinModeAtoms object 

68 MinModeAtoms is an extension to the Atoms object, which includes 

69 information about the lowest eigenvalue mode. 

70 control: DimerControl object 

71 Contains the parameters necessary for the eigenmode search. 

72 If no control object is supplied a default DimerControl 

73 will be created and used. 

74 basis: list of xyz-values 

75 Eigenmode. Must be an ndarray of shape (n, 3). 

76 It is possible to constrain the eigenmodes to be orthogonal 

77 to this given eigenmode. 

78 

79 Notes 

80 ----- 

81 

82 The code is inspired, with permission, by code written by the Henkelman 

83 group, which can be found at http://theory.cm.utexas.edu/vtsttools/code/ 

84 

85 References 

86 ---------- 

87 

88 * Henkelman and Jonsson, JCP 111, 7010 (1999) 

89 * Olsen, Kroes, Henkelman, Arnaldsson, and Jonsson, JCP 121, 

90 9776 (2004). 

91 * Heyden, Bell, and Keil, JCP 123, 224101 (2005). 

92 * Kastner and Sherwood, JCP 128, 014106 (2008). 

93 

94 """ 

95 

96 def __init__( 

97 self, dimeratoms, control=None, eigenmode=None, basis=None, **kwargs 

98 ): 

99 if hasattr(dimeratoms, 'get_eigenmode'): 

100 self.dimeratoms = dimeratoms 

101 else: 

102 e = 'The atoms object must be a MinModeAtoms object' 

103 raise TypeError(e) 

104 self.basis = basis 

105 

106 if eigenmode is None: 

107 self.eigenmode = self.dimeratoms.get_eigenmode() 

108 else: 

109 self.eigenmode = eigenmode 

110 

111 if control is None: 

112 self.control = DimerControl(**kwargs) 

113 w = ( 

114 'Missing control object in ' 

115 + self.__class__.__name__ 

116 + '. Using default: DimerControl()' 

117 ) 

118 warnings.warn(w, UserWarning) 

119 if self.control.logfile is not None: 

120 self.control.logfile.write('DIM:WARN: ' + w + '\n') 

121 self.control.logfile.flush() 

122 else: 

123 self.control = control 

124 # kwargs must be empty if a control object is supplied 

125 for key in kwargs: 

126 e = f"__init__() got an unexpected keyword argument '{(key)}'" 

127 raise TypeError(e) 

128 

129 self.dR = self.control.get_parameter('dimer_separation') 

130 self.logfile = self.control.get_logfile() 

131 

132 def converge_to_eigenmode(self): 

133 """Perform an eigenmode search.""" 

134 self.set_up_for_eigenmode_search() 

135 stoprot = False 

136 

137 # Load the relevant parameters from control 

138 f_rot_min = self.control.get_parameter('f_rot_min') 

139 f_rot_max = self.control.get_parameter('f_rot_max') 

140 trial_angle = self.control.get_parameter('trial_angle') 

141 max_num_rot = self.control.get_parameter('max_num_rot') 

142 extrapolate = self.control.get_parameter('extrapolate_forces') 

143 

144 while not stoprot: 

145 if self.forces1E is None: 

146 self.update_virtual_forces() 

147 else: 

148 self.update_virtual_forces(extrapolated_forces=True) 

149 self.forces1A = self.forces1 

150 self.update_curvature() 

151 f_rot_A = self.get_rotational_force() 

152 

153 # Pre rotation stop criteria 

154 if norm(f_rot_A) <= f_rot_min: 

155 self.log(f_rot_A, None) 

156 stoprot = True 

157 else: 

158 n_A = self.eigenmode 

159 rot_unit_A = normalize(f_rot_A) 

160 

161 # Get the curvature and its derivative 

162 c0 = self.get_curvature() 

163 c0d = ( 

164 np.vdot((self.forces2 - self.forces1), rot_unit_A) / self.dR 

165 ) 

166 

167 # Trial rotation (no need to store the curvature) 

168 # NYI variable trial angles from [3] 

169 n_B, rot_unit_B = rotate_vectors(n_A, rot_unit_A, trial_angle) 

170 self.eigenmode = n_B 

171 self.update_virtual_forces() 

172 self.forces1B = self.forces1 

173 

174 # Get the curvature's derivative 

175 c1d = ( 

176 np.vdot((self.forces2 - self.forces1), rot_unit_B) / self.dR 

177 ) 

178 

179 # Calculate the Fourier coefficients 

180 a1 = c0d * cos(2 * trial_angle) - c1d / ( 

181 2 * sin(2 * trial_angle) 

182 ) 

183 b1 = 0.5 * c0d 

184 a0 = 2 * (c0 - a1) 

185 

186 # Estimate the rotational angle 

187 rotangle = atan(b1 / a1) / 2.0 

188 

189 # Make sure that you didn't find a maximum 

190 cmin = ( 

191 a0 / 2.0 + a1 * cos(2 * rotangle) + b1 * sin(2 * rotangle) 

192 ) 

193 if c0 < cmin: 

194 rotangle += pi / 2.0 

195 

196 # Rotate into the (hopefully) lowest eigenmode 

197 # NYI Conjugate gradient rotation 

198 n_min, _dummy = rotate_vectors(n_A, rot_unit_A, rotangle) 

199 self.update_eigenmode(n_min) 

200 

201 # Store the curvature estimate instead of the old curvature 

202 self.update_curvature(cmin) 

203 

204 self.log(f_rot_A, rotangle) 

205 

206 # Force extrapolation scheme from [4] 

207 if extrapolate: 

208 self.forces1E = ( 

209 sin(trial_angle - rotangle) 

210 / sin(trial_angle) 

211 * self.forces1A 

212 + sin(rotangle) / sin(trial_angle) * self.forces1B 

213 + ( 

214 1 

215 - cos(rotangle) 

216 - sin(rotangle) * tan(trial_angle / 2.0) 

217 ) 

218 * self.forces0 

219 ) 

220 else: 

221 self.forces1E = None 

222 

223 # Post rotation stop criteria 

224 if not stoprot: 

225 if self.control.get_counter('rotcount') >= max_num_rot: 

226 stoprot = True 

227 elif norm(f_rot_A) <= f_rot_max: 

228 stoprot = True 

229 

230 def log(self, f_rot_A, angle): 

231 """Log each rotational step.""" 

232 # NYI Log for the trial angle 

233 if self.logfile is not None: 

234 if angle: 

235 l = 'DIM:ROT: %7d %9d %9.4f %9.4f %9.4f\n' % ( 

236 self.control.get_counter('optcount'), 

237 self.control.get_counter('rotcount'), 

238 self.get_curvature(), 

239 degrees(angle), 

240 norm(f_rot_A), 

241 ) 

242 else: 

243 l = 'DIM:ROT: %7d %9d %9.4f %9s %9.4f\n' % ( 

244 self.control.get_counter('optcount'), 

245 self.control.get_counter('rotcount'), 

246 self.get_curvature(), 

247 '---------', 

248 norm(f_rot_A), 

249 ) 

250 self.logfile.write(l) 

251 

252 def get_rotational_force(self): 

253 """Calculate the rotational force that acts on the dimer.""" 

254 rot_force = perpendicular_vector( 

255 (self.forces1 - self.forces2), self.eigenmode 

256 ) / (2.0 * self.dR) 

257 if self.basis is not None: 

258 if ( 

259 len(self.basis) == len(self.dimeratoms) 

260 and len(self.basis[0]) == 3 

261 and isinstance(self.basis[0][0], float) 

262 ): 

263 rot_force = perpendicular_vector(rot_force, self.basis) 

264 else: 

265 for base in self.basis: 

266 rot_force = perpendicular_vector(rot_force, base) 

267 return rot_force 

268 

269 def update_curvature(self, curv=None): 

270 """Update the curvature in the MinModeAtoms object.""" 

271 if curv: 

272 self.curvature = curv 

273 else: 

274 self.curvature = np.vdot( 

275 (self.forces2 - self.forces1), self.eigenmode 

276 ) / (2.0 * self.dR) 

277 

278 def update_eigenmode(self, eigenmode): 

279 """Update the eigenmode in the MinModeAtoms object.""" 

280 self.eigenmode = eigenmode 

281 self.update_virtual_positions() 

282 self.control.increment_counter('rotcount') 

283 

284 def get_eigenmode(self): 

285 """Returns the current eigenmode.""" 

286 return self.eigenmode 

287 

288 def get_curvature(self): 

289 """Returns the curvature along the current eigenmode.""" 

290 return self.curvature 

291 

292 def get_control(self): 

293 """Return the control object.""" 

294 return self.control 

295 

296 def update_center_forces(self): 

297 """Get the forces at the center of the dimer.""" 

298 self.dimeratoms.set_positions(self.pos0) 

299 self.forces0 = self.dimeratoms.get_forces(real=True) 

300 self.energy0 = self.dimeratoms.get_potential_energy() 

301 

302 def update_virtual_forces(self, extrapolated_forces=False): 

303 """Get the forces at the endpoints of the dimer.""" 

304 self.update_virtual_positions() 

305 

306 # Estimate / Calculate the forces at pos1 

307 if extrapolated_forces: 

308 self.forces1 = self.forces1E.copy() 

309 else: 

310 self.forces1 = self.dimeratoms.get_forces(real=True, pos=self.pos1) 

311 

312 # Estimate / Calculate the forces at pos2 

313 if self.control.get_parameter('use_central_forces'): 

314 self.forces2 = 2 * self.forces0 - self.forces1 

315 else: 

316 self.forces2 = self.dimeratoms.get_forces(real=True, pos=self.pos2) 

317 

318 def update_virtual_positions(self): 

319 """Update the end point positions.""" 

320 self.pos1 = self.pos0 + self.eigenmode * self.dR 

321 self.pos2 = self.pos0 - self.eigenmode * self.dR 

322 

323 def set_up_for_eigenmode_search(self): 

324 """Before eigenmode search, prepare for rotation.""" 

325 self.pos0 = self.dimeratoms.get_positions() 

326 self.update_center_forces() 

327 self.update_virtual_positions() 

328 self.control.reset_counter('rotcount') 

329 self.forces1E = None 

330 

331 def set_up_for_optimization_step(self): 

332 """At the end of rotation, prepare for displacement of the dimer.""" 

333 self.dimeratoms.set_positions(self.pos0) 

334 self.forces1E = None 

335 

336 

337class MinModeControl(IOContext): 

338 """A parent class for controlling minimum mode saddle point searches. 

339 

340 Method specific control classes inherit this one. The only thing 

341 inheriting classes need to implement are the log() method and 

342 the *parameters* class variable with default values for ALL 

343 parameters needed by the method in question. 

344 When instantiating control classes default parameter values can 

345 be overwritten. 

346 

347 """ 

348 

349 parameters: dict[str, Any] = {} 

350 

351 def __init__( 

352 self, logfile='-', eigenmode_logfile=None, comm=world, **kwargs 

353 ): 

354 # Overwrite the defaults with the input parameters given 

355 for key in kwargs: 

356 if key not in self.parameters: 

357 e = ( 

358 f'Invalid parameter >>{key}<< with value >>' 

359 f'{kwargs[key]!s}<< in {self.__class__.__name__}' 

360 ) 

361 raise ValueError(e) 

362 else: 

363 self.set_parameter(key, kwargs[key], log=False) 

364 

365 self.initialize_logfiles( 

366 comm=comm, logfile=logfile, eigenmode_logfile=eigenmode_logfile 

367 ) 

368 self.counters = {'forcecalls': 0, 'rotcount': 0, 'optcount': 0} 

369 self.log() 

370 

371 def initialize_logfiles(self, comm, logfile=None, eigenmode_logfile=None): 

372 self.logfile = self.openfile(file=logfile, comm=comm) 

373 self.eigenmode_logfile = self.openfile( 

374 file=eigenmode_logfile, comm=comm 

375 ) 

376 

377 def log(self, parameter=None): 

378 """Log the parameters of the eigenmode search.""" 

379 

380 def set_parameter(self, parameter, value, log=True): 

381 """Change a parameter's value.""" 

382 if parameter not in self.parameters: 

383 e = f'Invalid parameter >>{parameter}<< with value >>{value!s}<<' 

384 raise ValueError(e) 

385 self.parameters[parameter] = value 

386 if log: 

387 self.log(parameter) 

388 

389 def get_parameter(self, parameter): 

390 """Returns the value of a parameter.""" 

391 if parameter not in self.parameters: 

392 e = f'Invalid parameter >>{(parameter)}<<' 

393 raise ValueError(e) 

394 return self.parameters[parameter] 

395 

396 def get_logfile(self): 

397 """Returns the log file.""" 

398 return self.logfile 

399 

400 def get_eigenmode_logfile(self): 

401 """Returns the eigenmode log file.""" 

402 return self.eigenmode_logfile 

403 

404 def get_counter(self, counter): 

405 """Returns a given counter.""" 

406 return self.counters[counter] 

407 

408 def increment_counter(self, counter): 

409 """Increment a given counter.""" 

410 self.counters[counter] += 1 

411 

412 def reset_counter(self, counter): 

413 """Reset a given counter.""" 

414 self.counters[counter] = 0 

415 

416 def reset_all_counters(self): 

417 """Reset all counters.""" 

418 for key in self.counters: 

419 self.counters[key] = 0 

420 

421 

422class DimerControl(MinModeControl): 

423 """A class that takes care of the parameters needed for a Dimer search. 

424 

425 Parameters 

426 ---------- 

427 

428 eigenmode_method: str 

429 The name of the eigenmode search method. 

430 f_rot_min: float 

431 Size of the rotational force under which no rotation will be 

432 performed. 

433 f_rot_max: float 

434 Size of the rotational force under which only one rotation will be 

435 performed. 

436 max_num_rot: int 

437 Maximum number of rotations per optimizer step. 

438 trial_angle: float 

439 Trial angle for the finite difference estimate of the rotational 

440 angle in radians. 

441 trial_trans_step: float 

442 Trial step size for the MinModeTranslate optimizer. 

443 maximum_translation: float 

444 Maximum step size and forced step size when the curvature is still 

445 positive for the MinModeTranslate optimizer. 

446 cg_translation: bool 

447 Conjugate Gradient for the MinModeTranslate optimizer. 

448 use_central_forces: bool 

449 Only calculate the forces at one end of the dimer and extrapolate 

450 the forces to the other. 

451 dimer_separation: float 

452 Separation of the dimer's images. 

453 initial_eigenmode_method: str 

454 How to construct the initial eigenmode of the dimer. If an eigenmode 

455 is given when creating the MinModeAtoms object, this will be ignored. 

456 Possible choices are: 'gauss' and 'displacement' 

457 extrapolate_forces: bool 

458 When more than one rotation is performed, an extrapolation scheme can 

459 be used to reduce the number of force evaluations. 

460 displacement_method: str 

461 How to displace the atoms. Possible choices are 'gauss' and 'vector'. 

462 gauss_std: float 

463 The standard deviation of the gauss curve used when doing random 

464 displacement. 

465 order: int 

466 How many lowest eigenmodes will be inverted. 

467 mask: list of bool 

468 Which atoms will be moved during displacement. 

469 displacement_center: int or [float, float, float] 

470 The center of displacement, nearby atoms will be displaced. 

471 displacement_radius: float 

472 When choosing which atoms to displace with the *displacement_center* 

473 keyword, this decides how many nearby atoms to displace. 

474 number_of_displacement_atoms: int 

475 The amount of atoms near *displacement_center* to displace. 

476 

477 """ 

478 

479 # Default parameters for the Dimer eigenmode search 

480 parameters = { 

481 'eigenmode_method': 'dimer', 

482 'f_rot_min': 0.1, 

483 'f_rot_max': 1.00, 

484 'max_num_rot': 1, 

485 'trial_angle': pi / 4.0, 

486 'trial_trans_step': 0.001, 

487 'maximum_translation': 0.1, 

488 'cg_translation': True, 

489 'use_central_forces': True, 

490 'dimer_separation': 0.0001, 

491 'initial_eigenmode_method': 'gauss', 

492 'extrapolate_forces': False, 

493 'displacement_method': 'gauss', 

494 'gauss_std': 0.1, 

495 'order': 1, 

496 'mask': None, # NB mask should not be a "parameter" 

497 'displacement_center': None, 

498 'displacement_radius': None, 

499 'number_of_displacement_atoms': None, 

500 } 

501 

502 # NB: Can maybe put this in EigenmodeSearch and MinModeControl 

503 def log(self, parameter=None): 

504 """Log the parameters of the eigenmode search.""" 

505 if self.logfile is not None: 

506 if parameter is not None: 

507 l = 'DIM:CONTROL: Updated Parameter: {} = {}\n'.format( 

508 parameter, str(self.get_parameter(parameter)) 

509 ) 

510 else: 

511 l = 'MINMODE:METHOD: Dimer\n' 

512 l += 'DIM:CONTROL: Search Parameters:\n' 

513 l += 'DIM:CONTROL: ------------------\n' 

514 for key in self.parameters: 

515 l += 'DIM:CONTROL: {} = {}\n'.format( 

516 key, str(self.get_parameter(key)) 

517 ) 

518 l += 'DIM:CONTROL: ------------------\n' 

519 l += ( 

520 'DIM:ROT: OPT-STEP ROT-STEP CURVATURE ROT-ANGLE ' 

521 + 'ROT-FORCE\n' 

522 ) 

523 self.logfile.write(l) 

524 self.logfile.flush() 

525 

526 

527class MinModeAtoms: 

528 """Wrapper for Atoms with information related to minimum mode searching. 

529 

530 Contains an Atoms object and pipes all unknown function calls to that 

531 object. 

532 Other information that is stored in this object are the estimate for 

533 the lowest eigenvalue, *curvature*, and its corresponding eigenmode, 

534 *eigenmode*. Furthermore, the original configuration of the Atoms 

535 object is stored for use in multiple minimum mode searches. 

536 The forces on the system are modified by inverting the component 

537 along the eigenmode estimate. This eventually brings the system to 

538 a saddle point. 

539 

540 [1]_ [2]_ [3]_ [4]_ 

541 

542 Parameters 

543 ---------- 

544 

545 atoms : Atoms object 

546 A regular Atoms object 

547 control : MinModeControl object 

548 Contains the parameters necessary for the eigenmode search. 

549 If no control object is supplied a default DimerControl 

550 will be created and used. 

551 mask: list of bool 

552 Determines which atoms will be moved when calling displace() 

553 random_seed: int 

554 The seed used for the random number generator. Defaults to 

555 modified version the current time. 

556 

557 References 

558 ---------- 

559 .. [1] Henkelman and Jonsson, JCP 111, 7010 (1999) 

560 .. [2] Olsen, Kroes, Henkelman, Arnaldsson, and Jonsson, JCP 121, 

561 9776 (2004). 

562 .. [3] Heyden, Bell, and Keil, JCP 123, 224101 (2005). 

563 .. [4] Kastner and Sherwood, JCP 128, 014106 (2008). 

564 

565 """ 

566 

567 def __init__( 

568 self, 

569 atoms, 

570 control=None, 

571 eigenmodes=None, 

572 random_seed=None, 

573 comm=world, 

574 **kwargs, 

575 ): 

576 self.minmode_init = True 

577 self.atoms = atoms 

578 

579 # Initialize to None to avoid strange behaviour due to __getattr__ 

580 self.eigenmodes = eigenmodes 

581 self.curvatures = None 

582 

583 if control is None: 

584 self.control = DimerControl(**kwargs) 

585 w = ( 

586 'Missing control object in ' 

587 + self.__class__.__name__ 

588 + '. Using default: DimerControl()' 

589 ) 

590 warnings.warn(w, UserWarning) 

591 if self.control.logfile is not None: 

592 self.control.logfile.write('DIM:WARN: ' + w + '\n') 

593 self.control.logfile.flush() 

594 else: 

595 self.control = control 

596 logfile = self.control.get_logfile() 

597 mlogfile = self.control.get_eigenmode_logfile() 

598 for key in kwargs: 

599 if key == 'logfile': 

600 logfile = kwargs[key] 

601 elif key == 'eigenmode_logfile': 

602 mlogfile = kwargs[key] 

603 else: 

604 self.control.set_parameter(key, kwargs[key]) 

605 self.control.initialize_logfiles( 

606 comm=comm, logfile=logfile, eigenmode_logfile=mlogfile 

607 ) 

608 

609 # Seed the randomness 

610 if random_seed is None: 

611 t = time.time() 

612 if world.size > 1: 

613 t = world.sum(t) / world.size 

614 # Harvest the latter part of the current time 

615 random_seed = int(('%30.9f' % t)[-9:]) 

616 self.random_state = np.random.RandomState(random_seed) 

617 

618 # Check the order 

619 self.order = self.control.get_parameter('order') 

620 

621 # Construct the curvatures list 

622 self.curvatures = [100.0] * self.order 

623 

624 # Save the original state of the atoms. 

625 self.atoms0 = self.atoms.copy() 

626 self.save_original_forces() 

627 

628 # Get a reference to the log files 

629 self.logfile = self.control.get_logfile() 

630 self.mlogfile = self.control.get_eigenmode_logfile() 

631 

632 def __ase_optimizable__(self): 

633 return DimerOptimizable(self) 

634 

635 def save_original_forces(self, force_calculation=False): 

636 """Store the forces (and energy) of the original state.""" 

637 # NB: Would be nice if atoms.copy() took care of this. 

638 if self.calc is not None: 

639 # Hack because some calculators do not have calculation_required 

640 if ( 

641 hasattr(self.calc, 'calculation_required') 

642 and not self.calc.calculation_required( 

643 self.atoms, ['energy', 'forces'] 

644 ) 

645 ) or force_calculation: 

646 calc = SinglePointCalculator( 

647 self.atoms0, 

648 energy=self.atoms.get_potential_energy(), 

649 forces=self.atoms.get_forces(), 

650 ) 

651 self.atoms0.calc = calc 

652 

653 def initialize_eigenmodes( 

654 self, method=None, eigenmodes=None, gauss_std=None 

655 ): 

656 """Make an initial guess for the eigenmode.""" 

657 if eigenmodes is None: 

658 pos = self.get_positions() 

659 old_pos = self.get_original_positions() 

660 if method is None: 

661 method = self.control.get_parameter('initial_eigenmode_method') 

662 if method.lower() == 'displacement' and (pos - old_pos).any(): 

663 eigenmode = normalize(pos - old_pos) 

664 elif method.lower() == 'gauss': 

665 self.displace(log=False, gauss_std=gauss_std, method=method) 

666 new_pos = self.get_positions() 

667 eigenmode = normalize(new_pos - pos) 

668 self.set_positions(pos) 

669 else: 

670 e = ( 

671 "initial_eigenmode must use either 'gauss' or " 

672 + "'displacement', if the latter is used the atoms " 

673 + 'must have moved away from the original positions.' 

674 + f"You have requested '{method}'." 

675 ) 

676 raise NotImplementedError(e) # NYI 

677 eigenmodes = [eigenmode] 

678 

679 # Create random higher order mode guesses 

680 if self.order > 1: 

681 if len(eigenmodes) == 1: 

682 for _ in range(1, self.order): 

683 pos = self.get_positions() 

684 self.displace(log=False, gauss_std=gauss_std, method=method) 

685 new_pos = self.get_positions() 

686 eigenmode = normalize(new_pos - pos) 

687 self.set_positions(pos) 

688 eigenmodes += [eigenmode] 

689 

690 self.eigenmodes = eigenmodes 

691 # Ensure that the higher order mode guesses are all orthogonal 

692 if self.order > 1: 

693 for k in range(self.order): 

694 self.ensure_eigenmode_orthogonality(k) 

695 self.eigenmode_log() 

696 

697 # NB maybe this name might be confusing in context to 

698 # calc.calculation_required() 

699 def calculation_required(self): 

700 """Check if a calculation is required.""" 

701 return self.minmode_init or self.check_atoms != self.atoms 

702 

703 def calculate_real_forces_and_energies(self, **kwargs): 

704 """Calculate and store the potential energy and forces.""" 

705 if self.minmode_init: 

706 self.minmode_init = False 

707 self.initialize_eigenmodes(eigenmodes=self.eigenmodes) 

708 self.rotation_required = True 

709 self.forces0 = self.atoms.get_forces(**kwargs) 

710 self.energy0 = self.atoms.get_potential_energy() 

711 self.control.increment_counter('forcecalls') 

712 self.check_atoms = self.atoms.copy() 

713 

714 def get_potential_energy(self): 

715 """Return the potential energy.""" 

716 if self.calculation_required(): 

717 self.calculate_real_forces_and_energies() 

718 return self.energy0 

719 

720 def get_forces(self, real=False, pos=None, **kwargs): 

721 """Return the forces, projected or real.""" 

722 if self.calculation_required() and pos is None: 

723 self.calculate_real_forces_and_energies(**kwargs) 

724 if real and pos is None: 

725 return self.forces0 

726 elif real and pos is not None: 

727 old_pos = self.atoms.get_positions() 

728 self.atoms.set_positions(pos) 

729 forces = self.atoms.get_forces() 

730 self.control.increment_counter('forcecalls') 

731 self.atoms.set_positions(old_pos) 

732 return forces 

733 else: 

734 if self.rotation_required: 

735 self.find_eigenmodes(order=self.order) 

736 self.eigenmode_log() 

737 self.rotation_required = False 

738 self.control.increment_counter('optcount') 

739 return self.get_projected_forces() 

740 

741 def ensure_eigenmode_orthogonality(self, order): 

742 mode = self.eigenmodes[order - 1].copy() 

743 for k in range(order - 1): 

744 mode = perpendicular_vector(mode, self.eigenmodes[k]) 

745 self.eigenmodes[order - 1] = normalize(mode) 

746 

747 def find_eigenmodes(self, order=1): 

748 """Launch eigenmode searches.""" 

749 if self.control.get_parameter('eigenmode_method').lower() != 'dimer': 

750 e = 'Only the Dimer control object has been implemented.' 

751 raise NotImplementedError(e) # NYI 

752 for k in range(order): 

753 if k > 0: 

754 self.ensure_eigenmode_orthogonality(k + 1) 

755 search = DimerEigenmodeSearch( 

756 self, 

757 self.control, 

758 eigenmode=self.eigenmodes[k], 

759 basis=self.eigenmodes[:k], 

760 ) 

761 search.converge_to_eigenmode() 

762 search.set_up_for_optimization_step() 

763 self.eigenmodes[k] = search.get_eigenmode() 

764 self.curvatures[k] = search.get_curvature() 

765 

766 def get_projected_forces(self, pos=None): 

767 """Return the projected forces.""" 

768 if pos is not None: 

769 forces = self.get_forces(real=True, pos=pos).copy() 

770 else: 

771 forces = self.forces0.copy() 

772 

773 # Loop through all the eigenmodes 

774 # NB: Can this be done with a linear combination, instead? 

775 for k, mode in enumerate(self.eigenmodes): 

776 # NYI This If statement needs to be overridable in the control 

777 if self.get_curvature(order=k) > 0.0 and self.order == 1: 

778 forces = -parallel_vector(forces, mode) 

779 else: 

780 forces -= 2 * parallel_vector(forces, mode) 

781 return forces 

782 

783 def restore_original_positions(self): 

784 """Restore the MinModeAtoms object positions to the original state.""" 

785 self.atoms.set_positions(self.get_original_positions()) 

786 

787 def get_barrier_energy(self): 

788 """The energy difference between the current and original states""" 

789 try: 

790 original_energy = self.get_original_potential_energy() 

791 dimer_energy = self.get_potential_energy() 

792 return dimer_energy - original_energy 

793 except RuntimeError: 

794 w = ( 

795 'The potential energy is not available, without further ' 

796 + 'calculations, most likely at the original state.' 

797 ) 

798 warnings.warn(w, UserWarning) 

799 return np.nan 

800 

801 def get_control(self): 

802 """Return the control object.""" 

803 return self.control 

804 

805 def get_curvature(self, order='max'): 

806 """Return the eigenvalue estimate.""" 

807 if order == 'max': 

808 return max(self.curvatures) 

809 else: 

810 return self.curvatures[order - 1] 

811 

812 def get_eigenmode(self, order=1): 

813 """Return the current eigenmode guess.""" 

814 return self.eigenmodes[order - 1] 

815 

816 def get_atoms(self): 

817 """Return the unextended Atoms object.""" 

818 return self.atoms 

819 

820 def set_atoms(self, atoms): 

821 """Set a new Atoms object""" 

822 self.atoms = atoms 

823 

824 def set_eigenmode(self, eigenmode, order=1): 

825 """Set the eigenmode guess.""" 

826 self.eigenmodes[order - 1] = eigenmode 

827 

828 def set_curvature(self, curvature, order=1): 

829 """Set the eigenvalue estimate.""" 

830 self.curvatures[order - 1] = curvature 

831 

832 # Pipe all the stuff from Atoms that is not overwritten. 

833 # Pipe all requests for get_original_* to self.atoms0. 

834 def __getattr__(self, attr): 

835 """Return any value of the Atoms object""" 

836 if 'original' in attr.split('_'): 

837 attr = attr.replace('_original_', '_') 

838 return getattr(self.atoms0, attr) 

839 else: 

840 return getattr(self.atoms, attr) 

841 

842 def __len__(self): 

843 return len(self.atoms) 

844 

845 def displace( 

846 self, 

847 displacement_vector=None, 

848 mask=None, 

849 method=None, 

850 displacement_center=None, 

851 radius=None, 

852 number_of_atoms=None, 

853 gauss_std=None, 

854 mic=True, 

855 log=True, 

856 ): 

857 """Move the atoms away from their current position. 

858 

859 This is one of the essential parts of minimum mode searches. 

860 The parameters can all be set in the control object and overwritten 

861 when this method is run, apart from *displacement_vector*. 

862 It is preferred to modify the control values rather than those here 

863 in order for the correct ones to show up in the log file. 

864 

865 *method* can be either 'gauss' for random displacement or 'vector' 

866 to perform a predefined displacement. 

867 

868 *gauss_std* is the standard deviation of the gauss curve that is 

869 used for random displacement. 

870 

871 *displacement_center* can be either the number of an atom or a 3D 

872 position. It must be accompanied by a *radius* (all atoms within it 

873 will be displaced) or a *number_of_atoms* which decides how many of 

874 the closest atoms will be displaced. 

875 

876 *mic* controls the usage of the Minimum Image Convention. 

877 

878 If both *mask* and *displacement_center* are used, the atoms marked 

879 as False in the *mask* will not be affected even though they are 

880 within reach of the *displacement_center*. 

881 

882 The parameters priority order: 

883 1) displacement_vector 

884 2) mask 

885 3) displacement_center (with radius and/or number_of_atoms) 

886 

887 If both *radius* and *number_of_atoms* are supplied with 

888 *displacement_center*, only atoms that fulfill both criteria will 

889 be displaced. 

890 

891 """ 

892 

893 # Fetch the default values from the control 

894 if mask is None: 

895 mask = self.control.get_parameter('mask') 

896 if method is None: 

897 method = self.control.get_parameter('displacement_method') 

898 if gauss_std is None: 

899 gauss_std = self.control.get_parameter('gauss_std') 

900 if displacement_center is None: 

901 displacement_center = self.control.get_parameter( 

902 'displacement_center' 

903 ) 

904 if radius is None: 

905 radius = self.control.get_parameter('displacement_radius') 

906 if number_of_atoms is None: 

907 number_of_atoms = self.control.get_parameter( 

908 'number_of_displacement_atoms' 

909 ) 

910 

911 # Check for conflicts 

912 if displacement_vector is not None and method.lower() != 'vector': 

913 e = ( 

914 'displacement_vector was supplied but a different method ' 

915 + f"('{method!s}') was chosen.\n" 

916 ) 

917 raise ValueError(e) 

918 elif displacement_vector is None and method.lower() == 'vector': 

919 e = ( 

920 'A displacement_vector must be supplied when using ' 

921 + f"method = '{method!s}'.\n" 

922 ) 

923 raise ValueError(e) 

924 elif ( 

925 displacement_center is not None 

926 and radius is None 

927 and number_of_atoms is None 

928 ): 

929 e = ( 

930 'When displacement_center is chosen, either radius or ' 

931 + 'number_of_atoms must be supplied.\n' 

932 ) 

933 raise ValueError(e) 

934 

935 # Set up the center of displacement mask (c_mask) 

936 if displacement_center is not None: 

937 c = displacement_center 

938 # Construct a distance list 

939 # The center is an atom 

940 if isinstance(c, int): 

941 # Parse negative indexes 

942 c = displacement_center % len(self) 

943 d = [ 

944 (k, self.get_distance(k, c, mic=mic)) 

945 for k in range(len(self)) 

946 ] 

947 # The center is a position in 3D space 

948 elif len(c) == 3 and [type(c_k) for c_k in c] == [float] * 3: 

949 # NB: MIC is not considered. 

950 d = [ 

951 (k, norm(self.get_positions()[k] - c)) 

952 for k in range(len(self)) 

953 ] 

954 else: 

955 e = ( 

956 'displacement_center must be either the number of an ' 

957 + 'atom in MinModeAtoms object or a 3D position ' 

958 + '(3-tuple of floats).' 

959 ) 

960 raise ValueError(e) 

961 

962 # Set up the mask 

963 if radius is not None: 

964 r_mask = [dist[1] < radius for dist in d] 

965 else: 

966 r_mask = [True for _ in range(len(self))] 

967 

968 if number_of_atoms is not None: 

969 d_sorted = [n[0] for n in sorted(d, key=lambda k: k[1])] 

970 n_nearest = d_sorted[:number_of_atoms] 

971 n_mask = [k in n_nearest for k in range(len(self))] 

972 else: 

973 n_mask = [True for _ in range(len(self))] 

974 

975 # Resolve n_mask / r_mask conflicts 

976 c_mask = [n_mask[k] and r_mask[k] for k in range(len(self))] 

977 else: 

978 c_mask = None 

979 

980 # Set up a True mask if there is no mask supplied 

981 if mask is None: 

982 mask = [True for _ in range(len(self))] 

983 if c_mask is None: 

984 w = ( 

985 'It was not possible to figure out which atoms to ' 

986 + 'displace, Will try to displace all atoms.\n' 

987 ) 

988 warnings.warn(w, UserWarning) 

989 if self.logfile is not None: 

990 self.logfile.write('MINMODE:WARN: ' + w + '\n') 

991 self.logfile.flush() 

992 

993 # Resolve mask / c_mask conflicts 

994 if c_mask is not None: 

995 mask = [mask[k] and c_mask[k] for k in range(len(self))] 

996 

997 if displacement_vector is None: 

998 displacement_vector = [] 

999 for k in range(len(self)): 

1000 if mask[k]: 

1001 diff_line = [] 

1002 for _ in range(3): 

1003 if method.lower() == 'gauss': 

1004 if not gauss_std: 

1005 gauss_std = self.control.get_parameter( 

1006 'gauss_std' 

1007 ) 

1008 diff = self.random_state.normal(0.0, gauss_std) 

1009 else: 

1010 e = f'Invalid displacement method >>{method!s}<<' 

1011 raise ValueError(e) 

1012 diff_line.append(diff) 

1013 displacement_vector.append(diff_line) 

1014 else: 

1015 displacement_vector.append([0.0] * 3) 

1016 

1017 # Remove displacement of masked atoms 

1018 for k in range(len(mask)): 

1019 if not mask[k]: 

1020 displacement_vector[k] = [0.0] * 3 

1021 

1022 # Perform the displacement and log it 

1023 if log: 

1024 pos0 = self.get_positions() 

1025 self.set_positions(self.get_positions() + displacement_vector) 

1026 if log: 

1027 parameters = { 

1028 'mask': mask, 

1029 'displacement_method': method, 

1030 'gauss_std': gauss_std, 

1031 'displacement_center': displacement_center, 

1032 'displacement_radius': radius, 

1033 'number_of_displacement_atoms': number_of_atoms, 

1034 } 

1035 self.displacement_log(self.get_positions() - pos0, parameters) 

1036 

1037 def eigenmode_log(self): 

1038 """Log the eigenmodes (eigenmode estimates)""" 

1039 if self.mlogfile is not None: 

1040 l = 'MINMODE:MODE: Optimization Step: %i\n' % ( 

1041 self.control.get_counter('optcount') 

1042 ) 

1043 for m_num, mode in enumerate(self.eigenmodes): 

1044 l += 'MINMODE:MODE: Order: %i\n' % m_num 

1045 for k in range(len(mode)): 

1046 l += 'MINMODE:MODE: %7i %15.8f %15.8f %15.8f\n' % ( 

1047 k, 

1048 mode[k][0], 

1049 mode[k][1], 

1050 mode[k][2], 

1051 ) 

1052 self.mlogfile.write(l) 

1053 self.mlogfile.flush() 

1054 

1055 def displacement_log(self, displacement_vector, parameters): 

1056 """Log the displacement""" 

1057 if self.logfile is not None: 

1058 lp = 'MINMODE:DISP: Parameters, different from the control:\n' 

1059 mod_para = False 

1060 for key in parameters: 

1061 if parameters[key] != self.control.get_parameter(key): 

1062 lp += 'MINMODE:DISP: {} = {}\n'.format( 

1063 str(key), str(parameters[key]) 

1064 ) 

1065 mod_para = True 

1066 if mod_para: 

1067 l = lp 

1068 else: 

1069 l = '' 

1070 for k in range(len(displacement_vector)): 

1071 l += 'MINMODE:DISP: %7i %15.8f %15.8f %15.8f\n' % ( 

1072 k, 

1073 displacement_vector[k][0], 

1074 displacement_vector[k][1], 

1075 displacement_vector[k][2], 

1076 ) 

1077 self.logfile.write(l) 

1078 self.logfile.flush() 

1079 

1080 def summarize(self): 

1081 """Summarize the Minimum mode search.""" 

1082 if self.logfile is None: 

1083 logfile = sys.stdout 

1084 else: 

1085 logfile = self.logfile 

1086 

1087 c = self.control 

1088 label = 'MINMODE:SUMMARY: ' 

1089 

1090 l = label + '-------------------------\n' 

1091 l += label + 'Barrier: %16.4f\n' % self.get_barrier_energy() 

1092 l += label + 'Curvature: %14.4f\n' % self.get_curvature() 

1093 l += label + 'Optimizer steps: %8i\n' % c.get_counter('optcount') 

1094 l += label + 'Forcecalls: %13i\n' % c.get_counter('forcecalls') 

1095 l += label + '-------------------------\n' 

1096 

1097 logfile.write(l) 

1098 

1099 

1100class MinModeTranslate(Optimizer): 

1101 """An Optimizer specifically tailored to minimum mode following.""" 

1102 

1103 def __init__(self, dimeratoms, logfile='-', trajectory=None): 

1104 Optimizer.__init__(self, dimeratoms, None, logfile, trajectory) 

1105 

1106 self.control = dimeratoms.get_control() 

1107 self.dimeratoms = dimeratoms 

1108 

1109 # Make a header for the log 

1110 if self.logfile is not None: 

1111 l = '' 

1112 if isinstance(self.control, DimerControl): 

1113 l = ( 

1114 'MinModeTranslate: STEP TIME ENERGY ' 

1115 + 'MAX-FORCE STEPSIZE CURVATURE ROT-STEPS\n' 

1116 ) 

1117 self.logfile.write(l) 

1118 

1119 # Load the relevant parameters from control 

1120 self.cg_on = self.control.get_parameter('cg_translation') 

1121 self.trial_step = self.control.get_parameter('trial_trans_step') 

1122 self.max_step = self.control.get_parameter('maximum_translation') 

1123 

1124 # Start conjugate gradient 

1125 if self.cg_on: 

1126 self.cg_init = True 

1127 

1128 def initialize(self): 

1129 """Set initial values.""" 

1130 self.r0 = None 

1131 self.f0 = None 

1132 

1133 def step(self, f=None): 

1134 """Perform the optimization step.""" 

1135 

1136 atoms = self.dimeratoms 

1137 if f is None: 

1138 f = atoms.get_forces() 

1139 r = atoms.get_positions() 

1140 curv = atoms.get_curvature() 

1141 f0p = f.copy() 

1142 r0 = r.copy() 

1143 direction = f0p.copy() 

1144 if self.cg_on: 

1145 direction = self.get_cg_direction(direction) 

1146 if norm(direction) == np.inf: 

1147 raise RuntimeError('Dimer calculation diverged') 

1148 direction = normalize(direction) 

1149 if curv > 0.0: 

1150 step = direction * self.max_step 

1151 else: 

1152 r0t = r0 + direction * self.trial_step 

1153 f0tp = self.dimeratoms.get_projected_forces(r0t) 

1154 F = np.vdot((f0tp + f0p), direction) / 2.0 

1155 C = np.vdot((f0tp - f0p), direction) / self.trial_step 

1156 step = (-F / C + self.trial_step / 2.0) * direction 

1157 if norm(step) > self.max_step or np.isnan(norm(step)): 

1158 step = direction * self.max_step 

1159 self.log(f0p, norm(step)) 

1160 

1161 atoms.set_positions(r + step) 

1162 

1163 self.f0 = f.flat.copy() 

1164 self.r0 = r.flat.copy() 

1165 

1166 def get_cg_direction(self, direction): 

1167 """Apply the Conjugate Gradient algorithm to the step direction.""" 

1168 if self.cg_init: 

1169 self.cg_init = False 

1170 self.direction_old = direction.copy() 

1171 self.cg_direction = direction.copy() 

1172 old_norm = np.vdot(self.direction_old, self.direction_old) 

1173 # Polak-Ribiere Conjugate Gradient 

1174 if old_norm != 0.0: 

1175 betaPR = ( 

1176 np.vdot(direction, (direction - self.direction_old)) / old_norm 

1177 ) 

1178 else: 

1179 betaPR = 0.0 

1180 if betaPR < 0.0: 

1181 betaPR = 0.0 

1182 self.cg_direction = direction + self.cg_direction * betaPR 

1183 self.direction_old = direction.copy() 

1184 return self.cg_direction.copy() 

1185 

1186 def log(self, gradient, stepsize=None): 

1187 """Log each step of the optimization.""" 

1188 f = self.dimeratoms.get_forces() 

1189 if self.logfile is not None: 

1190 T = time.localtime() 

1191 e = self.dimeratoms.get_potential_energy() 

1192 fmax = sqrt((f**2).sum(axis=1).max()) 

1193 rotsteps = self.dimeratoms.control.get_counter('rotcount') 

1194 curvature = self.dimeratoms.get_curvature() 

1195 l = '' 

1196 if stepsize: 

1197 if isinstance(self.control, DimerControl): 

1198 l = ( 

1199 '%s: %4d %02d:%02d:%02d %15.6f %12.4f %12.6f ' 

1200 '%12.6f %10d\n' 

1201 % ( 

1202 'MinModeTranslate', 

1203 self.nsteps, 

1204 T[3], 

1205 T[4], 

1206 T[5], 

1207 e, 

1208 fmax, 

1209 stepsize, 

1210 curvature, 

1211 rotsteps, 

1212 ) 

1213 ) 

1214 else: 

1215 if isinstance(self.control, DimerControl): 

1216 l = ( 

1217 '%s: %4d %02d:%02d:%02d %15.6f %12.4f %s ' 

1218 '%12.6f %10d\n' 

1219 % ( 

1220 'MinModeTranslate', 

1221 self.nsteps, 

1222 T[3], 

1223 T[4], 

1224 T[5], 

1225 e, 

1226 fmax, 

1227 ' --------', 

1228 curvature, 

1229 rotsteps, 

1230 ) 

1231 ) 

1232 self.logfile.write(l) 

1233 

1234 

1235def read_eigenmode(mlog, index=-1): 

1236 """Read an eigenmode. 

1237 To access the pre optimization eigenmode set index = 'null'. 

1238 

1239 """ 

1240 mlog_is_str = isinstance(mlog, str) 

1241 if mlog_is_str: 

1242 fd = open(mlog) 

1243 else: 

1244 fd = mlog 

1245 

1246 lines = fd.readlines() 

1247 

1248 # Detect the amount of atoms and iterations 

1249 k = 2 

1250 while lines[k].split()[1].lower() not in ['optimization', 'order']: 

1251 k += 1 

1252 n = k - 2 

1253 n_itr = (len(lines) // (n + 1)) - 2 

1254 

1255 # Locate the correct image. 

1256 if isinstance(index, str): 

1257 if index.lower() == 'null': 

1258 i = 0 

1259 else: 

1260 i = int(index) + 1 

1261 else: 

1262 if index >= 0: 

1263 i = index + 1 

1264 else: 

1265 if index < -n_itr - 1: 

1266 raise IndexError('list index out of range') 

1267 else: 

1268 i = index 

1269 

1270 mode = np.ndarray(shape=(n, 3), dtype=float) 

1271 for k_atom, k in enumerate(range(1, n + 1)): 

1272 line = lines[i * (n + 1) + k].split() 

1273 for k_dim in range(3): 

1274 mode[k_atom][k_dim] = float(line[k_dim + 2]) 

1275 if mlog_is_str: 

1276 fd.close() 

1277 

1278 return mode 

1279 

1280 

1281# Aliases 

1282DimerAtoms = MinModeAtoms 

1283DimerTranslate = MinModeTranslate