Coverage for ase/calculators/qmmm.py: 90.99%

455 statements  

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

1from collections.abc import Sequence 

2 

3import numpy as np 

4 

5from ase.calculators.calculator import Calculator 

6from ase.cell import Cell 

7from ase.data import atomic_numbers 

8from ase.geometry import get_distances 

9from ase.parallel import world 

10from ase.utils import IOContext 

11 

12 

13class SimpleQMMM(Calculator): 

14 """Simple QMMM calculator.""" 

15 

16 implemented_properties = ['energy', 'forces'] 

17 

18 def __init__(self, selection, qmcalc, mmcalc1, mmcalc2, vacuum=None): 

19 """SimpleQMMM object. 

20 

21 The energy is calculated as:: 

22 

23 _ _ _ 

24 E = E (R ) - E (R ) + E (R ) 

25 QM QM MM QM MM all 

26 

27 parameters 

28 ---------- 

29 

30 selection: list of int, slice object or list of bool 

31 Selection out of all the atoms that belong to the QM part. 

32 qmcalc: Calculator object 

33 QM-calculator. 

34 mmcalc1: Calculator object 

35 MM-calculator used for QM region. 

36 mmcalc2: Calculator object 

37 MM-calculator used for everything. 

38 vacuum: float or None 

39 Amount of vacuum to add around QM atoms. Use None if QM 

40 calculator doesn't need a box. 

41 

42 """ 

43 self.selection = selection 

44 self.qmcalc = qmcalc 

45 self.mmcalc1 = mmcalc1 

46 self.mmcalc2 = mmcalc2 

47 self.vacuum = vacuum 

48 

49 self.qmatoms = None 

50 self.center = None 

51 

52 Calculator.__init__(self) 

53 

54 def _get_name(self): 

55 return f'{self.qmcalc.name}-{self.mmcalc1.name}+{self.mmcalc1.name}' 

56 

57 def initialize_qm(self, atoms): 

58 constraints = atoms.constraints 

59 atoms.constraints = [] 

60 self.qmatoms = atoms[self.selection] 

61 atoms.constraints = constraints 

62 self.qmatoms.pbc = False 

63 if self.vacuum: 

64 self.qmatoms.center(vacuum=self.vacuum) 

65 self.center = self.qmatoms.positions.mean(axis=0) 

66 

67 def calculate(self, atoms, properties, system_changes): 

68 Calculator.calculate(self, atoms, properties, system_changes) 

69 

70 if self.qmatoms is None: 

71 self.initialize_qm(atoms) 

72 

73 self.qmatoms.positions = atoms.positions[self.selection] 

74 if self.vacuum: 

75 self.qmatoms.positions += self.center - self.qmatoms.positions.mean( 

76 axis=0 

77 ) 

78 

79 energy = self.qmcalc.get_potential_energy(self.qmatoms) 

80 qmforces = self.qmcalc.get_forces(self.qmatoms) 

81 energy += self.mmcalc2.get_potential_energy(atoms) 

82 forces = self.mmcalc2.get_forces(atoms) 

83 

84 if self.vacuum: 

85 qmforces -= qmforces.mean(axis=0) 

86 forces[self.selection] += qmforces 

87 

88 energy -= self.mmcalc1.get_potential_energy(self.qmatoms) 

89 forces[self.selection] -= self.mmcalc1.get_forces(self.qmatoms) 

90 

91 self.results['energy'] = energy 

92 self.results['forces'] = forces 

93 

94 

95class EIQMMM(Calculator, IOContext): 

96 """Explicit interaction QMMM calculator.""" 

97 

98 implemented_properties = ['energy', 'forces'] 

99 

100 def __init__( 

101 self, 

102 selection, 

103 qmcalc, 

104 mmcalc, 

105 interaction, 

106 vacuum=None, 

107 embedding=None, 

108 output=None, 

109 comm=world, 

110 ): 

111 """EIQMMM object. 

112 

113 The energy is calculated as:: 

114 

115 _ _ _ _ 

116 E = E (R ) + E (R ) + E (R , R ) 

117 QM QM MM MM I QM MM 

118 

119 parameters 

120 ---------- 

121 

122 selection: list of int, slice object or list of bool 

123 Selection out of all the atoms that belong to the QM part. 

124 qmcalc: Calculator object 

125 QM-calculator. 

126 mmcalc: Calculator object 

127 MM-calculator. 

128 interaction: Interaction object 

129 Interaction between QM and MM regions. 

130 vacuum: float or None 

131 Amount of vacuum to add around QM atoms. Use None if QM 

132 calculator doesn't need a box. 

133 embedding: Embedding object or None 

134 Specialized embedding object. Use None in order to use the 

135 default one. 

136 output: None, '-', str or file-descriptor. 

137 File for logging information - default is no logging (None). 

138 

139 """ 

140 

141 self.selection = selection 

142 

143 self.qmcalc = qmcalc 

144 self.mmcalc = mmcalc 

145 self.interaction = interaction 

146 self.vacuum = vacuum 

147 self.embedding = embedding 

148 

149 self.qmatoms = None 

150 self.mmatoms = None 

151 self.mask = None 

152 self.center = None # center of QM atoms in QM-box 

153 

154 self.output = self.openfile(file=output, comm=comm) 

155 

156 Calculator.__init__(self) 

157 

158 def _get_name(self): 

159 return f'{self.qmcalc.name}+{self.interaction.name}+{self.mmcalc.name}' 

160 

161 def initialize(self, atoms): 

162 self.mask = np.zeros(len(atoms), bool) 

163 self.mask[self.selection] = True 

164 

165 constraints = atoms.constraints 

166 atoms.constraints = [] # avoid slicing of constraints 

167 self.qmatoms = atoms[self.mask] 

168 self.mmatoms = atoms[~self.mask] 

169 atoms.constraints = constraints 

170 

171 self.qmatoms.pbc = False 

172 

173 if self.vacuum: 

174 self.qmatoms.center(vacuum=self.vacuum) 

175 self.center = self.qmatoms.positions.mean(axis=0) 

176 print( 

177 'Size of QM-cell after centering:', 

178 self.qmatoms.cell.diagonal(), 

179 file=self.output, 

180 ) 

181 

182 self.qmatoms.calc = self.qmcalc 

183 self.mmatoms.calc = self.mmcalc 

184 

185 if self.embedding is None: 

186 self.embedding = Embedding() 

187 

188 self.embedding.initialize(self.qmatoms, self.mmatoms) 

189 print('Embedding:', self.embedding, file=self.output) 

190 

191 def calculate(self, atoms, properties, system_changes): 

192 Calculator.calculate(self, atoms, properties, system_changes) 

193 

194 if self.qmatoms is None: 

195 self.initialize(atoms) 

196 

197 self.mmatoms.set_positions(atoms.positions[~self.mask]) 

198 self.qmatoms.set_positions(atoms.positions[self.mask]) 

199 

200 if self.vacuum: 

201 shift = self.center - self.qmatoms.positions.mean(axis=0) 

202 self.qmatoms.positions += shift 

203 else: 

204 shift = (0, 0, 0) 

205 

206 self.embedding.update(shift) 

207 

208 ienergy, iqmforces, immforces = self.interaction.calculate( 

209 self.qmatoms, self.mmatoms, shift 

210 ) 

211 

212 qmenergy = self.qmatoms.get_potential_energy() 

213 mmenergy = self.mmatoms.get_potential_energy() 

214 energy = ienergy + qmenergy + mmenergy 

215 

216 print( 

217 'Energies: {:12.3f} {:+12.3f} {:+12.3f} = {:12.3f}'.format( 

218 ienergy, qmenergy, mmenergy, energy 

219 ), 

220 file=self.output, 

221 ) 

222 

223 qmforces = self.qmatoms.get_forces() 

224 mmforces = self.mmatoms.get_forces() 

225 

226 mmforces += self.embedding.get_mm_forces() 

227 

228 forces = np.empty((len(atoms), 3)) 

229 forces[self.mask] = qmforces + iqmforces 

230 forces[~self.mask] = mmforces + immforces 

231 

232 self.results['energy'] = energy 

233 self.results['forces'] = forces 

234 

235 

236def wrap(D, cell, pbc): 

237 """Wrap distances to nearest neighbor (minimum image convention).""" 

238 for i, periodic in enumerate(pbc): 

239 if periodic: 

240 d = D[:, i] 

241 L = cell[i] 

242 d[:] = (d + L / 2) % L - L / 2 # modify D inplace 

243 

244 

245class Embedding: 

246 def __init__(self, molecule_size=3, **parameters): 

247 """Point-charge embedding.""" 

248 self.qmatoms = None 

249 self.mmatoms = None 

250 self.molecule_size = molecule_size 

251 self.virtual_molecule_size = None 

252 self.parameters = parameters 

253 

254 def __repr__(self): 

255 return f'Embedding(molecule_size={self.molecule_size})' 

256 

257 def initialize(self, qmatoms, mmatoms): 

258 """Hook up embedding object to QM and MM atoms objects.""" 

259 self.qmatoms = qmatoms 

260 self.mmatoms = mmatoms 

261 charges = mmatoms.calc.get_virtual_charges(mmatoms) 

262 self.pcpot = qmatoms.calc.embed(charges, **self.parameters) 

263 self.virtual_molecule_size = ( 

264 self.molecule_size * len(charges) // len(mmatoms) 

265 ) 

266 

267 def update(self, shift): 

268 """Update point-charge positions.""" 

269 # Wrap point-charge positions to the MM-cell closest to the 

270 # center of the the QM box, but avoid ripping molecules apart: 

271 qmcenter = self.qmatoms.positions.mean(axis=0) 

272 # if counter ions are used, then molecule_size has more than 1 value 

273 if self.mmatoms.calc.name == 'combinemm': 

274 mask1 = self.mmatoms.calc.mask 

275 mask2 = ~mask1 

276 vmask1 = self.mmatoms.calc.virtual_mask 

277 vmask2 = ~vmask1 

278 apm1 = self.mmatoms.calc.apm1 

279 apm2 = self.mmatoms.calc.apm2 

280 spm1 = self.mmatoms.calc.atoms1.calc.sites_per_mol 

281 spm2 = self.mmatoms.calc.atoms2.calc.sites_per_mol 

282 pos = self.mmatoms.positions 

283 pos1 = pos[mask1].reshape((-1, apm1, 3)) 

284 pos2 = pos[mask2].reshape((-1, apm2, 3)) 

285 pos = (pos1, pos2) 

286 else: 

287 pos = (self.mmatoms.positions,) 

288 apm1 = self.molecule_size 

289 apm2 = self.molecule_size 

290 # This is only specific to calculators where apm != spm, 

291 # i.e. TIP4P. Non-native MM calcs do not have this attr. 

292 if hasattr(self.mmatoms.calc, 'sites_per_mol'): 

293 spm1 = self.mmatoms.calc.sites_per_mol 

294 spm2 = self.mmatoms.calc.sites_per_mol 

295 else: 

296 spm1 = self.molecule_size 

297 spm2 = spm1 

298 mask1 = np.ones(len(self.mmatoms), dtype=bool) 

299 mask2 = mask1 

300 

301 wrap_pos = np.zeros_like(self.mmatoms.positions) 

302 com_all = [] 

303 apm = (apm1, apm2) 

304 mask = (mask1, mask2) 

305 spm = (spm1, spm2) 

306 for p, n, m, vn in zip(pos, apm, mask, spm): 

307 positions = p.reshape((-1, n, 3)) + shift 

308 

309 # Distances from the center of the QM box to the first atom of 

310 # each molecule: 

311 distances = positions[:, 0] - qmcenter 

312 

313 wrap(distances, self.mmatoms.cell.diagonal(), self.mmatoms.pbc) 

314 offsets = distances - positions[:, 0] 

315 positions += offsets[:, np.newaxis] + qmcenter 

316 

317 # Geometric center positions for each mm mol for LR cut 

318 com = np.array([p.mean(axis=0) for p in positions]) 

319 # Need per atom for C-code: 

320 com_pv = np.repeat(com, vn, axis=0) 

321 com_all.append(com_pv) 

322 

323 wrap_pos[m] = positions.reshape((-1, 3)) 

324 

325 positions = wrap_pos.copy() 

326 positions = self.mmatoms.calc.add_virtual_sites(positions) 

327 

328 if self.mmatoms.calc.name == 'combinemm': 

329 com_pv = np.zeros_like(positions) 

330 for ii, m in enumerate((vmask1, vmask2)): 

331 com_pv[m] = com_all[ii] 

332 

333 # compatibility with gpaw versions w/o LR cut in PointChargePotential 

334 if 'rc2' in self.parameters: 

335 self.pcpot.set_positions(positions, com_pv=com_pv) 

336 else: 

337 self.pcpot.set_positions(positions) 

338 

339 def get_mm_forces(self): 

340 """Calculate the forces on the MM-atoms from the QM-part.""" 

341 f = self.pcpot.get_forces(self.qmatoms.calc) 

342 return self.mmatoms.calc.redistribute_forces(f) 

343 

344 

345def combine_lj_lorenz_berthelot(sigmaqm, sigmamm, epsilonqm, epsilonmm): 

346 """Combine LJ parameters according to the Lorenz-Berthelot rule""" 

347 sigma = [] 

348 epsilon = [] 

349 # check if input is tuple of vals for more than 1 mm calc, or only for 1. 

350 if isinstance(sigmamm, Sequence): 

351 numcalcs = len(sigmamm) 

352 else: 

353 numcalcs = 1 # if only 1 mm calc, eps and sig are simply np arrays 

354 sigmamm = (sigmamm,) 

355 epsilonmm = (epsilonmm,) 

356 for cc in range(numcalcs): 

357 sigma_c = np.zeros((len(sigmaqm), len(sigmamm[cc]))) 

358 epsilon_c = np.zeros_like(sigma_c) 

359 

360 for ii in range(len(sigmaqm)): 

361 sigma_c[ii, :] = (sigmaqm[ii] + sigmamm[cc]) / 2 

362 epsilon_c[ii, :] = (epsilonqm[ii] * epsilonmm[cc]) ** 0.5 

363 sigma.append(sigma_c) 

364 epsilon.append(epsilon_c) 

365 

366 if numcalcs == 1: # retain original, 1 calc function 

367 sigma = np.array(sigma[0]) 

368 epsilon = np.array(epsilon[0]) 

369 

370 return sigma, epsilon 

371 

372 

373class LJInteractionsGeneral: 

374 name = 'LJ-general' 

375 

376 def __init__( 

377 self, 

378 sigmaqm, 

379 epsilonqm, 

380 sigmamm, 

381 epsilonmm, 

382 qm_molecule_size, 

383 mm_molecule_size=3, 

384 rc=np.inf, 

385 width=1.0, 

386 ): 

387 """General Lennard-Jones type explicit interaction. 

388 

389 sigmaqm: array 

390 Array of sigma-parameters which should have the length of the QM 

391 subsystem 

392 epsilonqm: array 

393 As sigmaqm, but for epsilon-paramaters 

394 sigmamm: Either array (A) or tuple (B) 

395 A (no counterions): 

396 Array of sigma-parameters with the length of the smallests 

397 repeating atoms-group (i.e. molecule) of the MM subsystem 

398 B (counterions): 

399 Tuple: (arr1, arr2), where arr1 is an array of sigmas with 

400 the length of counterions in the MM subsystem, and 

401 arr2 is the array from A. 

402 epsilonmm: array or tuple 

403 As sigmamm but for epsilon-parameters. 

404 qm_molecule_size: int 

405 number of atoms of the smallest repeating atoms-group (i.e. 

406 molecule) in the QM subsystem (often just the number of atoms 

407 in the QM subsystem) 

408 mm_molecule_size: int 

409 as qm_molecule_size but for the MM subsystem. Will be overwritten 

410 if counterions are present in the MM subsystem (via the CombineMM 

411 calculator) 

412 

413 """ 

414 self.sigmaqm = sigmaqm 

415 self.epsilonqm = epsilonqm 

416 self.sigmamm = sigmamm 

417 self.epsilonmm = epsilonmm 

418 self.qms = qm_molecule_size 

419 self.mms = mm_molecule_size 

420 self.rc = rc 

421 self.width = width 

422 self.combine_lj() 

423 

424 def combine_lj(self): 

425 self.sigma, self.epsilon = combine_lj_lorenz_berthelot( 

426 self.sigmaqm, self.sigmamm, self.epsilonqm, self.epsilonmm 

427 ) 

428 

429 def calculate(self, qmatoms, mmatoms, shift): 

430 epsilon = self.epsilon 

431 sigma = self.sigma 

432 

433 # loop over possible multiple mm calculators 

434 # currently 1 or 2, but could be generalized in the future... 

435 apm1 = self.mms 

436 mask1 = np.ones(len(mmatoms), dtype=bool) 

437 mask2 = mask1 

438 apm = (apm1,) 

439 sigma = (sigma,) 

440 epsilon = (epsilon,) 

441 if hasattr(mmatoms.calc, 'name'): 

442 if mmatoms.calc.name == 'combinemm': 

443 mask1 = mmatoms.calc.mask 

444 mask2 = ~mask1 

445 apm1 = mmatoms.calc.apm1 

446 apm2 = mmatoms.calc.apm2 

447 apm = (apm1, apm2) 

448 sigma = sigma[0] # Was already loopable 2-tuple 

449 epsilon = epsilon[0] 

450 

451 mask = (mask1, mask2) 

452 e_all = 0 

453 qmforces_all = np.zeros_like(qmatoms.positions) 

454 mmforces_all = np.zeros_like(mmatoms.positions) 

455 

456 # zip stops at shortest tuple so we dont double count 

457 # cases of no counter ions. 

458 for n, m, eps, sig in zip(apm, mask, epsilon, sigma): 

459 mmpositions = self.update(qmatoms, mmatoms[m], n, shift) 

460 qmforces = np.zeros_like(qmatoms.positions) 

461 mmforces = np.zeros_like(mmatoms[m].positions) 

462 energy = 0.0 

463 

464 qmpositions = qmatoms.positions.reshape((-1, self.qms, 3)) 

465 

466 for q, qmpos in enumerate(qmpositions): # molwise loop 

467 # cutoff from first atom of each mol 

468 R00 = mmpositions[:, 0] - qmpos[0, :] 

469 d002 = (R00**2).sum(1) 

470 d00 = d002**0.5 

471 x1 = d00 > self.rc - self.width 

472 x2 = d00 < self.rc 

473 x12 = np.logical_and(x1, x2) 

474 y = (d00[x12] - self.rc + self.width) / self.width 

475 t = np.zeros(len(d00)) 

476 t[x2] = 1.0 

477 t[x12] -= y**2 * (3.0 - 2.0 * y) 

478 dt = np.zeros(len(d00)) 

479 dt[x12] -= 6.0 / self.width * y * (1.0 - y) 

480 for qa in range(len(qmpos)): 

481 if ~np.any(eps[qa, :]): 

482 continue 

483 R = mmpositions - qmpos[qa, :] 

484 d2 = (R**2).sum(2) 

485 c6 = (sig[qa, :] ** 2 / d2) ** 3 

486 c12 = c6**2 

487 e = 4 * eps[qa, :] * (c12 - c6) 

488 energy += np.dot(e.sum(1), t) 

489 f = ( 

490 t[:, None, None] 

491 * (24 * eps[qa, :] * (2 * c12 - c6) / d2)[:, :, None] 

492 * R 

493 ) 

494 f00 = -(e.sum(1) * dt / d00)[:, None] * R00 

495 mmforces += f.reshape((-1, 3)) 

496 qmforces[q * self.qms + qa, :] -= f.sum(0).sum(0) 

497 qmforces[q * self.qms, :] -= f00.sum(0) 

498 mmforces[::n, :] += f00 

499 

500 e_all += energy 

501 qmforces_all += qmforces 

502 mmforces_all[m] += mmforces 

503 

504 return e_all, qmforces_all, mmforces_all 

505 

506 def update(self, qmatoms, mmatoms, n, shift): 

507 # Wrap point-charge positions to the MM-cell closest to the 

508 # center of the the QM box, but avoid ripping molecules apart: 

509 qmcenter = qmatoms.cell.diagonal() / 2 

510 positions = mmatoms.positions.reshape((-1, n, 3)) + shift 

511 

512 # Distances from the center of the QM box to the first atom of 

513 # each molecule: 

514 distances = positions[:, 0] - qmcenter 

515 

516 wrap(distances, mmatoms.cell.diagonal(), mmatoms.pbc) 

517 offsets = distances - positions[:, 0] 

518 positions += offsets[:, np.newaxis] + qmcenter 

519 

520 return positions 

521 

522 

523class LJInteractions: 

524 name = 'LJ' 

525 

526 def __init__(self, parameters): 

527 """Lennard-Jones type explicit interaction. 

528 

529 parameters: dict 

530 Mapping from pair of atoms to tuple containing epsilon and sigma 

531 for that pair. 

532 

533 Example: 

534 

535 lj = LJInteractions({('O', 'O'): (eps, sigma)}) 

536 

537 """ 

538 self.parameters = {} 

539 for (symbol1, symbol2), (epsilon, sigma) in parameters.items(): 

540 Z1 = atomic_numbers[symbol1] 

541 Z2 = atomic_numbers[symbol2] 

542 self.parameters[(Z1, Z2)] = epsilon, sigma 

543 self.parameters[(Z2, Z1)] = epsilon, sigma 

544 

545 def calculate(self, qmatoms, mmatoms, shift): 

546 qmforces = np.zeros_like(qmatoms.positions) 

547 mmforces = np.zeros_like(mmatoms.positions) 

548 species = set(mmatoms.numbers) 

549 energy = 0.0 

550 for R1, Z1, F1 in zip(qmatoms.positions, qmatoms.numbers, qmforces): 

551 for Z2 in species: 

552 if (Z1, Z2) not in self.parameters: 

553 continue 

554 epsilon, sigma = self.parameters[(Z1, Z2)] 

555 mask = mmatoms.numbers == Z2 

556 D = mmatoms.positions[mask] + shift - R1 

557 wrap(D, mmatoms.cell.diagonal(), mmatoms.pbc) 

558 d2 = (D**2).sum(1) 

559 c6 = (sigma**2 / d2) ** 3 

560 c12 = c6**2 

561 energy += 4 * epsilon * (c12 - c6).sum() 

562 f = 24 * epsilon * ((2 * c12 - c6) / d2)[:, np.newaxis] * D 

563 F1 -= f.sum(0) 

564 mmforces[mask] += f 

565 return energy, qmforces, mmforces 

566 

567 

568class RescaledCalculator(Calculator): 

569 """Rescales length and energy of a calculators to match given 

570 lattice constant and bulk modulus 

571 

572 Useful for MM calculator used within a :class:`ForceQMMM` model. 

573 See T. D. Swinburne and J. R. Kermode, Phys. Rev. B 96, 144102 (2017) 

574 for a derivation of the scaling constants. 

575 """ 

576 

577 implemented_properties = ['forces', 'energy', 'stress'] 

578 

579 def __init__( 

580 self, 

581 mm_calc, 

582 qm_lattice_constant, 

583 qm_bulk_modulus, 

584 mm_lattice_constant, 

585 mm_bulk_modulus, 

586 ): 

587 Calculator.__init__(self) 

588 self.mm_calc = mm_calc 

589 self.alpha = qm_lattice_constant / mm_lattice_constant 

590 self.beta = mm_bulk_modulus / qm_bulk_modulus / (self.alpha**3) 

591 

592 def calculate(self, atoms, properties, system_changes): 

593 Calculator.calculate(self, atoms, properties, system_changes) 

594 

595 # mm_pos = atoms.get_positions() 

596 scaled_atoms = atoms.copy() 

597 

598 # scaled_atoms.positions = mm_pos/self.alpha 

599 mm_cell = atoms.get_cell() 

600 scaled_atoms.set_cell(mm_cell / self.alpha, scale_atoms=True) 

601 

602 results = {} 

603 

604 if 'energy' in properties: 

605 energy = self.mm_calc.get_potential_energy(scaled_atoms) 

606 results['energy'] = energy / self.beta 

607 

608 if 'forces' in properties: 

609 forces = self.mm_calc.get_forces(scaled_atoms) 

610 results['forces'] = forces / (self.beta * self.alpha) 

611 

612 if 'stress' in properties: 

613 stress = self.mm_calc.get_stress(scaled_atoms) 

614 results['stress'] = stress / (self.beta * self.alpha**3) 

615 

616 self.results = results 

617 

618 

619class ForceConstantCalculator(Calculator): 

620 """ 

621 Compute forces based on provided force-constant matrix 

622 

623 Useful with `ForceQMMM` to do harmonic QM/MM using force constants 

624 of QM method. 

625 """ 

626 

627 implemented_properties = ['forces', 'energy'] 

628 

629 def __init__(self, D, ref, f0): 

630 """ 

631 Parameters 

632 ---------- 

633 

634 D: matrix or sparse matrix, shape `(3*len(ref), 3*len(ref))` 

635 Force constant matrix. 

636 Sign convention is `D_ij = d^2E/(dx_i dx_j), so 

637 `force = -D.dot(displacement)` 

638 ref: ase.atoms.Atoms 

639 Atoms object for reference configuration 

640 f0: array, shape `(len(ref), 3)` 

641 Value of forces at reference configuration 

642 """ 

643 assert D.shape[0] == D.shape[1] 

644 assert D.shape[0] // 3 == len(ref) 

645 self.D = D 

646 self.ref = ref 

647 self.f0 = f0 

648 self.size = len(ref) 

649 Calculator.__init__(self) 

650 

651 def calculate(self, atoms, properties, system_changes): 

652 Calculator.calculate(self, atoms, properties, system_changes) 

653 u = atoms.positions - self.ref.positions 

654 f = -self.D.dot(u.reshape(3 * self.size)) 

655 forces = np.zeros((len(atoms), 3)) 

656 forces[:, :] = f.reshape(self.size, 3) 

657 self.results['forces'] = forces + self.f0 

658 self.results['energy'] = 0.0 

659 

660 

661class ForceQMMM(Calculator): 

662 """ 

663 Force-based QM/MM calculator 

664 

665 QM forces are computed using a buffer region and then mixed abruptly 

666 with MM forces: 

667 

668 F^i_QMMM = { F^i_QM if i in QM region 

669 { F^i_MM otherwise 

670 

671 cf. N. Bernstein, J. R. Kermode, and G. Csanyi, 

672 Rep. Prog. Phys. 72, 026501 (2009) 

673 and T. D. Swinburne and J. R. Kermode, Phys. Rev. B 96, 144102 (2017). 

674 """ 

675 

676 implemented_properties = ['forces', 'energy'] 

677 

678 def __init__( 

679 self, 

680 atoms, 

681 qm_selection_mask, 

682 qm_calc, 

683 mm_calc, 

684 buffer_width, 

685 vacuum=5.0, 

686 zero_mean=True, 

687 qm_cell_round_off=3, 

688 qm_radius=None, 

689 ): 

690 """ 

691 ForceQMMM calculator 

692 

693 Parameters 

694 ---------- 

695 

696 qm_selection_mask: list of ints, slice object or bool list/array 

697 Selection out of atoms that belong to the QM region. 

698 qm_calc: Calculator object 

699 QM-calculator. 

700 mm_calc: Calculator object 

701 MM-calculator (should be scaled, see :class:`RescaledCalculator`) 

702 Can use `ForceConstantCalculator` based on QM force constants, if 

703 available. 

704 vacuum: float or None 

705 Amount of vacuum to add around QM atoms. 

706 zero_mean: bool 

707 If True, add a correction to zero the mean force in each direction 

708 qm_cell_round_off: float 

709 Tolerance value in Angstrom to round the qm cluster cell 

710 qm_radius: 3x1 array of floats qm_radius for [x, y, z] 

711 3d qm radius for calculation of qm cluster cell. default is None 

712 and the radius is estimated from maximum distance between the atoms 

713 in qm region. 

714 """ 

715 

716 if len(atoms[qm_selection_mask]) == 0: 

717 raise ValueError('no QM atoms selected!') 

718 

719 self.qm_selection_mask = qm_selection_mask 

720 self.qm_calc = qm_calc 

721 self.mm_calc = mm_calc 

722 self.vacuum = vacuum 

723 self.buffer_width = buffer_width 

724 self.zero_mean = zero_mean 

725 self.qm_cell_round_off = qm_cell_round_off 

726 self.qm_radius = qm_radius 

727 

728 self.qm_buffer_mask = None 

729 

730 Calculator.__init__(self) 

731 

732 def initialize_qm_buffer_mask(self, atoms): 

733 """ 

734 Initialises system to perform qm calculation 

735 """ 

736 # calculate the distances between all atoms and qm atoms 

737 # qm_distance_matrix is a [N_QM_atoms x N_atoms] matrix 

738 _, qm_distance_matrix = get_distances( 

739 atoms.positions[self.qm_selection_mask], 

740 atoms.positions, 

741 atoms.cell, 

742 atoms.pbc, 

743 ) 

744 

745 self.qm_buffer_mask = np.zeros(len(atoms), dtype=bool) 

746 

747 # every r_qm is a matrix of distances 

748 # from an atom in qm region and all atoms with size [N_atoms] 

749 for r_qm in qm_distance_matrix: 

750 self.qm_buffer_mask[r_qm < self.buffer_width] = True 

751 

752 def get_qm_cluster(self, atoms): 

753 

754 if self.qm_buffer_mask is None: 

755 self.initialize_qm_buffer_mask(atoms) 

756 

757 qm_cluster = atoms[self.qm_buffer_mask] 

758 del qm_cluster.constraints 

759 

760 round_cell = False 

761 if self.qm_radius is None: 

762 round_cell = True 

763 # get all distances between qm atoms. 

764 # Treat all X, Y and Z directions independently 

765 # only distance between qm atoms is calculated 

766 # in order to estimate qm radius in thee directions 

767 R_qm, _ = get_distances( 

768 atoms.positions[self.qm_selection_mask], 

769 cell=atoms.cell, 

770 pbc=atoms.pbc, 

771 ) 

772 # estimate qm radius in three directions as 1/2 

773 # of max distance between qm atoms 

774 self.qm_radius = np.amax(np.amax(R_qm, axis=1), axis=0) * 0.5 

775 

776 if atoms.cell.orthorhombic: 

777 cell_size = np.diagonal(atoms.cell) 

778 else: 

779 raise RuntimeError('NON-orthorhombic cell is not supported!') 

780 

781 # check if qm_cluster should be left periodic 

782 # in periodic directions of the cell (cell[i] < qm_radius + buffer 

783 # otherwise change to non pbc 

784 # and make a cluster in a vacuum configuration 

785 qm_cluster_pbc = atoms.pbc & ( 

786 cell_size < 2.0 * (self.qm_radius + self.buffer_width) 

787 ) 

788 

789 # start with the original orthorhombic cell 

790 qm_cluster_cell = cell_size.copy() 

791 # create a cluster in a vacuum cell in non periodic directions 

792 qm_cluster_cell[~qm_cluster_pbc] = 2.0 * ( 

793 self.qm_radius[~qm_cluster_pbc] + self.buffer_width + self.vacuum 

794 ) 

795 

796 if round_cell: 

797 # round the qm cell to the required tolerance 

798 qm_cluster_cell[~qm_cluster_pbc] = ( 

799 np.round( 

800 (qm_cluster_cell[~qm_cluster_pbc]) / self.qm_cell_round_off 

801 ) 

802 * self.qm_cell_round_off 

803 ) 

804 

805 qm_cluster.set_cell(Cell(np.diag(qm_cluster_cell))) 

806 qm_cluster.pbc = qm_cluster_pbc 

807 

808 qm_shift = 0.5 * qm_cluster.cell.diagonal() - qm_cluster.positions.mean( 

809 axis=0 

810 ) 

811 

812 if 'cell_origin' in qm_cluster.info: 

813 del qm_cluster.info['cell_origin'] 

814 

815 # center the cluster only in non pbc directions 

816 qm_cluster.positions[:, ~qm_cluster_pbc] += qm_shift[~qm_cluster_pbc] 

817 

818 return qm_cluster 

819 

820 def calculate(self, atoms, properties, system_changes): 

821 Calculator.calculate(self, atoms, properties, system_changes) 

822 

823 qm_cluster = self.get_qm_cluster(atoms) 

824 

825 forces = self.mm_calc.get_forces(atoms) 

826 qm_forces = self.qm_calc.get_forces(qm_cluster) 

827 

828 forces[self.qm_selection_mask] = qm_forces[ 

829 self.qm_selection_mask[self.qm_buffer_mask] 

830 ] 

831 

832 if self.zero_mean: 

833 # Target is that: forces.sum(axis=1) == [0., 0., 0.] 

834 forces[:] -= forces.mean(axis=0) 

835 

836 self.results['forces'] = forces 

837 self.results['energy'] = 0.0 

838 

839 def get_region_from_masks(self, atoms=None, print_mapping=False): 

840 """ 

841 creates region array from the masks of the calculators. The tags in 

842 the array are: 

843 QM - qm atoms 

844 buffer - buffer atoms 

845 MM - atoms treated with mm calculator 

846 """ 

847 if atoms is None: 

848 if self.atoms is None: 

849 raise ValueError('Calculator has no atoms') 

850 else: 

851 atoms = self.atoms 

852 

853 region = np.full_like(atoms, 'MM') 

854 

855 region[self.qm_selection_mask] = np.full_like( 

856 region[self.qm_selection_mask], 'QM' 

857 ) 

858 

859 buffer_only_mask = self.qm_buffer_mask & ~self.qm_selection_mask 

860 

861 region[buffer_only_mask] = np.full_like( 

862 region[buffer_only_mask], 'buffer' 

863 ) 

864 

865 if print_mapping: 

866 print(f'Mapping of {len(region):5d} atoms in total:') 

867 for region_id in np.unique(region): 

868 n_at = np.count_nonzero(region == region_id) 

869 print(f'{n_at:16d} {region_id}') 

870 

871 qm_atoms = atoms[self.qm_selection_mask] 

872 symbol_counts = qm_atoms.symbols.formula.count() 

873 print('QM atoms types:') 

874 for symbol, count in symbol_counts.items(): 

875 print(f'{count:16d} {symbol}') 

876 

877 return region 

878 

879 def set_masks_from_region(self, region): 

880 """ 

881 Sets masks from provided region array 

882 """ 

883 self.qm_selection_mask = region == 'QM' 

884 buffer_mask = region == 'buffer' 

885 

886 self.qm_buffer_mask = self.qm_selection_mask ^ buffer_mask 

887 

888 def export_extxyz(self, atoms=None, filename='qmmm_atoms.xyz'): 

889 """ 

890 exports the atoms to extended xyz file with additional "region" 

891 array keeping the mapping between QM, buffer and MM parts of 

892 the simulation 

893 """ 

894 if atoms is None: 

895 if self.atoms is None: 

896 raise ValueError('Calculator has no atoms') 

897 else: 

898 atoms = self.atoms 

899 

900 region = self.get_region_from_masks(atoms=atoms) 

901 

902 atoms_copy = atoms.copy() 

903 atoms_copy.new_array('region', region) 

904 

905 atoms_copy.calc = self # to keep the calculation results 

906 

907 atoms_copy.write(filename, format='extxyz') 

908 

909 @classmethod 

910 def import_extxyz(cls, filename, qm_calc, mm_calc): 

911 """ 

912 A static method to import the the mapping from an estxyz file saved by 

913 export_extxyz() function 

914 Parameters 

915 ---------- 

916 filename: string 

917 filename with saved configuration 

918 

919 qm_calc: Calculator object 

920 QM-calculator. 

921 mm_calc: Calculator object 

922 MM-calculator (should be scaled, see :class:`RescaledCalculator`) 

923 Can use `ForceConstantCalculator` based on QM force constants, if 

924 available. 

925 

926 Returns 

927 ------- 

928 New object of ForceQMMM calculator with qm_selection_mask and 

929 qm_buffer_mask set according to the region array in the saved file 

930 """ 

931 

932 from ase.io import read 

933 

934 atoms = read(filename, format='extxyz') 

935 

936 if 'region' in atoms.arrays: 

937 region = atoms.get_array('region') 

938 else: 

939 raise RuntimeError("Please provide extxyz file with 'region' array") 

940 

941 dummy_qm_mask = np.full_like(atoms, False, dtype=bool) 

942 dummy_qm_mask[0] = True 

943 

944 self = cls(atoms, dummy_qm_mask, qm_calc, mm_calc, buffer_width=1.0) 

945 

946 self.set_masks_from_region(region) 

947 

948 return self