Coverage for ase/optimize/precon/precon.py: 85.84%

664 statements  

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

1""" 

2Implementation of the Precon abstract base class and subclasses 

3""" 

4 

5import copy 

6import sys 

7import time 

8import warnings 

9from abc import ABC, abstractmethod 

10 

11import numpy as np 

12from scipy import sparse 

13from scipy.interpolate import CubicSpline 

14from scipy.sparse.linalg import spsolve 

15 

16import ase.units as units 

17import ase.utils.ff as ff 

18from ase.constraints import FixAtoms 

19from ase.filters import Filter 

20from ase.geometry import find_mic 

21from ase.neighborlist import neighbor_list 

22from ase.optimize.precon.neighbors import ( 

23 estimate_nearest_neighbour_distance, 

24 get_neighbours, 

25) 

26from ase.utils import longsum, tokenize_version 

27 

28try: 

29 import pyamg 

30except ImportError: 

31 have_pyamg = False 

32else: 

33 have_pyamg = True 

34 

35 

36def create_pyamg_solver(P, max_levels=15): 

37 if not have_pyamg: 

38 raise RuntimeError( 

39 'pyamg not available: install with `pip install pyamg`' 

40 ) 

41 filter_key = 'filter' 

42 if tokenize_version(pyamg.__version__) >= tokenize_version('4.2.1'): 

43 filter_key = 'filter_entries' 

44 return pyamg.smoothed_aggregation_solver( 

45 P, 

46 B=None, 

47 strength=('symmetric', {'theta': 0.0}), 

48 smooth=('jacobi', {filter_key: True, 'weighting': 'local'}), 

49 improve_candidates=( 

50 [('block_gauss_seidel', {'sweep': 'symmetric', 'iterations': 4})] 

51 + [None] * (max_levels - 1) 

52 ), 

53 aggregate='standard', 

54 presmoother=( 

55 'block_gauss_seidel', 

56 {'sweep': 'symmetric', 'iterations': 1}, 

57 ), 

58 postsmoother=( 

59 'block_gauss_seidel', 

60 {'sweep': 'symmetric', 'iterations': 1}, 

61 ), 

62 max_levels=max_levels, 

63 max_coarse=300, 

64 coarse_solver='pinv', 

65 ) 

66 

67 

68THz = 1e12 * 1.0 / units.s 

69 

70 

71class Precon(ABC): 

72 @abstractmethod 

73 def make_precon(self, atoms, reinitialize=None): 

74 """ 

75 Create a preconditioner matrix based on the passed set of atoms. 

76 

77 Creates a general-purpose preconditioner for use with optimization 

78 algorithms, based on examining distances between pairs of atoms in the 

79 lattice. The matrix will be stored in the attribute self.P and 

80 returned. 

81 

82 Args: 

83 atoms: the Atoms object used to create the preconditioner. 

84 

85 reinitialize: if True, parameters of the preconditioner 

86 will be recalculated before the preconditioner matrix is 

87 created. If False, they will be calculated only when they 

88 do not currently have a value (ie, the first time this 

89 function is called). 

90 

91 Returns 

92 ------- 

93 P: A sparse scipy csr_matrix. BE AWARE that using 

94 numpy.dot() with sparse matrices will result in 

95 errors/incorrect results - use the .dot method directly 

96 on the matrix instead. 

97 """ 

98 ... 

99 

100 @abstractmethod 

101 def Pdot(self, x): 

102 """ 

103 Return the result of applying P to a vector x 

104 """ 

105 ... 

106 

107 def dot(self, x, y): 

108 """ 

109 Return the preconditioned dot product <P x, y> 

110 

111 Uses 128-bit floating point math for vector dot products 

112 """ 

113 return longsum(self.Pdot(x) * y) 

114 

115 def norm(self, x): 

116 """ 

117 Return the P-norm of x, where |x|_P = sqrt(<Px, x>) 

118 """ 

119 return np.sqrt(self.dot(x, x)) 

120 

121 def vdot(self, x, y): 

122 return self.dot(x.reshape(-1), y.reshape(-1)) 

123 

124 @abstractmethod 

125 def solve(self, x): 

126 """ 

127 Solve the (sparse) linear system P x = y and return y 

128 """ 

129 ... 

130 

131 def apply(self, forces, atoms): 

132 """ 

133 Convenience wrapper that combines make_precon() and solve() 

134 

135 Parameters 

136 ---------- 

137 forces: array 

138 (len(atoms)*3) array of input forces 

139 atoms: ase.atoms.Atoms 

140 

141 Returns 

142 ------- 

143 precon_forces: array 

144 (len(atoms), 3) array of preconditioned forces 

145 """ 

146 self.make_precon(atoms) 

147 precon_forces = self.solve(forces) 

148 return precon_forces 

149 

150 @abstractmethod 

151 def copy(self): ... 

152 

153 @abstractmethod 

154 def asarray(self): 

155 """ 

156 Array representation of preconditioner, as a dense matrix 

157 """ 

158 ... 

159 

160 

161class Logfile: 

162 def __init__(self, logfile=None): 

163 if isinstance(logfile, str): 

164 if logfile == '-': 

165 logfile = sys.stdout 

166 else: 

167 logfile = open(logfile, 'a') 

168 self.logfile = logfile 

169 

170 def write(self, *args): 

171 if self.logfile is None: 

172 return 

173 self.logfile.write(*args) 

174 

175 

176class SparsePrecon(Precon): 

177 def __init__( 

178 self, 

179 r_cut=None, 

180 r_NN=None, 

181 mu=None, 

182 mu_c=None, 

183 dim=3, 

184 c_stab=0.1, 

185 force_stab=False, 

186 reinitialize=False, 

187 array_convention='C', 

188 solver='auto', 

189 solve_tol=1e-8, 

190 apply_positions=True, 

191 apply_cell=True, 

192 estimate_mu_eigmode=False, 

193 logfile=None, 

194 rng=None, 

195 neighbour_list=neighbor_list, 

196 ): 

197 """Initialise a preconditioner object based on passed parameters. 

198 

199 Parameters 

200 ---------- 

201 r_cut: float. This is a cut-off radius. The preconditioner matrix 

202 will be created by considering pairs of atoms that are within a 

203 distance r_cut of each other. For a regular lattice, this is 

204 usually taken somewhere between the first- and second-nearest 

205 neighbour distance. If r_cut is not provided, default is 

206 2 * r_NN (see below) 

207 r_NN: nearest neighbour distance. If not provided, this is 

208 calculated 

209 from input structure. 

210 mu: float 

211 energy scale for position degreees of freedom. If `None`, mu 

212 is precomputed using finite difference derivatives. 

213 mu_c: float 

214 energy scale for cell degreees of freedom. Also precomputed 

215 if None. 

216 estimate_mu_eigmode: 

217 If True, estimates mu based on the lowest eigenmodes of 

218 unstabilised preconditioner. If False it uses the sine based 

219 approach. 

220 dim: int; dimensions of the problem 

221 c_stab: float. The diagonal of the preconditioner matrix will have 

222 a stabilisation constant added, which will be the value of 

223 c_stab times mu. 

224 force_stab: 

225 If True, always add the stabilisation to diagnonal, regardless 

226 of the presence of fixed atoms. 

227 reinitialize: if True, the value of mu will be recalculated when 

228 self.make_precon is called. This can be overridden in specific 

229 cases with reinitialize argument in self.make_precon. If it 

230 is set to True here, the value passed for mu will be 

231 irrelevant unless reinitialize is set to False the first time 

232 make_precon is called. 

233 array_convention: Either 'C' or 'F' for Fortran; this will change 

234 the preconditioner to reflect the ordering of the indices in 

235 the vector it will operate on. The C convention assumes the 

236 vector will be arranged atom-by-atom (ie [x1, y1, z1, x2, ...]) 

237 while the F convention assumes it will be arranged component 

238 by component (ie [x1, x2, ..., y1, y2, ...]). 

239 solver: One of "auto", "direct" or "pyamg", specifying whether to 

240 use a direct sparse solver or PyAMG to solve P x = y. 

241 Default is "auto" which uses PyAMG if available, falling 

242 back to sparse solver if not. solve_tol: tolerance used for 

243 PyAMG sparse linear solver, if available. 

244 apply_positions: bool 

245 if True, apply preconditioner to position DoF 

246 apply_cell: bool 

247 if True, apply preconditioner to cell DoF 

248 logfile: file object or str 

249 If *logfile* is a string, a file with that name will be opened. 

250 Use '-' for stdout. 

251 rng: None or np.random.RandomState instance 

252 Random number generator to use for initialising pyamg solver 

253 neighbor_list: function (optional). Optionally replace the built-in 

254 ASE neighbour list with an alternative with the same call 

255 signature, e.g. `matscipy.neighbours.neighbour_list`. 

256 

257 Raises 

258 ------ 

259 ValueError for problem with arguments 

260 

261 """ 

262 self.r_NN = r_NN 

263 self.r_cut = r_cut 

264 self.mu = mu 

265 self.mu_c = mu_c 

266 self.estimate_mu_eigmode = estimate_mu_eigmode 

267 self.c_stab = c_stab 

268 self.force_stab = force_stab 

269 self.array_convention = array_convention 

270 self.reinitialize = reinitialize 

271 self.P = None 

272 self.old_positions = None 

273 

274 use_pyamg = False 

275 if solver == 'auto': 

276 use_pyamg = have_pyamg 

277 elif solver == 'direct': 

278 use_pyamg = False 

279 elif solver == 'pyamg': 

280 if not have_pyamg: 

281 raise RuntimeError("solver='pyamg', PyAMG can't be imported!") 

282 use_pyamg = True 

283 else: 

284 raise ValueError( 

285 'unknown solver - should be "auto", "direct" or "pyamg"' 

286 ) 

287 

288 self.use_pyamg = use_pyamg 

289 self.solve_tol = solve_tol 

290 self.apply_positions = apply_positions 

291 self.apply_cell = apply_cell 

292 

293 if dim < 1: 

294 raise ValueError('Dimension must be at least 1') 

295 self.dim = dim 

296 self.logfile = Logfile(logfile) 

297 

298 if rng is None: 

299 rng = np.random.RandomState() 

300 self.rng = rng 

301 

302 self.neighbor_list = neighbor_list 

303 

304 def copy(self): 

305 return copy.deepcopy(self) 

306 

307 def Pdot(self, x): 

308 return self.P.dot(x) 

309 

310 def solve(self, x): 

311 start_time = time.time() 

312 if self.use_pyamg and have_pyamg: 

313 y = self.ml.solve( 

314 x, 

315 x0=self.rng.random(self.P.shape[0]), 

316 tol=self.solve_tol, 

317 accel='cg', 

318 maxiter=300, 

319 cycle='W', 

320 ) 

321 else: 

322 y = spsolve(self.P, x) 

323 self.logfile.write( 

324 f'--- Precon applied in {(time.time() - start_time)} seconds ---\n' 

325 ) 

326 return y 

327 

328 def estimate_mu(self, atoms, H=None): 

329 r"""Estimate optimal preconditioner coefficient \mu 

330 

331 \mu is estimated from a numerical solution of 

332 

333 [dE(p+v) - dE(p)] \cdot v = \mu < P1 v, v > 

334 

335 with perturbation 

336 

337 v(x,y,z) = H P_lowest_nonzero_eigvec(x, y, z) 

338 

339 or 

340 

341 v(x,y,z) = H (sin(x / Lx), sin(y / Ly), sin(z / Lz)) 

342 

343 After the optimal \mu is found, self.mu will be set to its value. 

344 

345 If `atoms` is an instance of Filter an additional \mu_c 

346 will be computed for the cell degrees of freedom . 

347 

348 Args: 

349 atoms: Atoms object for initial system 

350 

351 H: 3x3 array or None 

352 Magnitude of deformation to apply. 

353 Default is 1e-2*rNN*np.eye(3) 

354 

355 Returns 

356 ------- 

357 mu : float 

358 mu_c : float or None 

359 """ 

360 logfile = self.logfile 

361 

362 if self.dim != 3: 

363 raise ValueError( 

364 'Automatic calculation of mu only possible for ' 

365 'three-dimensional preconditioners. Try setting ' 

366 'mu manually instead.' 

367 ) 

368 

369 if self.r_NN is None: 

370 self.r_NN = estimate_nearest_neighbour_distance( 

371 atoms, self.neighbor_list 

372 ) 

373 

374 # deformation matrix, default is diagonal 

375 if H is None: 

376 H = 1e-2 * self.r_NN * np.eye(3) 

377 

378 # compute perturbation 

379 p = atoms.get_positions() 

380 

381 if self.estimate_mu_eigmode: 

382 self.mu = 1.0 

383 self.mu_c = 1.0 

384 c_stab = self.c_stab 

385 self.c_stab = 0.0 

386 

387 if isinstance(atoms, Filter): 

388 n = len(atoms.atoms) 

389 else: 

390 n = len(atoms) 

391 self._make_sparse_precon(atoms, initial_assembly=True) 

392 self.P = self.P[: 3 * n, : 3 * n] 

393 eigvals, eigvecs = sparse.linalg.eigsh(self.P, k=4, which='SM') 

394 

395 logfile.write( 

396 'estimate_mu(): lowest 4 eigvals = %f %f %f %f\n' 

397 % (eigvals[0], eigvals[1], eigvals[2], eigvals[3]) 

398 ) 

399 # check eigenvalues 

400 if any(eigvals[0:3] > 1e-6): 

401 raise ValueError( 

402 'First 3 eigenvalues of preconditioner matrix' 

403 'do not correspond to translational modes.' 

404 ) 

405 elif eigvals[3] < 1e-6: 

406 raise ValueError( 

407 'Fourth smallest eigenvalue of ' 

408 'preconditioner matrix ' 

409 'is too small, increase r_cut.' 

410 ) 

411 

412 x = np.zeros(n) 

413 for i in range(n): 

414 x[i] = eigvecs[:, 3][3 * i] 

415 x = x / np.linalg.norm(x) 

416 if x[0] < 0: 

417 x = -x 

418 

419 v = np.zeros(3 * len(atoms)) 

420 for i in range(n): 

421 v[3 * i] = x[i] 

422 v[3 * i + 1] = x[i] 

423 v[3 * i + 2] = x[i] 

424 v = v / np.linalg.norm(v) 

425 v = v.reshape((-1, 3)) 

426 

427 self.c_stab = c_stab 

428 else: 

429 Lx, Ly, Lz = (p[:, i].max() - p[:, i].min() for i in range(3)) 

430 logfile.write( 

431 'estimate_mu(): Lx=%.1f Ly=%.1f Lz=%.1f\n' % (Lx, Ly, Lz) 

432 ) 

433 

434 x, y, z = p.T 

435 # sine_vr = [np.sin(x/Lx), np.sin(y/Ly), np.sin(z/Lz)], but we need 

436 # to take into account the possibility that one of Lx/Ly/Lz is 

437 # zero. 

438 sine_vr = [x, y, z] 

439 

440 for i, L in enumerate([Lx, Ly, Lz]): 

441 if L == 0: 

442 warnings.warn( 

443 'Cell length L[%d] == 0. Setting H[%d,%d] = 0.' 

444 % (i, i, i) 

445 ) 

446 H[i, i] = 0.0 

447 else: 

448 sine_vr[i] = np.sin(sine_vr[i] / L) 

449 

450 v = np.dot(H, sine_vr).T 

451 

452 natoms = len(atoms) 

453 if isinstance(atoms, Filter): 

454 natoms = len(atoms.atoms) 

455 eps = H / self.r_NN 

456 v[natoms:, :] = eps 

457 

458 v1 = v.reshape(-1) 

459 

460 # compute LHS 

461 dE_p = -atoms.get_forces().reshape(-1) 

462 atoms_v = atoms.copy() 

463 atoms_v.calc = atoms.calc 

464 if isinstance(atoms, Filter): 

465 atoms_v = atoms.__class__(atoms_v) 

466 if hasattr(atoms, 'constant_volume'): 

467 atoms_v.constant_volume = atoms.constant_volume 

468 atoms_v.set_positions(p + v) 

469 dE_p_plus_v = -atoms_v.get_forces().reshape(-1) 

470 

471 # compute left hand side 

472 LHS = (dE_p_plus_v - dE_p) * v1 

473 

474 # assemble P with \mu = 1 

475 self.mu = 1.0 

476 self.mu_c = 1.0 

477 

478 self._make_sparse_precon(atoms, initial_assembly=True) 

479 

480 # compute right hand side 

481 RHS = self.P.dot(v1) * v1 

482 

483 # use partial sums to compute separate mu for positions and cell DoFs 

484 self.mu = longsum(LHS[: 3 * natoms]) / longsum(RHS[: 3 * natoms]) 

485 if self.mu < 1.0: 

486 logfile.write( 

487 'estimate_mu(): mu (%.3f) < 1.0, capping at mu=1.0' % self.mu 

488 ) 

489 self.mu = 1.0 

490 

491 if isinstance(atoms, Filter): 

492 self.mu_c = longsum(LHS[3 * natoms :]) / longsum(RHS[3 * natoms :]) 

493 if self.mu_c < 1.0: 

494 logfile.write( 

495 'estimate_mu(): mu_c (%.3f) < 1.0, ' 

496 'capping at mu_c=1.0\n' % self.mu_c 

497 ) 

498 self.mu_c = 1.0 

499 

500 logfile.write('estimate_mu(): mu=%r, mu_c=%r\n' % (self.mu, self.mu_c)) 

501 

502 self.P = None # force a rebuild with new mu (there may be fixed atoms) 

503 return (self.mu, self.mu_c) 

504 

505 def asarray(self): 

506 return np.array(self.P.todense()) 

507 

508 def one_dim_to_ndim(self, csc_P, N): 

509 """ 

510 Expand an N x N precon matrix to self.dim*N x self.dim * N 

511 

512 Args: 

513 csc_P (sparse matrix): N x N sparse matrix, in CSC format 

514 """ 

515 start_time = time.time() 

516 if self.dim == 1: 

517 P = csc_P 

518 elif self.array_convention == 'F': 

519 csc_P = csc_P.tocsr() 

520 P = csc_P 

521 for _ in range(self.dim - 1): 

522 P = sparse.block_diag((P, csc_P)).tocsr() 

523 else: 

524 # convert back to triplet and read the arrays 

525 csc_P = csc_P.tocoo() 

526 i = csc_P.row * self.dim 

527 j = csc_P.col * self.dim 

528 z = csc_P.data 

529 

530 # N-dimensionalise, interlaced coordinates 

531 I = np.hstack([i + d for d in range(self.dim)]) 

532 J = np.hstack([j + d for d in range(self.dim)]) 

533 Z = np.hstack([z for _ in range(self.dim)]) 

534 P = sparse.csc_matrix( 

535 (Z, (I, J)), shape=(self.dim * N, self.dim * N) 

536 ) 

537 P = P.tocsr() 

538 self.logfile.write( 

539 f'--- N-dim precon created in {(time.time() - start_time)} s ---\n' 

540 ) 

541 return P 

542 

543 def create_solver(self): 

544 if self.use_pyamg and have_pyamg: 

545 start_time = time.time() 

546 self.ml = create_pyamg_solver(self.P) 

547 self.logfile.write( 

548 f'--- multi grid solver created in {(time.time() - start_time)}' 

549 ' ---\n' 

550 ) 

551 

552 

553class SparseCoeffPrecon(SparsePrecon): 

554 def _make_sparse_precon( 

555 self, atoms, initial_assembly=False, force_stab=False 

556 ): 

557 """Create a sparse preconditioner matrix based on the passed atoms. 

558 

559 Creates a general-purpose preconditioner for use with optimization 

560 algorithms, based on examining distances between pairs of atoms in the 

561 lattice. The matrix will be stored in the attribute self.P and 

562 returned. Note that this function will use self.mu, whatever it is. 

563 

564 Args: 

565 atoms: the Atoms object used to create the preconditioner. 

566 

567 Returns 

568 ------- 

569 A scipy.sparse.csr_matrix object, representing a d*N by d*N matrix 

570 (where N is the number of atoms, and d is the value of self.dim). 

571 BE AWARE that using numpy.dot() with this object will result in 

572 errors/incorrect results - use the .dot method directly on the 

573 sparse matrix instead. 

574 

575 """ 

576 logfile = self.logfile 

577 logfile.write( 

578 'creating sparse precon: initial_assembly=%r, ' 

579 'force_stab=%r, apply_positions=%r, apply_cell=%r\n' 

580 % ( 

581 initial_assembly, 

582 force_stab, 

583 self.apply_positions, 

584 self.apply_cell, 

585 ) 

586 ) 

587 

588 N = len(atoms) 

589 diag_i = np.arange(N, dtype=int) 

590 start_time = time.time() 

591 if self.apply_positions: 

592 # compute neighbour list 

593 i, j, rij, fixed_atoms = get_neighbours( 

594 atoms, self.r_cut, neighbor_list=self.neighbor_list 

595 ) 

596 logfile.write( 

597 f'--- neighbour list created in {(time.time() - start_time)} s ' 

598 '--- \n' 

599 ) 

600 

601 # compute entries in triplet format: without the constraints 

602 start_time = time.time() 

603 coeff = self.get_coeff(rij) 

604 diag_coeff = np.bincount(i, -coeff, minlength=N).astype(np.float64) 

605 if force_stab or len(fixed_atoms) == 0: 

606 logfile.write('adding stabilisation to precon') 

607 diag_coeff += self.mu * self.c_stab 

608 else: 

609 diag_coeff = np.ones(N) 

610 

611 # precon is mu_c * identity for cell DoF 

612 if isinstance(atoms, Filter): 

613 if self.apply_cell: 

614 diag_coeff[-3:] = self.mu_c 

615 else: 

616 diag_coeff[-3:] = 1.0 

617 logfile.write( 

618 f'--- computed triplet format in {(time.time() - start_time)} s ' 

619 '---\n' 

620 ) 

621 

622 if self.apply_positions and not initial_assembly: 

623 # apply the constraints 

624 start_time = time.time() 

625 mask = np.ones(N) 

626 mask[fixed_atoms] = 0.0 

627 coeff *= mask[i] * mask[j] 

628 diag_coeff[fixed_atoms] = 1.0 

629 logfile.write( 

630 f'--- applied fixed_atoms in {(time.time() - start_time)} s ' 

631 '---\n' 

632 ) 

633 

634 if self.apply_positions: 

635 # remove zeros 

636 start_time = time.time() 

637 inz = np.nonzero(coeff) 

638 i = np.hstack((i[inz], diag_i)) 

639 j = np.hstack((j[inz], diag_i)) 

640 coeff = np.hstack((coeff[inz], diag_coeff)) 

641 logfile.write( 

642 f'--- remove zeros in {(time.time() - start_time)} s ---\n' 

643 ) 

644 else: 

645 i = diag_i 

646 j = diag_i 

647 coeff = diag_coeff 

648 

649 # create an N x N precon matrix in compressed sparse column (CSC) format 

650 start_time = time.time() 

651 csc_P = sparse.csc_matrix((coeff, (i, j)), shape=(N, N)) 

652 logfile.write( 

653 f'--- created CSC matrix in {(time.time() - start_time)} s ---\n' 

654 ) 

655 

656 self.P = self.one_dim_to_ndim(csc_P, N) 

657 self.create_solver() 

658 

659 def make_precon(self, atoms, reinitialize=None): 

660 if self.r_NN is None: 

661 self.r_NN = estimate_nearest_neighbour_distance( 

662 atoms, self.neighbor_list 

663 ) 

664 

665 if self.r_cut is None: 

666 # This is the first time this function has been called, and no 

667 # cutoff radius has been specified, so calculate it automatically. 

668 self.r_cut = 2.0 * self.r_NN 

669 elif self.r_cut < self.r_NN: 

670 warning = ( 

671 'WARNING: r_cut (%.2f) < r_NN (%.2f), ' 

672 'increasing to 1.1*r_NN = %.2f' 

673 % (self.r_cut, self.r_NN, 1.1 * self.r_NN) 

674 ) 

675 warnings.warn(warning) 

676 self.r_cut = 1.1 * self.r_NN 

677 

678 if reinitialize is None: 

679 # The caller has not specified whether or not to recalculate mu, 

680 # so the Precon's setting is used. 

681 reinitialize = self.reinitialize 

682 

683 if self.mu is None: 

684 # Regardless of what the caller has specified, if we don't 

685 # currently have a value of mu, then we need one. 

686 reinitialize = True 

687 

688 if reinitialize: 

689 self.estimate_mu(atoms) 

690 

691 if self.P is not None: 

692 real_atoms = atoms 

693 if isinstance(atoms, Filter): 

694 real_atoms = atoms.atoms 

695 if self.old_positions is None: 

696 self.old_positions = real_atoms.positions 

697 displacement, _ = find_mic( 

698 real_atoms.positions - self.old_positions, 

699 real_atoms.cell, 

700 real_atoms.pbc, 

701 ) 

702 self.old_positions = real_atoms.get_positions() 

703 max_abs_displacement = abs(displacement).max() 

704 self.logfile.write( 

705 'max(abs(displacements)) = %.2f A (%.2f r_NN)' 

706 % (max_abs_displacement, max_abs_displacement / self.r_NN) 

707 ) 

708 if max_abs_displacement < 0.5 * self.r_NN: 

709 return 

710 

711 start_time = time.time() 

712 self._make_sparse_precon(atoms, force_stab=self.force_stab) 

713 self.logfile.write( 

714 f'--- Precon created in {(time.time() - start_time)} seconds --- \n' 

715 ) 

716 

717 @abstractmethod 

718 def get_coeff(self, r): ... 

719 

720 

721class Pfrommer(Precon): 

722 """ 

723 Use initial guess for inverse Hessian from Pfrommer et al. as a 

724 simple preconditioner 

725 

726 J. Comput. Phys. vol 131 p233-240 (1997) 

727 """ 

728 

729 def __init__( 

730 self, 

731 bulk_modulus=500 * units.GPa, 

732 phonon_frequency=50 * THz, 

733 apply_positions=True, 

734 apply_cell=True, 

735 ): 

736 """ 

737 Default bulk modulus is 500 GPa and default phonon frequency is 50 THz 

738 """ 

739 self.bulk_modulus = bulk_modulus 

740 self.phonon_frequency = phonon_frequency 

741 self.apply_positions = apply_positions 

742 self.apply_cell = apply_cell 

743 self.H0 = None 

744 

745 def make_precon(self, atoms, reinitialize=None): 

746 if self.H0 is not None: 

747 # only build H0 on first call 

748 return 

749 

750 variable_cell = False 

751 if isinstance(atoms, Filter): 

752 variable_cell = True 

753 atoms = atoms.atoms 

754 

755 # position DoF 

756 omega = self.phonon_frequency 

757 mass = atoms.get_masses().mean() 

758 block = sparse.eye(3, format='coo') / (mass * omega**2) 

759 blocks = [block] * len(atoms) 

760 

761 # cell DoF 

762 if variable_cell: 

763 coeff = 1.0 

764 if self.apply_cell: 

765 coeff = 1.0 / (3 * self.bulk_modulus) 

766 blocks.append(sparse.eye(9, format='coo') * coeff) 

767 

768 self.H0 = sparse.block_diag(blocks, format='csr') 

769 return 

770 

771 def Pdot(self, x): 

772 return self.H0.solve(x) 

773 

774 def solve(self, x): 

775 y = self.H0.dot(x) 

776 return y 

777 

778 def copy(self): 

779 return Pfrommer( 

780 self.bulk_modulus, 

781 self.phonon_frequency, 

782 self.apply_positions, 

783 self.apply_cell, 

784 ) 

785 

786 def asarray(self): 

787 return np.array(self.H0.todense()) 

788 

789 

790class IdentityPrecon(Precon): 

791 """ 

792 Dummy preconditioner which does not modify forces 

793 """ 

794 

795 def make_precon(self, atoms, reinitialize=None): 

796 self.atoms = atoms 

797 

798 def Pdot(self, x): 

799 return x 

800 

801 def solve(self, x): 

802 return x 

803 

804 def copy(self): 

805 return IdentityPrecon() 

806 

807 def asarray(self): 

808 return np.eye(3 * len(self.atoms)) 

809 

810 

811class C1(SparseCoeffPrecon): 

812 """Creates matrix by inserting a constant where r_ij is less than r_cut.""" 

813 

814 def __init__( 

815 self, 

816 r_cut=None, 

817 mu=None, 

818 mu_c=None, 

819 dim=3, 

820 c_stab=0.1, 

821 force_stab=False, 

822 reinitialize=False, 

823 array_convention='C', 

824 solver='auto', 

825 solve_tol=1e-9, 

826 apply_positions=True, 

827 apply_cell=True, 

828 logfile=None, 

829 ): 

830 super().__init__( 

831 r_cut=r_cut, 

832 mu=mu, 

833 mu_c=mu_c, 

834 dim=dim, 

835 c_stab=c_stab, 

836 force_stab=force_stab, 

837 reinitialize=reinitialize, 

838 array_convention=array_convention, 

839 solver=solver, 

840 solve_tol=solve_tol, 

841 apply_positions=apply_positions, 

842 apply_cell=apply_cell, 

843 logfile=logfile, 

844 ) 

845 

846 def get_coeff(self, r): 

847 return -self.mu * np.ones_like(r) 

848 

849 

850class Exp(SparseCoeffPrecon): 

851 """Creates matrix with values decreasing exponentially with distance.""" 

852 

853 def __init__( 

854 self, 

855 A=3.0, 

856 r_cut=None, 

857 r_NN=None, 

858 mu=None, 

859 mu_c=None, 

860 dim=3, 

861 c_stab=0.1, 

862 force_stab=False, 

863 reinitialize=False, 

864 array_convention='C', 

865 solver='auto', 

866 solve_tol=1e-9, 

867 apply_positions=True, 

868 apply_cell=True, 

869 estimate_mu_eigmode=False, 

870 logfile=None, 

871 ): 

872 """ 

873 Initialise an Exp preconditioner with given parameters. 

874 

875 Args: 

876 r_cut, mu, c_stab, dim, sparse, reinitialize, array_convention: see 

877 precon.__init__() 

878 A: coefficient in exp(-A*r/r_NN). Default is A=3.0. 

879 """ 

880 super().__init__( 

881 r_cut=r_cut, 

882 r_NN=r_NN, 

883 mu=mu, 

884 mu_c=mu_c, 

885 dim=dim, 

886 c_stab=c_stab, 

887 force_stab=force_stab, 

888 reinitialize=reinitialize, 

889 array_convention=array_convention, 

890 solver=solver, 

891 solve_tol=solve_tol, 

892 apply_positions=apply_positions, 

893 apply_cell=apply_cell, 

894 estimate_mu_eigmode=estimate_mu_eigmode, 

895 logfile=logfile, 

896 ) 

897 

898 self.A = A 

899 

900 def get_coeff(self, r): 

901 return -self.mu * np.exp(-self.A * (r / self.r_NN - 1)) 

902 

903 

904def ij_to_x(i, j): 

905 x = [3 * i, 3 * i + 1, 3 * i + 2, 3 * j, 3 * j + 1, 3 * j + 2] 

906 return x 

907 

908 

909def ijk_to_x(i, j, k): 

910 x = [ 

911 3 * i, 

912 3 * i + 1, 

913 3 * i + 2, 

914 3 * j, 

915 3 * j + 1, 

916 3 * j + 2, 

917 3 * k, 

918 3 * k + 1, 

919 3 * k + 2, 

920 ] 

921 return x 

922 

923 

924def ijkl_to_x(i, j, k, l): 

925 x = [ 

926 3 * i, 

927 3 * i + 1, 

928 3 * i + 2, 

929 3 * j, 

930 3 * j + 1, 

931 3 * j + 2, 

932 3 * k, 

933 3 * k + 1, 

934 3 * k + 2, 

935 3 * l, 

936 3 * l + 1, 

937 3 * l + 2, 

938 ] 

939 return x 

940 

941 

942def apply_fixed(atoms, P): 

943 fixed_atoms = [] 

944 for constraint in atoms.constraints: 

945 if isinstance(constraint, FixAtoms): 

946 fixed_atoms.extend(list(constraint.index)) 

947 else: 

948 raise TypeError( 

949 'only FixAtoms constraints are supported by Precon class' 

950 ) 

951 if len(fixed_atoms) != 0: 

952 P = P.tolil() 

953 for i in fixed_atoms: 

954 P[i, :] = 0.0 

955 P[:, i] = 0.0 

956 P[i, i] = 1.0 

957 return P 

958 

959 

960class FF(SparsePrecon): 

961 """Creates matrix using morse/bond/angle/dihedral force field parameters.""" 

962 

963 def __init__( 

964 self, 

965 dim=3, 

966 c_stab=0.1, 

967 force_stab=False, 

968 array_convention='C', 

969 solver='auto', 

970 solve_tol=1e-9, 

971 apply_positions=True, 

972 apply_cell=True, 

973 hessian='spectral', 

974 morses=None, 

975 bonds=None, 

976 angles=None, 

977 dihedrals=None, 

978 logfile=None, 

979 ): 

980 """Initialise an FF preconditioner with given parameters. 

981 

982 Args: 

983 dim, c_stab, force_stab, array_convention, use_pyamg, solve_tol: 

984 see SparsePrecon.__init__() 

985 morses: Morse instance 

986 bonds: Bond instance 

987 angles: Angle instance 

988 dihedrals: Dihedral instance 

989 """ 

990 

991 if ( 

992 morses is None 

993 and bonds is None 

994 and angles is None 

995 and dihedrals is None 

996 ): 

997 raise ImportError( 

998 'At least one of morses, bonds, angles or dihedrals must be ' 

999 'defined!' 

1000 ) 

1001 

1002 super().__init__( 

1003 dim=dim, 

1004 c_stab=c_stab, 

1005 force_stab=force_stab, 

1006 array_convention=array_convention, 

1007 solver=solver, 

1008 solve_tol=solve_tol, 

1009 apply_positions=apply_positions, 

1010 apply_cell=apply_cell, 

1011 logfile=logfile, 

1012 ) 

1013 

1014 self.hessian = hessian 

1015 self.morses = morses 

1016 self.bonds = bonds 

1017 self.angles = angles 

1018 self.dihedrals = dihedrals 

1019 

1020 def make_precon(self, atoms, reinitialize=None): 

1021 start_time = time.time() 

1022 self._make_sparse_precon(atoms, force_stab=self.force_stab) 

1023 self.logfile.write( 

1024 f'--- Precon created in {(time.time() - start_time)} seconds ---\n' 

1025 ) 

1026 

1027 def add_morse(self, morse, atoms, row, col, data, conn=None): 

1028 if self.hessian == 'reduced': 

1029 i, j, Hx = ff.get_morse_potential_reduced_hessian(atoms, morse) 

1030 elif self.hessian == 'spectral': 

1031 i, j, Hx = ff.get_morse_potential_hessian( 

1032 atoms, morse, spectral=True 

1033 ) 

1034 else: 

1035 raise NotImplementedError('Not implemented hessian') 

1036 x = ij_to_x(i, j) 

1037 row.extend(np.repeat(x, 6)) 

1038 col.extend(np.tile(x, 6)) 

1039 data.extend(Hx.flatten()) 

1040 if conn is not None: 

1041 conn[i, j] = True 

1042 conn[j, i] = True 

1043 

1044 def add_bond(self, bond, atoms, row, col, data, conn=None): 

1045 if self.hessian == 'reduced': 

1046 i, j, Hx = ff.get_bond_potential_reduced_hessian( 

1047 atoms, bond, self.morses 

1048 ) 

1049 elif self.hessian == 'spectral': 

1050 i, j, Hx = ff.get_bond_potential_hessian( 

1051 atoms, bond, self.morses, spectral=True 

1052 ) 

1053 else: 

1054 raise NotImplementedError('Not implemented hessian') 

1055 x = ij_to_x(i, j) 

1056 row.extend(np.repeat(x, 6)) 

1057 col.extend(np.tile(x, 6)) 

1058 data.extend(Hx.flatten()) 

1059 if conn is not None: 

1060 conn[i, j] = True 

1061 conn[j, i] = True 

1062 

1063 def add_angle(self, angle, atoms, row, col, data, conn=None): 

1064 if self.hessian == 'reduced': 

1065 i, j, k, Hx = ff.get_angle_potential_reduced_hessian( 

1066 atoms, angle, self.morses 

1067 ) 

1068 elif self.hessian == 'spectral': 

1069 i, j, k, Hx = ff.get_angle_potential_hessian( 

1070 atoms, angle, self.morses, spectral=True 

1071 ) 

1072 else: 

1073 raise NotImplementedError('Not implemented hessian') 

1074 x = ijk_to_x(i, j, k) 

1075 row.extend(np.repeat(x, 9)) 

1076 col.extend(np.tile(x, 9)) 

1077 data.extend(Hx.flatten()) 

1078 if conn is not None: 

1079 conn[i, j] = conn[i, k] = conn[j, k] = True 

1080 conn[j, i] = conn[k, i] = conn[k, j] = True 

1081 

1082 def add_dihedral(self, dihedral, atoms, row, col, data, conn=None): 

1083 if self.hessian == 'reduced': 

1084 i, j, k, l, Hx = ff.get_dihedral_potential_reduced_hessian( 

1085 atoms, dihedral, self.morses 

1086 ) 

1087 elif self.hessian == 'spectral': 

1088 i, j, k, l, Hx = ff.get_dihedral_potential_hessian( 

1089 atoms, dihedral, self.morses, spectral=True 

1090 ) 

1091 else: 

1092 raise NotImplementedError('Not implemented hessian') 

1093 x = ijkl_to_x(i, j, k, l) 

1094 row.extend(np.repeat(x, 12)) 

1095 col.extend(np.tile(x, 12)) 

1096 data.extend(Hx.flatten()) 

1097 if conn is not None: 

1098 conn[i, j] = conn[i, k] = conn[i, l] = conn[j, k] = conn[ 

1099 j, l 

1100 ] = conn[k, l] = True 

1101 conn[j, i] = conn[k, i] = conn[l, i] = conn[k, j] = conn[ 

1102 l, j 

1103 ] = conn[l, k] = True 

1104 

1105 def _make_sparse_precon( 

1106 self, atoms, initial_assembly=False, force_stab=False 

1107 ): 

1108 N = len(atoms) 

1109 

1110 row = [] 

1111 col = [] 

1112 data = [] 

1113 

1114 if self.morses is not None: 

1115 for morse in self.morses: 

1116 self.add_morse(morse, atoms, row, col, data) 

1117 

1118 if self.bonds is not None: 

1119 for bond in self.bonds: 

1120 self.add_bond(bond, atoms, row, col, data) 

1121 

1122 if self.angles is not None: 

1123 for angle in self.angles: 

1124 self.add_angle(angle, atoms, row, col, data) 

1125 

1126 if self.dihedrals is not None: 

1127 for dihedral in self.dihedrals: 

1128 self.add_dihedral(dihedral, atoms, row, col, data) 

1129 

1130 # add the diagonal 

1131 row.extend(range(self.dim * N)) 

1132 col.extend(range(self.dim * N)) 

1133 data.extend([self.c_stab] * self.dim * N) 

1134 

1135 # create the matrix 

1136 start_time = time.time() 

1137 self.P = sparse.csc_matrix( 

1138 (data, (row, col)), shape=(self.dim * N, self.dim * N) 

1139 ) 

1140 self.logfile.write( 

1141 f'--- created CSC matrix in {(time.time() - start_time)} s ---\n' 

1142 ) 

1143 

1144 self.P = apply_fixed(atoms, self.P) 

1145 self.P = self.P.tocsr() 

1146 self.logfile.write( 

1147 f'--- N-dim precon created in {(time.time() - start_time)} s ---\n' 

1148 ) 

1149 self.create_solver() 

1150 

1151 

1152class Exp_FF(Exp, FF): 

1153 """Creates matrix with values decreasing exponentially with distance.""" 

1154 

1155 def __init__( 

1156 self, 

1157 A=3.0, 

1158 r_cut=None, 

1159 r_NN=None, 

1160 mu=None, 

1161 mu_c=None, 

1162 dim=3, 

1163 c_stab=0.1, 

1164 force_stab=False, 

1165 reinitialize=False, 

1166 array_convention='C', 

1167 solver='auto', 

1168 solve_tol=1e-9, 

1169 apply_positions=True, 

1170 apply_cell=True, 

1171 estimate_mu_eigmode=False, 

1172 hessian='spectral', 

1173 morses=None, 

1174 bonds=None, 

1175 angles=None, 

1176 dihedrals=None, 

1177 logfile=None, 

1178 ): 

1179 """Initialise an Exp+FF preconditioner with given parameters. 

1180 

1181 Args: 

1182 r_cut, mu, c_stab, dim, reinitialize, array_convention: see 

1183 precon.__init__() 

1184 A: coefficient in exp(-A*r/r_NN). Default is A=3.0. 

1185 """ 

1186 if ( 

1187 morses is None 

1188 and bonds is None 

1189 and angles is None 

1190 and dihedrals is None 

1191 ): 

1192 raise ImportError( 

1193 'At least one of morses, bonds, angles or dihedrals must ' 

1194 'be defined!' 

1195 ) 

1196 

1197 SparsePrecon.__init__( 

1198 self, 

1199 r_cut=r_cut, 

1200 r_NN=r_NN, 

1201 mu=mu, 

1202 mu_c=mu_c, 

1203 dim=dim, 

1204 c_stab=c_stab, 

1205 force_stab=force_stab, 

1206 reinitialize=reinitialize, 

1207 array_convention=array_convention, 

1208 solver=solver, 

1209 solve_tol=solve_tol, 

1210 apply_positions=apply_positions, 

1211 apply_cell=apply_cell, 

1212 estimate_mu_eigmode=estimate_mu_eigmode, 

1213 logfile=logfile, 

1214 ) 

1215 

1216 self.A = A 

1217 self.hessian = hessian 

1218 self.morses = morses 

1219 self.bonds = bonds 

1220 self.angles = angles 

1221 self.dihedrals = dihedrals 

1222 

1223 def make_precon(self, atoms, reinitialize=None): 

1224 if self.r_NN is None: 

1225 self.r_NN = estimate_nearest_neighbour_distance( 

1226 atoms, self.neighbor_list 

1227 ) 

1228 

1229 if self.r_cut is None: 

1230 # This is the first time this function has been called, and no 

1231 # cutoff radius has been specified, so calculate it automatically. 

1232 self.r_cut = 2.0 * self.r_NN 

1233 elif self.r_cut < self.r_NN: 

1234 warning = ( 

1235 'WARNING: r_cut (%.2f) < r_NN (%.2f), ' 

1236 'increasing to 1.1*r_NN = %.2f' 

1237 % (self.r_cut, self.r_NN, 1.1 * self.r_NN) 

1238 ) 

1239 warnings.warn(warning) 

1240 self.r_cut = 1.1 * self.r_NN 

1241 

1242 if reinitialize is None: 

1243 # The caller has not specified whether or not to recalculate mu, 

1244 # so the Precon's setting is used. 

1245 reinitialize = self.reinitialize 

1246 

1247 if self.mu is None: 

1248 # Regardless of what the caller has specified, if we don't 

1249 # currently have a value of mu, then we need one. 

1250 reinitialize = True 

1251 

1252 if reinitialize: 

1253 self.estimate_mu(atoms) 

1254 

1255 if self.P is not None: 

1256 real_atoms = atoms 

1257 if isinstance(atoms, Filter): 

1258 real_atoms = atoms.atoms 

1259 if self.old_positions is None: 

1260 self.old_positions = real_atoms.positions 

1261 displacement, _ = find_mic( 

1262 real_atoms.positions - self.old_positions, 

1263 real_atoms.cell, 

1264 real_atoms.pbc, 

1265 ) 

1266 self.old_positions = real_atoms.get_positions() 

1267 max_abs_displacement = abs(displacement).max() 

1268 self.logfile.write( 

1269 'max(abs(displacements)) = %.2f A (%.2f r_NN)' 

1270 % (max_abs_displacement, max_abs_displacement / self.r_NN) 

1271 ) 

1272 if max_abs_displacement < 0.5 * self.r_NN: 

1273 return 

1274 

1275 # Create the preconditioner: 

1276 start_time = time.time() 

1277 self._make_sparse_precon(atoms, force_stab=self.force_stab) 

1278 self.logfile.write( 

1279 f'--- Precon created in {(time.time() - start_time)} seconds ---\n' 

1280 ) 

1281 

1282 def _make_sparse_precon( 

1283 self, atoms, initial_assembly=False, force_stab=False 

1284 ): 

1285 """Create a sparse preconditioner matrix based on the passed atoms. 

1286 

1287 Args: 

1288 atoms: the Atoms object used to create the preconditioner. 

1289 

1290 Returns 

1291 ------- 

1292 A scipy.sparse.csr_matrix object, representing a d*N by d*N matrix 

1293 (where N is the number of atoms, and d is the value of self.dim). 

1294 BE AWARE that using numpy.dot() with this object will result in 

1295 errors/incorrect results - use the .dot method directly on the 

1296 sparse matrix instead. 

1297 

1298 """ 

1299 self.logfile.write( 

1300 'creating sparse precon: initial_assembly=%r, ' 

1301 'force_stab=%r, apply_positions=%r, ' 

1302 'apply_cell=%r\n' 

1303 % ( 

1304 initial_assembly, 

1305 force_stab, 

1306 self.apply_positions, 

1307 self.apply_cell, 

1308 ) 

1309 ) 

1310 

1311 N = len(atoms) 

1312 start_time = time.time() 

1313 if self.apply_positions: 

1314 # compute neighbour list 

1315 i_list, j_list, rij_list, _fixed_atoms = get_neighbours( 

1316 atoms, self.r_cut, self.neighbor_list 

1317 ) 

1318 self.logfile.write( 

1319 f'--- neighbour list created in {(time.time() - start_time)} s ' 

1320 '---\n' 

1321 ) 

1322 

1323 row = [] 

1324 col = [] 

1325 data = [] 

1326 

1327 # precon is mu_c*identity for cell DoF 

1328 start_time = time.time() 

1329 if isinstance(atoms, Filter): 

1330 i = N - 3 

1331 j = N - 2 

1332 k = N - 1 

1333 x = ijk_to_x(i, j, k) 

1334 row.extend(x) 

1335 col.extend(x) 

1336 if self.apply_cell: 

1337 data.extend(np.repeat(self.mu_c, 9)) 

1338 else: 

1339 data.extend(np.repeat(self.mu_c, 9)) 

1340 self.logfile.write( 

1341 f'--- computed triplet format in {(time.time() - start_time)} s ' 

1342 '---\n' 

1343 ) 

1344 

1345 conn = sparse.lil_matrix((N, N), dtype=bool) 

1346 

1347 if self.apply_positions and not initial_assembly: 

1348 if self.morses is not None: 

1349 for morse in self.morses: 

1350 self.add_morse(morse, atoms, row, col, data, conn) 

1351 

1352 if self.bonds is not None: 

1353 for bond in self.bonds: 

1354 self.add_bond(bond, atoms, row, col, data, conn) 

1355 

1356 if self.angles is not None: 

1357 for angle in self.angles: 

1358 self.add_angle(angle, atoms, row, col, data, conn) 

1359 

1360 if self.dihedrals is not None: 

1361 for dihedral in self.dihedrals: 

1362 self.add_dihedral(dihedral, atoms, row, col, data, conn) 

1363 

1364 if self.apply_positions: 

1365 for i, j, rij in zip(i_list, j_list, rij_list): 

1366 if not conn[i, j]: 

1367 coeff = self.get_coeff(rij) 

1368 x = ij_to_x(i, j) 

1369 row.extend(x) 

1370 col.extend(x) 

1371 data.extend(3 * [-coeff] + 3 * [coeff]) 

1372 

1373 row.extend(range(self.dim * N)) 

1374 col.extend(range(self.dim * N)) 

1375 if initial_assembly: 

1376 data.extend([self.mu * self.c_stab] * self.dim * N) 

1377 else: 

1378 data.extend([self.c_stab] * self.dim * N) 

1379 

1380 # create the matrix 

1381 start_time = time.time() 

1382 self.P = sparse.csc_matrix( 

1383 (data, (row, col)), shape=(self.dim * N, self.dim * N) 

1384 ) 

1385 self.logfile.write( 

1386 f'--- created CSC matrix in {(time.time() - start_time)} s ---\n' 

1387 ) 

1388 

1389 if not initial_assembly: 

1390 self.P = apply_fixed(atoms, self.P) 

1391 

1392 self.P = self.P.tocsr() 

1393 self.create_solver() 

1394 

1395 

1396def make_precon(precon, atoms=None, **kwargs): 

1397 """ 

1398 Construct preconditioner from a string and optionally build for Atoms 

1399 

1400 Parameters 

1401 ---------- 

1402 precon - one of 'C1', 'Exp', 'Pfrommer', 'FF', 'Exp_FF', 'ID', None 

1403 or an instance of a subclass of `ase.optimize.precon.Precon` 

1404 

1405 atoms - ase.atoms.Atoms instance, optional 

1406 If present, build apreconditioner for this Atoms object 

1407 

1408 **kwargs - additional keyword arguments to pass to Precon constructor 

1409 

1410 Returns 

1411 ------- 

1412 precon - instance of relevant subclass of `ase.optimize.precon.Precon` 

1413 """ 

1414 lookup = { 

1415 'C1': C1, 

1416 'Exp': Exp, 

1417 'Pfrommer': Pfrommer, 

1418 'FF': FF, 

1419 'Exp_FF': Exp_FF, 

1420 'ID': IdentityPrecon, 

1421 'IdentityPrecon': IdentityPrecon, 

1422 None: IdentityPrecon, 

1423 } 

1424 if isinstance(precon, str) or precon is None: 

1425 cls = lookup[precon] 

1426 precon = cls(**kwargs) 

1427 if atoms is not None: 

1428 precon.make_precon(atoms) 

1429 return precon 

1430 

1431 

1432class SplineFit: 

1433 """ 

1434 Fit a cubic spline fit to images 

1435 """ 

1436 

1437 def __init__(self, s, x): 

1438 self._s = s 

1439 self._x_data = x 

1440 self._x = CubicSpline(self._s, x, bc_type='not-a-knot') 

1441 self._dx_ds = self._x.derivative() 

1442 self._d2x_ds2 = self._x.derivative(2) 

1443 

1444 @property 

1445 def s(self): 

1446 return self._s 

1447 

1448 @property 

1449 def x_data(self): 

1450 return self._x_data 

1451 

1452 @property 

1453 def x(self): 

1454 return self._x 

1455 

1456 @property 

1457 def dx_ds(self): 

1458 return self._dx_ds 

1459 

1460 @property 

1461 def d2x_ds2(self): 

1462 return self._d2x_ds2 

1463 

1464 

1465class PreconImages: 

1466 def __init__(self, precon, images, **kwargs): 

1467 """ 

1468 Wrapper for a list of Precon objects and associated images 

1469 

1470 This is used when preconditioning a NEB object. Equation references 

1471 refer to Paper IV in the :class:`ase.mep.NEB` documentation, i.e. 

1472 

1473 S. Makri, C. Ortner and J. R. Kermode, J. Chem. Phys. 

1474 150, 094109 (2019) 

1475 https://dx.doi.org/10.1063/1.5064465 

1476 

1477 Args: 

1478 precon (str or list): preconditioner(s) to use 

1479 images (list of Atoms): Atoms objects that define the state 

1480 

1481 """ 

1482 self.images = images 

1483 self._spline = None 

1484 

1485 if isinstance(precon, list): 

1486 if len(precon) != len(images): 

1487 raise ValueError( 

1488 f'length mismatch: len(precon)={len(precon)} ' 

1489 f'!= len(images)={len(images)}' 

1490 ) 

1491 self.precon = precon 

1492 return 

1493 P0 = make_precon(precon, images[0], **kwargs) 

1494 self.precon = [P0] 

1495 for image in images[1:]: 

1496 P = P0.copy() 

1497 P.make_precon(image) 

1498 self.precon.append(P) 

1499 

1500 def __len__(self): 

1501 return len(self.precon) 

1502 

1503 def __iter__(self): 

1504 return iter(self.precon) 

1505 

1506 def __getitem__(self, index): 

1507 return self.precon[index] 

1508 

1509 def apply(self, all_forces, index=None): 

1510 """Apply preconditioners to stored images 

1511 

1512 Args: 

1513 all_forces (array): forces on images, shape (nimages, natoms, 3) 

1514 index (slice, optional): Which images to include. Defaults to all. 

1515 

1516 Returns 

1517 ------- 

1518 precon_forces: array of preconditioned forces 

1519 """ 

1520 if index is None: 

1521 index = slice(None) 

1522 precon_forces = [] 

1523 for precon, image, forces in zip( 

1524 self.precon[index], self.images[index], all_forces 

1525 ): 

1526 f_vec = forces.reshape(-1) 

1527 pf_vec = precon.apply(f_vec, image) 

1528 precon_forces.append(pf_vec.reshape(-1, 3)) 

1529 

1530 return np.array(precon_forces) 

1531 

1532 def average_norm(self, i, j, dx): 

1533 """Average norm between images i and j 

1534 

1535 Args: 

1536 i (int): left image 

1537 j (int): right image 

1538 dx (array): vector 

1539 

1540 Returns 

1541 ------- 

1542 norm: norm of vector wrt average of precons at i and j 

1543 """ 

1544 return np.sqrt( 

1545 0.5 * (self.precon[i].dot(dx, dx) + self.precon[j].dot(dx, dx)) 

1546 ) 

1547 

1548 def get_tangent(self, i): 

1549 """Normalised tangent vector at image i 

1550 

1551 Args: 

1552 i (int): image of interest 

1553 

1554 Returns 

1555 ------- 

1556 tangent: tangent vector, normalised with appropriate precon norm 

1557 """ 

1558 tangent = self.spline.dx_ds(self.spline.s[i]) 

1559 tangent /= self.precon[i].norm(tangent) 

1560 return tangent.reshape(-1, 3) 

1561 

1562 def get_residual(self, i, imgforce): 

1563 # residuals computed consistent with ASE-standard fmax norm 

1564 # (slight change from eq 11 of the paper) 

1565 P_dot_imgforce = self.precon[i].Pdot(imgforce.reshape(-1)) 

1566 return np.linalg.norm(P_dot_imgforce.reshape(-1, 3), axis=1).max() 

1567 

1568 def get_spring_force(self, i, k1, k2, tangent): 

1569 """Spring force on image 

1570 

1571 Args: 

1572 i (int): image of interest 

1573 k1 (float): spring constant for left spring 

1574 k2 (float): spring constant for right spring 

1575 tangent (array): tangent vector, shape (natoms, 3) 

1576 

1577 Returns 

1578 ------- 

1579 eta: NEB spring forces, shape (natoms, 3) 

1580 """ 

1581 # Definition following Eq. 9 in Paper IV 

1582 nimages = len(self.images) 

1583 k = 0.5 * (k1 + k2) / (nimages**2) 

1584 curvature = self.spline.d2x_ds2(self.spline.s[i]).reshape(-1, 3) 

1585 # complete Eq. 9 by including the spring force 

1586 eta = k * self.precon[i].vdot(curvature, tangent) * tangent 

1587 return eta 

1588 

1589 def get_coordinates(self, positions=None): 

1590 """Compute displacements wrt appropriate precon metric for each image 

1591 

1592 Args: 

1593 positions (list or array, optional) - images positions. 

1594 Shape either (nimages * natoms, 3) or ((nimages-2)*natoms, 3) 

1595 

1596 Returns 

1597 ------- 

1598 s : array shape (nimages,), reaction coordinates, in range [0, 1] 

1599 x : array shape (nimages, 3 * natoms), flat displacement vectors 

1600 """ 

1601 nimages = len(self.precon) 

1602 natoms = len(self.images[0]) 

1603 d_P = np.zeros(nimages) 

1604 x = np.zeros((nimages, 3 * natoms)) # flattened positions 

1605 if positions is None: 

1606 positions = [image.positions for image in self.images] 

1607 elif isinstance(positions, np.ndarray) and len(positions.shape) == 2: 

1608 positions = positions.reshape(-1, natoms, 3) 

1609 positions = [positions[i, :, :] for i in range(len(positions))] 

1610 if len(positions) == len(self.images) - 2: 

1611 # prepend and append the non-moving images 

1612 positions = ( 

1613 [self.images[0].positions] 

1614 + positions 

1615 + [self.images[-1].positions] 

1616 ) 

1617 assert len(positions) == len(self.images) 

1618 

1619 x[0, :] = positions[0].reshape(-1) 

1620 for i in range(1, nimages): 

1621 x[i, :] = positions[i].reshape(-1) 

1622 dx, _ = find_mic( 

1623 positions[i] - positions[i - 1], 

1624 self.images[i - 1].cell, 

1625 self.images[i - 1].pbc, 

1626 ) 

1627 dx = dx.reshape(-1) 

1628 d_P[i] = self.average_norm(i, i - 1, dx) 

1629 

1630 s = d_P.cumsum() / d_P.sum() # Eq. A1 in paper IV 

1631 return s, x 

1632 

1633 def spline_fit(self, positions=None): 

1634 """Fit 3 * natoms cubic splines as a function of reaction coordinate 

1635 

1636 Returns 

1637 ------- 

1638 fit : :class:`ase.optimize.precon.SplineFit` object 

1639 """ 

1640 s, x = self.get_coordinates(positions) 

1641 return SplineFit(s, x) 

1642 

1643 @property 

1644 def spline(self): 

1645 s, x = self.get_coordinates() 

1646 if self._spline and ( 

1647 np.abs(s - self._old_s).max() < 1e-6 

1648 and np.abs(x - self._old_x).max() < 1e-6 

1649 ): 

1650 return self._spline 

1651 

1652 self._spline = self.spline_fit() 

1653 self._old_s = s 

1654 self._old_x = x 

1655 return self._spline