Coverage for ase/md/nose_hoover_chain.py: 98.65%

370 statements  

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

1from __future__ import annotations 

2 

3import numpy as np 

4import numpy.typing as npt 

5from scipy.special import exprel 

6 

7import ase.units 

8from ase import Atoms 

9from ase.md.md import MolecularDynamics 

10 

11# Coefficients for the fourth-order Suzuki-Yoshida integration scheme 

12# Ref: H. Yoshida, Phys. Lett. A 150, 5-7, 262-268 (1990). 

13# https://doi.org/10.1016/0375-9601(90)90092-3 

14FOURTH_ORDER_COEFFS = [ 

15 1 / (2 - 2 ** (1 / 3)), 

16 -(2 ** (1 / 3)) / (2 - 2 ** (1 / 3)), 

17 1 / (2 - 2 ** (1 / 3)), 

18] 

19 

20 

21class NoseHooverChainNVT(MolecularDynamics): 

22 """Isothermal molecular dynamics with Nose-Hoover chain. 

23 

24 This implementation is based on the Nose-Hoover chain equations and 

25 the Liouville-operator derived integrator for non-Hamiltonian systems [1-3]. 

26 

27 - [1] G. J. Martyna, M. L. Klein, and M. E. Tuckerman, J. Chem. Phys. 97, 

28 2635 (1992). https://doi.org/10.1063/1.463940 

29 - [2] M. E. Tuckerman, J. Alejandre, R. López-Rendón, A. L. Jochim, 

30 and G. J. Martyna, J. Phys. A: Math. Gen. 39, 5629 (2006). 

31 https://doi.org/10.1088/0305-4470/39/19/S18 

32 - [3] M. E. Tuckerman, Statistical Mechanics: Theory and Molecular 

33 Simulation, Oxford University Press (2010). 

34 

35 While the algorithm and notation for the thermostat are largely adapted 

36 from Ref. [4], the core equations are detailed in the implementation 

37 note available at https://arxiv.org/abs/2603.24061. 

38 

39 - [4] M. E. Tuckerman, Statistical Mechanics: Theory and Molecular 

40 Simulation, 2nd ed. (Oxford University Press, 2009). 

41 

42 Constraints are applied with the RATTLE algorithm in the velocity-Verlet 

43 part of the propagator. In the notation of Zhang et al. [5], this is the 

44 T-C2-p-C1-x-p-T factorization, applied from right to left. 

45 

46 - [5] Z. Zhang, X. Liu, K. Yan, M. E. Tuckerman, and J. Liu, 

47 J. Phys. Chem. A 123, 6056 (2019). 

48 

49 .. versionadded:: 3.30.0 

50 Constraints are applied based on the RATTLE algorithm. 

51 

52 """ 

53 

54 def __init__( 

55 self, 

56 atoms: Atoms, 

57 timestep: float, 

58 temperature_K: float, 

59 tdamp: float, 

60 tchain: int = 3, 

61 tloop: int = 1, 

62 **kwargs, 

63 ): 

64 """ 

65 Parameters 

66 ---------- 

67 atoms: ase.Atoms 

68 The atoms object. 

69 timestep: float 

70 The time step in ASE time units. 

71 temperature_K: float 

72 The target temperature in K. 

73 tdamp: float 

74 The characteristic time scale for the thermostat in ASE time units. 

75 Typically, it is set to 100 times of `timestep`. 

76 tchain: int 

77 The number of thermostat variables in the Nose-Hoover chain. 

78 tloop: int 

79 The number of sub-steps in thermostat integration. 

80 **kwargs : dict, optional 

81 Additional arguments passed to :class:~ase.md.md.MolecularDynamics 

82 base class. 

83 

84 Physical background and limitations 

85 ----------------------------------- 

86 

87 In Nosé-Hoover dynamics, an extra term is added to the Hamiltonian 

88 representing the coupling to the heat bath. From a pragmatic point of 

89 view one can regard Nosé-Hoover dynamics as adding a friction term to 

90 Newton's second law, but dynamically changing the friction coefficient 

91 to move the system towards the desired temperature. Typically the 

92 "friction coefficient" will fluctuate around zero. To give a more 

93 stable dynamics, the friction coefficient is itself thermalized in the 

94 same way, leading to a chain of thermostats (a **Nosé-Hoover chain**, 

95 in ASE by default the chain length is 3). 

96 """ 

97 super().__init__( 

98 atoms=atoms, 

99 timestep=timestep, 

100 **kwargs, 

101 ) 

102 assert self.masses.shape == (len(self.atoms), 1) 

103 

104 self._thermostat = NoseHooverChainThermostat( 

105 ndof=self.atoms.get_number_of_degrees_of_freedom(), 

106 masses=self.masses, 

107 temperature_K=temperature_K, 

108 tdamp=tdamp, 

109 tchain=tchain, 

110 tloop=tloop, 

111 ) 

112 

113 # The following variables are updated during self.step() 

114 self._q = self.atoms.get_positions() 

115 self._p = self.atoms.get_momenta() 

116 

117 def step(self) -> None: 

118 dt2 = self.dt / 2 

119 self._p = self._thermostat.integrate_nhc(self._p, dt2) 

120 self._integrate_p(dt2, apply_constraint=False) 

121 self._integrate_q(self.dt, apply_constraint=True) 

122 self._integrate_p(dt2, apply_constraint=True) 

123 self._p = self._thermostat.integrate_nhc(self._p, dt2) 

124 

125 self._update_atoms() 

126 

127 def get_conserved_energy(self) -> float: 

128 """Return the conserved energy-like quantity. 

129 

130 This method is mainly used for testing. 

131 """ 

132 conserved_energy = ( 

133 self.atoms.get_potential_energy(force_consistent=True) 

134 + self.atoms.get_kinetic_energy() 

135 + self._thermostat.get_thermostat_energy() 

136 ) 

137 return float(conserved_energy) 

138 

139 def _update_atoms(self) -> None: 

140 # Note: Constraints are applied in `_integrate_q` and `_integrate_p`. 

141 self.atoms.set_positions(self._q, apply_constraint=False) 

142 self.atoms.set_momenta(self._p, apply_constraint=False) 

143 

144 def _get_forces(self) -> np.ndarray: 

145 self._update_atoms() 

146 return self.atoms.get_forces(md=True) 

147 

148 def _integrate_q(self, delta: float, apply_constraint: bool) -> None: 

149 """Integrate exp(i * L_1 * delta)""" 

150 old_q = self._q.copy() 

151 self._q += delta * self._p / self.masses 

152 

153 # First part of the RATTLE algorithm: constrain the new positions and 

154 # update momenta to reproduce it. 

155 if apply_constraint and self.atoms.constraints: 

156 self.atoms.set_positions(self._q, apply_constraint=True) 

157 self._q = self.atoms.get_positions() 

158 self._p = (self._q - old_q) * self.masses / delta 

159 self.atoms.set_momenta(self._p, apply_constraint=False) 

160 

161 def _integrate_p(self, delta: float, apply_constraint: bool) -> None: 

162 """Integrate exp(i * L_2 * delta)""" 

163 forces = self._get_forces() 

164 self._p += delta * forces 

165 

166 # Second part of RATTLE: constrain the new momenta. 

167 if apply_constraint and self.atoms.constraints: 

168 self.atoms.set_momenta(self._p, apply_constraint=True) 

169 self._p = self.atoms.get_momenta() 

170 

171 

172class NoseHooverChainThermostat: 

173 """Nose-Hoover chain style thermostats. 

174 

175 See `NoseHooverChainNVT` for the references. 

176 """ 

177 

178 def __init__( 

179 self, 

180 *, 

181 ndof: int, 

182 masses: np.ndarray, 

183 temperature_K: float, 

184 tdamp: float, 

185 tchain: int = 3, 

186 tloop: int = 1, 

187 ): 

188 """See `NoseHooverChainNVT` for the parameters.""" 

189 self._ndof = ndof 

190 self._masses = masses # (len(atoms), 1) 

191 self._tdamp = tdamp 

192 self._tchain = tchain 

193 self._tloop = tloop 

194 

195 self._kT = ase.units.kB * temperature_K 

196 

197 assert tchain >= 1 

198 self._Q = np.zeros(tchain) 

199 self._Q[0] = self._ndof * self._kT * tdamp**2 

200 self._Q[1:] = self._kT * tdamp**2 

201 

202 # The following variables are updated during self.step() 

203 self._eta = np.zeros(self._tchain) 

204 self._p_eta = np.zeros(self._tchain) 

205 

206 def get_thermostat_energy(self) -> float: 

207 """Return energy-like contribution from the thermostat variables.""" 

208 energy = ( 

209 self._ndof * self._kT * self._eta[0] 

210 + self._kT * np.sum(self._eta[1:]) 

211 + np.sum(0.5 * self._p_eta**2 / self._Q) 

212 ) 

213 return float(energy) 

214 

215 def integrate_nhc(self, p: np.ndarray, delta: float) -> np.ndarray: 

216 """Integrate exp(i * L_NHC * delta) and update momenta `p`.""" 

217 for _ in range(self._tloop): 

218 for coeff in FOURTH_ORDER_COEFFS: 

219 p = self._integrate_nhc_loop(p, coeff * delta / self._tloop) 

220 

221 return p 

222 

223 def _integrate_p_eta_j( 

224 self, p: np.ndarray, j: int, delta2: float, delta4: float 

225 ) -> None: 

226 if j < self._tchain - 1: 

227 self._p_eta[j] *= np.exp( 

228 -delta4 * self._p_eta[j + 1] / self._Q[j + 1] 

229 ) 

230 

231 if j == 0: 

232 g_j = np.sum(p**2 / self._masses) - self._ndof * self._kT 

233 else: 

234 g_j = self._p_eta[j - 1] ** 2 / self._Q[j - 1] - self._kT 

235 self._p_eta[j] += delta2 * g_j 

236 

237 if j < self._tchain - 1: 

238 self._p_eta[j] *= np.exp( 

239 -delta4 * self._p_eta[j + 1] / self._Q[j + 1] 

240 ) 

241 

242 def _integrate_eta(self, delta: float) -> None: 

243 self._eta += delta * self._p_eta / self._Q 

244 

245 def _integrate_nhc_p(self, p: np.ndarray, delta: float) -> None: 

246 p *= np.exp(-delta * self._p_eta[0] / self._Q[0]) 

247 

248 def _integrate_nhc_loop(self, p: np.ndarray, delta: float) -> np.ndarray: 

249 delta2 = delta / 2 

250 delta4 = delta / 4 

251 

252 for j in range(self._tchain): 

253 self._integrate_p_eta_j(p, self._tchain - j - 1, delta2, delta4) 

254 self._integrate_eta(delta) 

255 self._integrate_nhc_p(p, delta) 

256 for j in range(self._tchain): 

257 self._integrate_p_eta_j(p, j, delta2, delta4) 

258 

259 return p 

260 

261 

262class IsotropicMTKNPT(MolecularDynamics): 

263 """Isothermal-isobaric molecular dynamics with isotropic volume fluctuations 

264 by Martyna-Tobias-Klein (MTK) method [1]. 

265 

266 See also :class:`NoseHooverChainNVT` for the references. 

267 The factorization of the Liouville operator is the same as Reference [1]. 

268 

269 - [1] G. J. Martyna, D. J. Tobias, and M. L. Klein, J. Chem. Phys. 101, 

270 4177-4189 (1994). https://doi.org/10.1063/1.467468 

271 """ 

272 

273 def __init__( 

274 self, 

275 atoms: Atoms, 

276 timestep: float, 

277 temperature_K: float, 

278 pressure_au: float, 

279 tdamp: float, 

280 pdamp: float, 

281 tchain: int = 3, 

282 pchain: int = 3, 

283 tloop: int = 1, 

284 ploop: int = 1, 

285 **kwargs, 

286 ): 

287 """ 

288 Parameters 

289 ---------- 

290 atoms: ase.Atoms 

291 The atoms object. 

292 timestep: float 

293 The time step in ASE time units. 

294 temperature_K: float 

295 The target temperature in K. 

296 pressure_au: float 

297 The external pressure in eV/Ang^3. 

298 tdamp: float 

299 The characteristic time scale for the thermostat in ASE time units. 

300 Typically, it is set to 100 times of `timestep`. 

301 pdamp: float 

302 The characteristic time scale for the barostat in ASE time units. 

303 Typically, it is set to 1000 times of `timestep`. 

304 tchain: int 

305 The number of thermostat variables in the Nose-Hoover thermostat. 

306 pchain: int 

307 The number of barostat variables in the MTK barostat. 

308 tloop: int 

309 The number of sub-steps in thermostat integration. 

310 ploop: int 

311 The number of sub-steps in barostat integration. 

312 **kwargs : dict, optional 

313 Additional arguments passed to :class:~ase.md.md.MolecularDynamics 

314 base class. 

315 """ 

316 super().__init__( 

317 atoms=atoms, 

318 timestep=timestep, 

319 **kwargs, 

320 ) 

321 assert self.masses.shape == (len(self.atoms), 1) 

322 

323 if len(atoms.constraints) > 0: 

324 raise NotImplementedError( 

325 'Current implementation does not support constraints' 

326 ) 

327 

328 self._num_atoms_global = self.atoms.get_global_number_of_atoms() 

329 self._thermostat = NoseHooverChainThermostat( 

330 ndof=self.atoms.get_number_of_degrees_of_freedom(), 

331 masses=self.masses, 

332 temperature_K=temperature_K, 

333 tdamp=tdamp, 

334 tchain=tchain, 

335 tloop=tloop, 

336 ) 

337 self._barostat = IsotropicMTKBarostat( 

338 num_atoms_global=self._num_atoms_global, 

339 temperature_K=temperature_K, 

340 pdamp=pdamp, 

341 pchain=pchain, 

342 ploop=ploop, 

343 ) 

344 

345 self._temperature_K = temperature_K 

346 self._pressure_au = pressure_au 

347 

348 self._kT = ase.units.kB * self._temperature_K 

349 self._volume0 = self.atoms.get_volume() 

350 self._cell0 = np.array(self.atoms.get_cell()) 

351 

352 # The following variables are updated during self.step() 

353 self._q = self.atoms.get_positions() # positions 

354 self._p = self.atoms.get_momenta() # momenta 

355 self._eps = 0.0 # volume 

356 self._p_eps = 0.0 # volume momenta 

357 

358 def step(self) -> None: 

359 dt2 = self.dt / 2 

360 

361 self._p_eps = self._barostat.integrate_nhc_baro(self._p_eps, dt2) 

362 self._p = self._thermostat.integrate_nhc(self._p, dt2) 

363 self._integrate_p_cell(dt2) 

364 self._integrate_p(dt2) 

365 self._integrate_q(self.dt) 

366 self._integrate_q_cell(self.dt) 

367 self._integrate_p(dt2) 

368 self._integrate_p_cell(dt2) 

369 self._p = self._thermostat.integrate_nhc(self._p, dt2) 

370 self._p_eps = self._barostat.integrate_nhc_baro(self._p_eps, dt2) 

371 

372 self._update_atoms() 

373 

374 def get_conserved_energy(self) -> float: 

375 """Return the conserved energy-like quantity. 

376 

377 This method is mainly used for testing. 

378 """ 

379 conserved_energy = ( 

380 self.atoms.get_potential_energy(force_consistent=True) 

381 + self.atoms.get_kinetic_energy() 

382 + self._thermostat.get_thermostat_energy() 

383 + self._barostat.get_barostat_energy() 

384 + self._p_eps * self._p_eps / (2 * self._barostat.W) 

385 + self._pressure_au * self._get_volume() 

386 ) 

387 return float(conserved_energy) 

388 

389 def _update_atoms(self) -> None: 

390 self.atoms.set_positions(self._q) 

391 self.atoms.set_momenta(self._p) 

392 cell = self._cell0 * np.exp(self._eps) 

393 # Never set scale_atoms=True 

394 self.atoms.set_cell(cell, scale_atoms=False) 

395 

396 def _get_volume(self) -> float: 

397 return self._volume0 * np.exp(3 * self._eps) 

398 

399 def _get_forces(self) -> np.ndarray: 

400 self._update_atoms() 

401 return self.atoms.get_forces(md=True) 

402 

403 def _get_pressure(self) -> np.ndarray: 

404 self._update_atoms() 

405 stress = self.atoms.get_stress(voigt=False, include_ideal_gas=True) 

406 pressure = -np.trace(stress) / 3 

407 return pressure 

408 

409 def _integrate_q(self, delta: float) -> None: 

410 """Integrate exp(i * L_1 * delta)""" 

411 x = delta * self._p_eps / self._barostat.W 

412 self._q = self._q * np.exp(x) + self._p * delta / self.masses * exprel( 

413 x 

414 ) 

415 

416 def _integrate_p(self, delta: float) -> None: 

417 """Integrate exp(i * L_2 * delta)""" 

418 x = ( 

419 (1 + 1 / self._num_atoms_global) 

420 * self._p_eps 

421 * delta 

422 / self._barostat.W 

423 ) 

424 forces = self._get_forces() 

425 self._p = self._p * np.exp(-x) + delta * forces * exprel(-x) 

426 

427 def _integrate_q_cell(self, delta: float) -> None: 

428 """Integrate exp(i * L_(epsilon, 1) * delta)""" 

429 self._eps += delta * self._p_eps / self._barostat.W 

430 

431 def _integrate_p_cell(self, delta: float) -> None: 

432 """Integrate exp(i * L_(epsilon, 2) * delta)""" 

433 pressure = self._get_pressure() 

434 volume = self._get_volume() 

435 G = ( 

436 3 * volume * (pressure - self._pressure_au) 

437 + np.sum(self._p**2 / self.masses) / self._num_atoms_global 

438 ) 

439 self._p_eps += delta * G 

440 

441 

442class IsotropicMTKBarostat: 

443 """MTK barostat for isotropic volume fluctuations. 

444 

445 See `IsotropicMTKNPT` for the references. 

446 """ 

447 

448 def __init__( 

449 self, 

450 num_atoms_global: int, 

451 temperature_K: float, 

452 pdamp: float, 

453 pchain: int = 3, 

454 ploop: int = 1, 

455 ): 

456 self._num_atoms_global = num_atoms_global 

457 self._pdamp = pdamp 

458 self._pchain = pchain 

459 self._ploop = ploop 

460 

461 self._kT = ase.units.kB * temperature_K 

462 

463 self._W = (3 * self._num_atoms_global + 3) * self._kT * self._pdamp**2 

464 

465 assert pchain >= 1 

466 self._R = np.zeros(self._pchain) 

467 self._R[0] = 9 * self._kT * self._pdamp**2 

468 self._R[1:] = self._kT * self._pdamp**2 

469 

470 self._xi = np.zeros(self._pchain) # barostat coordinates 

471 self._p_xi = np.zeros(self._pchain) 

472 

473 @property 

474 def W(self) -> float: 

475 """Virtual mass for barostat momenta `p_xi`.""" 

476 return self._W 

477 

478 def get_barostat_energy(self) -> float: 

479 """Return energy-like contribution from the barostat variables.""" 

480 energy = +np.sum(0.5 * self._p_xi**2 / self._R) + self._kT * np.sum( 

481 self._xi 

482 ) 

483 return float(energy) 

484 

485 def integrate_nhc_baro(self, p_eps: float, delta: float) -> float: 

486 """Integrate exp(i * L_NHC-baro * delta)""" 

487 for _ in range(self._ploop): 

488 for coeff in FOURTH_ORDER_COEFFS: 

489 p_eps = self._integrate_nhc_baro_loop( 

490 p_eps, coeff * delta / self._ploop 

491 ) 

492 return p_eps 

493 

494 def _integrate_nhc_baro_loop(self, p_eps: float, delta: float) -> float: 

495 delta2 = delta / 2 

496 delta4 = delta / 4 

497 

498 for j in range(self._pchain): 

499 self._integrate_p_xi_j(p_eps, self._pchain - j - 1, delta2, delta4) 

500 self._integrate_xi(delta) 

501 p_eps = self._integrate_nhc_p_eps(p_eps, delta) 

502 for j in range(self._pchain): 

503 self._integrate_p_xi_j(p_eps, j, delta2, delta4) 

504 

505 return p_eps 

506 

507 def _integrate_p_xi_j( 

508 self, p_eps: float, j: int, delta2: float, delta4: float 

509 ) -> None: 

510 if j < self._pchain - 1: 

511 self._p_xi[j] *= np.exp( 

512 -delta4 * self._p_xi[j + 1] / self._R[j + 1] 

513 ) 

514 

515 if j == 0: 

516 g_j = p_eps**2 / self._W - self._kT 

517 else: 

518 g_j = self._p_xi[j - 1] ** 2 / self._R[j - 1] - self._kT 

519 self._p_xi[j] += delta2 * g_j 

520 

521 if j < self._pchain - 1: 

522 self._p_xi[j] *= np.exp( 

523 -delta4 * self._p_xi[j + 1] / self._R[j + 1] 

524 ) 

525 

526 def _integrate_xi(self, delta: float) -> None: 

527 self._xi += delta * self._p_xi / self._R 

528 

529 def _integrate_nhc_p_eps(self, p_eps: float, delta: float) -> float: 

530 p_eps_new = p_eps * float(np.exp(-delta * self._p_xi[0] / self._R[0])) 

531 return p_eps_new 

532 

533 

534class MTKNPT(MolecularDynamics): 

535 """Isothermal-isobaric molecular dynamics with volume-and-cell fluctuations 

536 by Martyna-Tobias-Klein (MTK) method [1]. 

537 

538 See also :class:`NoseHooverChainNVT` for the references. 

539 The factorization of the Liouville operator is the same as Reference [1]. 

540 

541 - [1] G. J. Martyna, D. J. Tobias, and M. L. Klein, J. Chem. Phys. 101, 

542 4177-4189 (1994). https://doi.org/10.1063/1.467468 

543 """ 

544 

545 def __init__( 

546 self, 

547 atoms: Atoms, 

548 timestep: float, 

549 temperature_K: float, 

550 pressure_au: float, 

551 tdamp: float, 

552 pdamp: float, 

553 tchain: int = 3, 

554 pchain: int = 3, 

555 tloop: int = 1, 

556 ploop: int = 1, 

557 **kwargs, 

558 ): 

559 """ 

560 Parameters 

561 ---------- 

562 atoms: ase.Atoms 

563 The atoms object. 

564 timestep: float 

565 The time step in ASE time units. 

566 temperature_K: float 

567 The target temperature in K. 

568 pressure_au: float 

569 The external pressure in eV/Ang^3. 

570 tdamp: float 

571 The characteristic time scale for the thermostat in ASE time units. 

572 Typically, it is set to 100 times of `timestep`. 

573 pdamp: float 

574 The characteristic time scale for the barostat in ASE time units. 

575 Typically, it is set to 1000 times of `timestep`. 

576 tchain: int 

577 The number of thermostat variables in the Nose-Hoover thermostat. 

578 pchain: int 

579 The number of barostat variables in the MTK barostat. 

580 tloop: int 

581 The number of sub-steps in thermostat integration. 

582 ploop: int 

583 The number of sub-steps in barostat integration. 

584 **kwargs : dict, optional 

585 Additional arguments passed to :class:~ase.md.md.MolecularDynamics 

586 base class. 

587 """ 

588 super().__init__( 

589 atoms=atoms, 

590 timestep=timestep, 

591 **kwargs, 

592 ) 

593 assert self.masses.shape == (len(self.atoms), 1) 

594 

595 if len(atoms.constraints) > 0: 

596 raise NotImplementedError( 

597 'Current implementation does not support constraints' 

598 ) 

599 

600 self._num_atoms_global = self.atoms.get_global_number_of_atoms() 

601 self._thermostat = NoseHooverChainThermostat( 

602 ndof=self.atoms.get_number_of_degrees_of_freedom(), 

603 masses=self.masses, 

604 temperature_K=temperature_K, 

605 tdamp=tdamp, 

606 tchain=tchain, 

607 tloop=tloop, 

608 ) 

609 

610 self._barostat = MTKBarostat( 

611 num_atoms_global=self._num_atoms_global, 

612 temperature_K=temperature_K, 

613 pdamp=pdamp, 

614 pchain=pchain, 

615 ploop=ploop, 

616 mask=self.mask, 

617 ) 

618 

619 self._temperature_K = temperature_K 

620 self._pressure_au = pressure_au 

621 

622 self._kT = ase.units.kB * self._temperature_K 

623 

624 # The following variables are updated during self.step() 

625 self._q = self.atoms.get_positions() # positions 

626 self._p = self.atoms.get_momenta() # momenta 

627 self._h = np.array(self.atoms.get_cell()) # cell 

628 

629 self._init_cell_momenta() 

630 

631 @property 

632 def mask(self) -> npt.NDArray[np.bool_] | None: 

633 return None 

634 

635 @mask.setter 

636 def mask(self, mask: tuple[bool, bool, bool]) -> None: 

637 raise AttributeError() 

638 

639 def _init_cell_momenta(self) -> None: 

640 self._p_g = np.zeros((3, 3)) # cell momenta 

641 

642 def step(self) -> None: 

643 dt2 = self.dt / 2 

644 

645 self._integrate_p_cell_by_barostat(dt2) 

646 self._p = self._thermostat.integrate_nhc(self._p, dt2) 

647 self._integrate_p_cell(dt2) 

648 self._integrate_p(dt2) 

649 self._integrate_q(self.dt) 

650 self._integrate_q_cell(self.dt) 

651 self._integrate_p(dt2) 

652 self._integrate_p_cell(dt2) 

653 self._p = self._thermostat.integrate_nhc(self._p, dt2) 

654 self._integrate_p_cell_by_barostat(dt2) 

655 

656 self._update_atoms() 

657 

658 def get_conserved_energy(self) -> float: 

659 conserved_energy = ( 

660 self.atoms.get_total_energy() 

661 + self._thermostat.get_thermostat_energy() 

662 + self._barostat.get_barostat_energy() 

663 + self._get_cell_kinetic_energy() 

664 + self._pressure_au * self._get_volume() 

665 ) 

666 return float(conserved_energy) 

667 

668 def _update_atoms(self) -> None: 

669 self.atoms.set_positions(self._q) 

670 self.atoms.set_momenta(self._p) 

671 self.atoms.set_cell(self._h, scale_atoms=False) 

672 

673 def _get_volume(self) -> float: 

674 return np.abs(np.linalg.det(self._h)) 

675 

676 def _get_forces(self) -> np.ndarray: 

677 self._update_atoms() 

678 return self.atoms.get_forces(md=True) 

679 

680 def _get_stress(self) -> np.ndarray: 

681 self._update_atoms() 

682 stress = self.atoms.get_stress(voigt=False, include_ideal_gas=True) 

683 return -stress 

684 

685 def _get_cell_kinetic_energy(self) -> float: 

686 return float(np.sum(self._p_g**2) / (2 * self._barostat.W)) 

687 

688 def _integrate_q(self, delta: float) -> None: 

689 """Integrate exp(i * L_1 * delta)""" 

690 # eigvals: (3-eigvec), U: (3-xyz, 3-eigvec) 

691 eigvals, U = np.linalg.eigh(self._p_g) 

692 x = self._q @ U # (num_atoms, 3-eigvec) 

693 y = self._p @ U # (num_atoms, 3-eigvec) 

694 sol = ( 

695 x * np.exp(eigvals * delta / self._barostat.W)[None, :] 

696 + delta 

697 * y 

698 / self.masses 

699 * exprel(eigvals * delta / self._barostat.W)[None, :] 

700 ) # (num_atoms, 3-eigvec) 

701 self._q = sol @ U.T 

702 

703 def _integrate_p(self, delta: float) -> None: 

704 """Integrate exp(i * L_2 * delta)""" 

705 forces = self._get_forces() # (num_atoms, 3-xyz) 

706 

707 # eigvals: (3-eigvec), U: (3-xyz, 3-eigvec) 

708 eigvals, U = np.linalg.eigh(self._p_g) 

709 kappas = eigvals + np.trace(self._p_g) / ( 

710 3 * self._num_atoms_global 

711 ) # (3-eigvec) 

712 y = self._p @ U # (num_atoms, 3-eigvec) 

713 sol = ( 

714 y * np.exp(-kappas * delta / self._barostat.W)[None, :] 

715 + delta 

716 * (forces @ U) 

717 * exprel(-kappas * delta / self._barostat.W)[None, :] 

718 ) # (num_atoms, 3-eigvec) 

719 self._p = sol @ U.T 

720 

721 def _integrate_q_cell(self, delta: float) -> None: 

722 """Integrate exp(i * L_(g, 1) * delta)""" 

723 # U @ np.diag(eigvals) @ U.T = self._p_g 

724 # eigvals: (3-eigvec), U: (3-xyz, 3-eigvec) 

725 eigvals, U = np.linalg.eigh(self._p_g) 

726 n = self._h @ U # (3-axis, 3-eigvec) 

727 sol = ( 

728 n * np.exp(eigvals * delta / self._barostat.W)[None, :] 

729 ) # (3-axis, 3-eigvec) 

730 self._h = sol @ U.T 

731 

732 def _integrate_p_cell(self, delta: float) -> None: 

733 """Integrate exp(i * L_(g, 2) * delta)""" 

734 stress = self._get_stress() 

735 volume = self._get_volume() 

736 particle_dof = 3 * self._num_atoms_global 

737 kinetic_term = np.sum(self._p**2 / self.masses) / particle_dof 

738 pv_tensor = volume * (stress - self._pressure_au * np.eye(3)) 

739 G = pv_tensor + kinetic_term * np.eye(3) 

740 self._p_g += delta * G 

741 

742 def _integrate_p_cell_by_barostat(self, delta: float) -> None: 

743 self._p_g = self._barostat.integrate_nhc_baro(self._p_g, delta) 

744 

745 

746class MaskedMTKNPT(MTKNPT): 

747 """Isothermal-isobaric molecular dynamics with cell fluctuations along 

748 specified crystallographic axes by Martyna-Tobias-Klein (MTK) method [1]. 

749 

750 The core equations are detailed in the implementation note available at 

751 https://arxiv.org/abs/2603.24061. 

752 

753 See also :class:`NoseHooverChainNVT` for the references. 

754 

755 - [1] G. J. Martyna, D. J. Tobias, and M. L. Klein, J. Chem. Phys. 101, 

756 4177-4189 (1994). https://doi.org/10.1063/1.467468 

757 """ 

758 

759 def __init__( 

760 self, 

761 *args, 

762 mask: tuple[bool, bool, bool], 

763 **kwargs, 

764 ): 

765 """ 

766 Parameters 

767 ---------- 

768 mask: tuple[bool, bool, bool] 

769 Boolean mask for (a, b, c) axis fluctuations. ``True`` enables 

770 fluctuations along an axis and ``False`` disables them. For 

771 example, ``mask=(False, False, True)`` allows only c-axis 

772 fluctuations. 

773 *args 

774 Positional arguments passed to :class:`MTKNPT`. 

775 **kwargs 

776 Keyword arguments passed to :class:`MTKNPT`. 

777 """ 

778 self.mask = mask 

779 super().__init__(*args, **kwargs) 

780 

781 def _init_cell_momenta(self) -> None: 

782 # Additional variables for masked MTK 

783 self._h0_basis = self._h / np.linalg.norm(self._h, axis=1)[:, None] 

784 self._p_c = np.zeros(3) # Cell momenta for axis 

785 

786 @property 

787 def mask(self) -> npt.NDArray[np.bool_]: 

788 return self._mask 

789 

790 @mask.setter 

791 def mask(self, mask: tuple[bool, bool, bool]) -> None: 

792 _mask = np.asarray(mask, dtype=bool) 

793 if _mask.shape != (3,): 

794 raise ValueError('mask must contain exactly three booleans') 

795 self._mask = _mask 

796 

797 @property 

798 def _p_g(self) -> np.ndarray: 

799 # equivalent to sum(pc * np.outer(ec, ec)) 

800 return (self._p_c * self._h0_basis.T) @ self._h0_basis 

801 

802 @_p_g.setter 

803 def _p_g(self, value: np.ndarray) -> None: 

804 raise AttributeError() 

805 

806 def _get_cell_kinetic_energy(self) -> float: 

807 return float(np.sum(self._p_c**2) / (2 * self._barostat.W)) 

808 

809 def _integrate_p_cell(self, delta: float) -> None: 

810 """Integrate exp(i * L_(g, 2) * delta)""" 

811 stress = self._get_stress() 

812 volume = self._get_volume() 

813 particle_dof = 3 * self._num_atoms_global 

814 kinetic_term = np.sum(self._p**2 / self.masses) / particle_dof 

815 pv_tensor = volume * (stress - self._pressure_au * np.eye(3)) 

816 gc = ( 

817 np.diag(self._h0_basis @ pv_tensor @ self._h0_basis.T) 

818 + kinetic_term 

819 ) 

820 self._p_c[self.mask] += delta * gc[self.mask] 

821 

822 def _integrate_p_cell_by_barostat(self, delta: float) -> None: 

823 self._p_c = self._barostat.integrate_nhc_baro(self._p_c, delta) 

824 

825 

826class MTKBarostat: 

827 """MTK barostat for volume-and-cell fluctuations. 

828 

829 See `MTKNPT` for the references. 

830 

831 Note for `mask` keyword argument: 

832 If `mask` is None, the symmetric cell momentum has 6 independent DoF. 

833 If `mask` is a 3-tuple of booleans, only the specified axes are allowed 

834 to fluctuate, and its DoF is a number of the specified axes. Thus, 

835 `mask=(True, True, True)` gives 3 DoF cell fluctuations along a, b, 

836 and c axes, which is different from the full 6 DoF fluctuations. 

837 Other cell fluctuations such as partially allowed off-diagonal 

838 components are not supported in the current implementation. 

839 """ 

840 

841 def __init__( 

842 self, 

843 num_atoms_global: int, 

844 temperature_K: float, 

845 pdamp: float, 

846 pchain: int = 3, 

847 ploop: int = 1, 

848 mask: npt.NDArray[np.bool_] | tuple[bool, bool, bool] | None = None, 

849 ): 

850 self._num_atoms_global = num_atoms_global 

851 self._pdamp = pdamp 

852 self._pchain = pchain 

853 self._ploop = ploop 

854 

855 self._cell_dof = 6 if mask is None else sum(mask) 

856 

857 self._kT = ase.units.kB * temperature_K 

858 

859 self._W = (self._num_atoms_global + 1) * self._kT * self._pdamp**2 

860 

861 assert pchain >= 1 

862 # Virtual masses for barostat momenta. Q_j' in the original paper. 

863 self._R = np.zeros(self._pchain) 

864 self._R[0] = self._cell_dof * self._kT * self._pdamp**2 

865 self._R[1:] = self._kT * self._pdamp**2 

866 

867 self._xi = np.zeros(self._pchain) # barostat coordinates 

868 self._p_xi = np.zeros(self._pchain) 

869 

870 @property 

871 def W(self) -> float: 

872 """Virtual mass for barostat momenta.""" 

873 return self._W 

874 

875 def get_barostat_energy(self) -> float: 

876 energy = ( 

877 np.sum(self._p_xi**2 / self._R) / 2 

878 + self._cell_dof * self._kT * self._xi[0] 

879 + self._kT * np.sum(self._xi[1:]) 

880 ) 

881 return float(energy) 

882 

883 def integrate_nhc_baro( 

884 self, p_cell: np.ndarray, delta: float 

885 ) -> np.ndarray: 

886 """Integrate exp(i * L_NHC-baro * delta)""" 

887 for _ in range(self._ploop): 

888 for coeff in FOURTH_ORDER_COEFFS: 

889 p_cell = self._integrate_nhc_baro_loop( 

890 p_cell, coeff * delta / self._ploop 

891 ) 

892 return p_cell 

893 

894 def _integrate_nhc_baro_loop( 

895 self, p_cell: np.ndarray, delta: float 

896 ) -> np.ndarray: 

897 delta2 = delta / 2 

898 delta4 = delta / 4 

899 

900 for j in range(self._pchain): 

901 self._integrate_p_xi_j(p_cell, self._pchain - j - 1, delta2, delta4) 

902 self._integrate_xi(delta) 

903 self._integrate_nhc_p_cell(p_cell, delta) 

904 for j in range(self._pchain): 

905 self._integrate_p_xi_j(p_cell, j, delta2, delta4) 

906 

907 return p_cell 

908 

909 def _integrate_p_xi_j( 

910 self, p_cell: np.ndarray, j: int, delta2: float, delta4: float 

911 ) -> None: 

912 if j < self._pchain - 1: 

913 self._p_xi[j] *= np.exp( 

914 -delta4 * self._p_xi[j + 1] / self._R[j + 1] 

915 ) 

916 

917 if j == 0: 

918 g_j = np.sum(p_cell**2) / self._W - self._cell_dof * self._kT 

919 else: 

920 g_j = self._p_xi[j - 1] ** 2 / self._R[j - 1] - self._kT 

921 self._p_xi[j] += delta2 * g_j 

922 

923 if j < self._pchain - 1: 

924 self._p_xi[j] *= np.exp( 

925 -delta4 * self._p_xi[j + 1] / self._R[j + 1] 

926 ) 

927 

928 def _integrate_xi(self, delta: float) -> None: 

929 for j in range(self._pchain): 

930 self._xi[j] += delta * self._p_xi[j] / self._R[j] 

931 

932 def _integrate_nhc_p_cell(self, p_cell: np.ndarray, delta: float) -> None: 

933 p_cell *= np.exp(-delta * self._p_xi[0] / self._R[0])