Coverage for ase/thermochemistry.py: 92.86%

658 statements  

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

1"""Modules for calculating thermochemical information from computational 

2outputs.""" 

3 

4import os 

5import sys 

6from abc import ABC, abstractmethod 

7from collections.abc import Sequence 

8from typing import Literal 

9from warnings import catch_warnings, simplefilter, warn 

10 

11import numpy as np 

12from scipy.integrate import trapezoid 

13 

14from ase import Atoms, units 

15 

16_GEOMETRY_OPTIONS = Literal['linear', 'nonlinear', 'monatomic'] 

17_VIB_SELECTION_OPTIONS = Literal['exact', 'all', 'highest', 'abs_highest'] 

18_FLOAT_OR_FLOATWITHDICT = float | tuple[float, dict[str, float]] 

19_FLOATWITHDICT = tuple[float, dict[str, float]] 

20 

21 

22def _sum_contributions(contrib_dicts: dict[str, float]) -> float: 

23 """Combine a Dict of floats to their sum. 

24 

25 Ommits keys starting with an underscore. 

26 """ 

27 return np.sum( 

28 [ 

29 value 

30 for key, value in contrib_dicts.items() 

31 if not key.startswith('_') 

32 ] 

33 ) 

34 

35 

36class AbstractMode(ABC): 

37 """Abstract base class for mode objects. 

38 

39 Input: 

40 

41 energy: float 

42 Initialize the mode with its energy in eV. 

43 Note: This energy refers to the vibrational energy of the mode. 

44 Get it e.g. from ase.vibrations.Vibrations.get_energies. 

45 """ 

46 

47 def __init__(self, energy: float) -> None: 

48 self.energy = energy 

49 

50 @abstractmethod 

51 def get_internal_energy( 

52 self, temperature: float, contributions: bool 

53 ) -> _FLOAT_OR_FLOATWITHDICT: 

54 raise NotImplementedError 

55 

56 @abstractmethod 

57 def get_entropy( 

58 self, temperature: float, contributions: bool 

59 ) -> _FLOAT_OR_FLOATWITHDICT: 

60 raise NotImplementedError 

61 

62 

63class HarmonicMode(AbstractMode): 

64 """Class for a single harmonic mode.""" 

65 

66 def get_ZPE_correction(self) -> float: 

67 """Returns the zero-point vibrational energy correction in eV.""" 

68 return 0.5 * self.energy 

69 

70 def get_vib_energy_contribution(self, temperature: float) -> float: 

71 """Calculates the change in internal energy due to vibrations from 

72 0K to the specified temperature for a set of vibrations given in 

73 eV and a temperature given in Kelvin. 

74 Returns the energy change in eV.""" 

75 kT = units.kB * temperature 

76 return self.energy / (np.exp(self.energy / kT) - 1.0) 

77 

78 def get_vib_entropy_contribution(self, temperature: float) -> float: 

79 """Calculates the entropy due to vibrations given in eV and a 

80 temperature given in Kelvin. Returns the entropy in eV/K.""" 

81 e = self.energy / units.kB / temperature 

82 S_v = e / (np.exp(e) - 1.0) - np.log(1.0 - np.exp(-e)) 

83 S_v *= units.kB 

84 return S_v 

85 

86 def get_internal_energy( 

87 self, temperature: float, contributions: bool 

88 ) -> _FLOAT_OR_FLOATWITHDICT: 

89 """Returns the internal energy in the harmonic approximation at a 

90 specified temperature (K).""" 

91 ret = {} 

92 ret['ZPE'] = self.get_ZPE_correction() 

93 ret['dU_v'] = self.get_vib_energy_contribution(temperature) 

94 ret_sum = _sum_contributions(ret) 

95 

96 if contributions: 

97 return ret_sum, ret 

98 else: 

99 return ret_sum 

100 

101 def get_entropy( 

102 self, temperature: float, contributions: bool 

103 ) -> _FLOAT_OR_FLOATWITHDICT: 

104 """Returns the entropy in the harmonic approximation at a specified 

105 temperature (K). 

106 

107 Parameters 

108 ---------- 

109 temperature : float 

110 The temperature in Kelvin. 

111 contributions : bool 

112 If True, return the contributions to the entropy as a dict too. 

113 Here it will only contain the vibrational entropy. 

114 

115 Returns 

116 ------- 

117 float or Tuple[float, Dict[str, float]] 

118 """ 

119 ret = {} 

120 ret['S_v'] = self.get_vib_entropy_contribution(temperature) 

121 if contributions: 

122 return ret['S_v'], ret 

123 else: 

124 return ret['S_v'] 

125 

126 

127class RRHOMode(HarmonicMode): 

128 """Class for a single RRHO mode, including Grimme's scaling method 

129 based on :doi:`10.1002/chem.201200497` and :doi:`10.1039/D1SC00621E`. 

130 

131 Inputs: 

132 

133 mean_inertia : float 

134 The mean moment of inertia in amu*angstrom^2. Use 

135 `np.mean(ase.Atoms.get_moments_of_inertia())` to calculate. 

136 tau : float 

137 the vibrational energy threshold in :math:`cm^{-1}`, named 

138 :math:`\\tau` in :doi:`10.1039/D1SC00621E`. 

139 Values close or equal to 0 will result in the standard harmonic 

140 approximation. Defaults to :math:`35cm^{-1}`. 

141 treat_int_energy : bool 

142 Extend the msRRHO treatement to the internal thermal energy. 

143 If False, only the entropy contribution as in Grimmmes paper is 

144 modified according to the RRHO scheme. If True, the approach of 

145 Otlyotov and Minenkov :doi:`10.1002/jcc.27129` is used to modify 

146 the internal energy contribution. 

147 """ 

148 

149 def __init__( 

150 self, 

151 energy: float, 

152 mean_inertia: float, 

153 tau: float = 35.0, 

154 treat_int_energy: bool = False, 

155 ) -> None: 

156 if np.iscomplex(energy): 

157 raise ValueError( 

158 'Imaginary frequencies are not allowed in RRHO mode.' 

159 ) 

160 super().__init__(energy) 

161 self._mean_inertia = mean_inertia 

162 self._tau = tau 

163 self._alpha = 4 # from paper 10.1002/chem.201200497 

164 self.treat_int_energy = treat_int_energy 

165 

166 @property 

167 def frequency(self) -> float: 

168 return self.energy / units.invcm 

169 

170 def _head_gordon_damp(self, freq: float) -> float: 

171 """Head-Gordon damping function. 

172 

173 Equation 8 from :doi:`10.1002/chem.201200497` 

174 

175 Parameters 

176 ---------- 

177 freq : float 

178 The frequency in the same unit as tau. 

179 

180 Returns 

181 ------- 

182 float 

183 """ 

184 return 1 / (1 + (self._tau / freq) ** self._alpha) 

185 

186 def _apply_head_gordon_damp( 

187 self, freq: float, large_part: float, small_part: float 

188 ) -> float: 

189 """Apply the head-gordon damping scheme to two contributions. 

190 

191 Equation 7 from :doi:`10.1002/chem.201200497` 

192 

193 Returns the damped sum of the two contributions.""" 

194 part_one = self._head_gordon_damp(freq) * large_part 

195 part_two = (1 - self._head_gordon_damp(freq)) * small_part 

196 return part_one + part_two 

197 

198 def get_RRHO_entropy_r(self, temperature: float) -> float: 

199 """Calculates the rotation of a rigid rotor for low frequency modes. 

200 

201 Equation numbering from :doi:`10.1002/chem.201200497` 

202 

203 Returns the entropy contribution in eV/K.""" 

204 kT = units._k * temperature 

205 R = units._k * units._Nav # J / K / mol 

206 B_av = self._mean_inertia / ( 

207 units.kg * units.m**2 

208 ) # from amu/A^2 to kg m^2 

209 # note, some codes use B_av = 1e-44 as in 10.1002/chem.201200497 

210 # eq 4 

211 omega = units._c * self.frequency * 1e2 # s^-1 

212 mu = units._hplanck / (8 * np.pi**2 * omega) # kg m^2 

213 # eq 5 

214 mu_prime = (mu * B_av) / (mu + B_av) # kg m^2 

215 # eq 6 

216 x = np.sqrt(8 * np.pi**3 * mu_prime * kT / (units._hplanck) ** 2) 

217 # filter zeros out and set them to zero 

218 if x == 0.0: 

219 log_x = 0.0 

220 else: 

221 log_x = np.log(x) 

222 S_r = R * (0.5 + log_x) # J/(Js)^2 

223 S_r *= units.J / units._Nav # J/K/mol to eV/K 

224 return S_r 

225 

226 def get_entropy( 

227 self, temperature: float, contributions: bool 

228 ) -> _FLOAT_OR_FLOATWITHDICT: 

229 ret = {} 

230 ret['_S_vib_v'] = self.get_vib_entropy_contribution(temperature) 

231 ret['_S_vib_r'] = self.get_RRHO_entropy_r(temperature) 

232 ret['S_vib_damped'] = self._apply_head_gordon_damp( 

233 self.frequency, ret['_S_vib_v'], ret['_S_vib_r'] 

234 ) 

235 if contributions: 

236 return ret['S_vib_damped'], ret 

237 else: 

238 return ret['S_vib_damped'] 

239 

240 def get_rrho_internal_energy_v_contribution( 

241 self, temperature: float 

242 ) -> float: 

243 """RRHO Vibrational Internal Energy Contribution from 

244 :doi:`10.1002/jcc.27129`. 

245 

246 Returns the internal energy contribution in eV.""" 

247 # equation numbering from :doi:`10.1002/jcc.27129` 

248 # eq 4 

249 # hv = self.energy 

250 theta = self.energy / units.kB 

251 E_v = 0.5 + 1 / (np.exp(theta / temperature) - 1) 

252 E_v *= self.energy # = theta * units.kB 

253 return E_v 

254 

255 @staticmethod 

256 def get_rrho_internal_energy_r_contribution(temperature: float) -> float: 

257 """Calculates the rotation of a rigid rotor contribution. 

258 

259 Equation numbering from :doi:`10.1002/jcc.27129` 

260 

261 Returns the internal energy contribution in eV.""" 

262 # eq 5 

263 R = units._k * units._Nav 

264 E_r = R * temperature / 2 

265 E_r *= units.J / units._Nav 

266 return E_r 

267 

268 def get_internal_energy( 

269 self, temperature: float, contributions: bool 

270 ) -> _FLOAT_OR_FLOATWITHDICT: 

271 """Returns the internal energy in the msRRHO approximation at a 

272 specified temperature (K). 

273 

274 If self.treat_int_energy is True, the approach of Otlyotov 

275 and Minenkov :doi:`10.1002/jcc.27129` is used. Otherwise, the approach 

276 of Grimme :doi:`10.1002/chem.201200497` is used. 

277 """ 

278 if self.treat_int_energy: 

279 # Otlyotov and Minenkov approach with damping between vibrational 

280 # and rotational contributions to the internal energy 

281 # Note: The ZPE is not needed here, as the formula in the paper 

282 # uses the "bottom of the well" as reference. See 

283 # https://gaussian.com/wp-content/uploads/dl/thermo.pdf 

284 # for more formulas 

285 ret = {} 

286 ret['_dU_vib_v'] = self.get_rrho_internal_energy_v_contribution( 

287 temperature 

288 ) 

289 ret['_dU_vib_r'] = self.get_rrho_internal_energy_r_contribution( 

290 temperature 

291 ) 

292 ret['dU_vib_damped'] = self._apply_head_gordon_damp( 

293 self.frequency, ret['_dU_vib_v'], ret['_dU_vib_r'] 

294 ) 

295 if contributions: 

296 return ret['dU_vib_damped'], ret 

297 else: 

298 return ret['dU_vib_damped'] 

299 else: 

300 # Grimme uses the Harmonic approach for the internal energy 

301 return super().get_internal_energy(temperature, contributions) 

302 

303 

304class BaseThermoChem(ABC): 

305 """Abstract base class containing common methods used in thermochemistry 

306 calculations.""" 

307 

308 def __init__( 

309 self, 

310 vib_energies: Sequence[float] | None = None, 

311 atoms: Atoms | None = None, 

312 modes: Sequence[AbstractMode] | None = None, 

313 spin: float | None = None, 

314 ) -> None: 

315 if vib_energies is None and modes is None: 

316 raise ValueError('Either vib_energies or modes must be provided.') 

317 elif modes: 

318 self.modes = modes 

319 # in the monoatomic case, the vib_energies can be an empty list 

320 else: 

321 self._vib_energies = vib_energies 

322 self.referencepressure = 1.0e5 # Pa 

323 if atoms: 

324 # check that atoms has no periodic boundary conditions 

325 # moments of inertia are wrong otherwise. 

326 if atoms.pbc.any(): 

327 raise ValueError( 

328 'Atoms object should not have periodic ' 

329 'boundary conditions for BaseThermoChem.' 

330 ) 

331 self.atoms = atoms 

332 if spin is not None and spin < 0: 

333 raise ValueError( 

334 f'spin must be non-negative (got {spin}); it is the total ' 

335 'electronic spin magnitude, not a spin z-projection.' 

336 ) 

337 self.spin = spin 

338 

339 @classmethod 

340 def from_transition_state( 

341 cls, vib_energies: Sequence[complex], *args, **kwargs 

342 ) -> 'BaseThermoChem': 

343 """Create a new instance for a transition state. 

344 

345 This will work just as the standard constructor, but will remove 

346 one imaginary frequency from the given vib_energies first. 

347 If there is more than one imaginary frequency, an error will be raised. 

348 

349 Returns 

350 ------- 

351 BaseThermoChem instance 

352 """ 

353 

354 if sum(np.iscomplex(vib_energies)): 

355 # supress user warning 

356 with catch_warnings(): 

357 simplefilter('ignore') 

358 vib_e, n_imag = _clean_vib_energies(vib_energies, True) 

359 if n_imag != 1: 

360 raise ValueError('Not exactly one imaginary frequency found.') 

361 else: 

362 raise ValueError('No imaginary frequencies found in vib_energies.') 

363 

364 thermo = cls(vib_e, *args, **kwargs) 

365 

366 return thermo 

367 

368 @staticmethod 

369 def combine_contributions( 

370 contrib_dicts: Sequence[dict[str, float]], 

371 ) -> dict[str, float]: 

372 """Combine the contributions from multiple modes.""" 

373 ret: dict[str, float] = {} 

374 for contrib_dict in contrib_dicts: 

375 for key, value in contrib_dict.items(): 

376 if key in ret: 

377 ret[key] += value 

378 else: 

379 ret[key] = value 

380 return ret 

381 

382 def print_contributions( 

383 self, contributions: dict[str, float], verbose: bool 

384 ) -> None: 

385 """Print the contributions.""" 

386 if verbose: 

387 fmt = '{:<15s}{:13.3f} eV' 

388 for key, value in contributions.items(): 

389 # subvalues start with _ 

390 if key.startswith('_'): 

391 key.replace('_', '... ') 

392 self._vprint(fmt.format(key, value)) 

393 

394 @abstractmethod 

395 def get_internal_energy(self, temperature: float, verbose: bool) -> float: 

396 raise NotImplementedError 

397 

398 @abstractmethod 

399 def get_entropy( 

400 self, 

401 temperature: float, 

402 pressure: float = units.bar, 

403 verbose: bool = True, 

404 ) -> float: 

405 raise NotImplementedError 

406 

407 @property 

408 def vib_energies(self) -> np.ndarray: 

409 """Get the vibrational energies in eV. 

410 

411 For backwards compatibility, this will return the modes' energies if 

412 they are available. Otherwise, it will return the stored vib_energies. 

413 """ 

414 # build from modes if available 

415 if hasattr(self, 'modes'): 

416 return np.array([mode.energy for mode in self.modes]) 

417 elif hasattr(self, '_vib_energies'): 

418 return np.array(self._vib_energies) 

419 else: 

420 raise AttributeError('No vibrational energies available.') 

421 

422 @vib_energies.setter 

423 def vib_energies(self, value: Sequence[float]) -> None: 

424 """For backwards compatibility, raise a deprecation warning.""" 

425 warn( 

426 'The vib_energies attribute is deprecated and will be removed in a' 

427 'future release. Please use the modes attribute instead.' 

428 'Setting this outside the constructor will not update the modes', 

429 DeprecationWarning, 

430 ) 

431 self._vib_energies = value 

432 

433 def get_ZPE_correction(self) -> float: 

434 """Returns the zero-point vibrational energy correction in eV.""" 

435 return 0.5 * np.sum(self.vib_energies) 

436 

437 @staticmethod 

438 def get_ideal_translational_energy(temperature: float) -> float: 

439 """Returns the translational heat capacity times T in eV. 

440 

441 Parameters 

442 ---------- 

443 temperature : float 

444 The temperature in Kelvin. 

445 

446 Returns 

447 ------- 

448 float 

449 """ 

450 return ( 

451 3.0 / 2.0 * units.kB * temperature 

452 ) # translational heat capacity (3-d gas) 

453 

454 @staticmethod 

455 def get_ideal_rotational_energy( 

456 geometry: _GEOMETRY_OPTIONS, temperature: float 

457 ) -> float: 

458 """Returns the rotational heat capacity times T in eV. 

459 

460 Parameters 

461 ---------- 

462 geometry : str 

463 The geometry of the molecule. Options are 'nonlinear', 

464 'linear', and 'monatomic'. 

465 temperature : float 

466 The temperature in Kelvin. 

467 

468 Returns 

469 ------- 

470 float 

471 """ 

472 if geometry == 'nonlinear': # rotational heat capacity 

473 Cv_r = 3.0 / 2.0 * units.kB 

474 elif geometry == 'linear': 

475 Cv_r = units.kB 

476 elif geometry == 'monatomic': 

477 Cv_r = 0.0 

478 else: 

479 raise ValueError('Invalid geometry: %s' % geometry) 

480 return Cv_r * temperature 

481 

482 def get_ideal_trans_entropy( 

483 self, atoms: Atoms, temperature: float 

484 ) -> float: 

485 """Returns the translational entropy in eV/K. 

486 

487 Parameters 

488 ---------- 

489 atoms : ase.Atoms 

490 The atoms object. 

491 temperature : float 

492 The temperature in Kelvin. 

493 

494 Returns 

495 ------- 

496 float 

497 """ 

498 # Translational entropy (term inside the log is in SI units). 

499 mass = sum(atoms.get_masses()) * units._amu # kg/molecule 

500 S_t = ( 

501 2 * np.pi * mass * units._k * temperature / units._hplanck**2 

502 ) ** (3.0 / 2) 

503 S_t *= units._k * temperature / self.referencepressure 

504 S_t = units.kB * (np.log(S_t) + 5.0 / 2.0) 

505 return S_t 

506 

507 def get_vib_energy_contribution(self, temperature: float) -> float: 

508 """Calculates the change in internal energy due to vibrations from 

509 0K to the specified temperature for a set of vibrations given in 

510 eV and a temperature given in Kelvin. 

511 Returns the energy change in eV.""" 

512 # Leftover for HinderedThermo class, delete once that is converted 

513 # to use modes 

514 kT = units.kB * temperature 

515 dU = 0.0 

516 

517 for energy in self.vib_energies: 

518 dU += energy / (np.exp(energy / kT) - 1.0) 

519 return dU 

520 

521 def get_vib_entropy_contribution( 

522 self, temperature: float, return_list: bool = False 

523 ) -> float | np.ndarray: 

524 """Calculates the entropy due to vibrations for a set of vibrations 

525 given in eV and a temperature given in Kelvin. Returns the entropy 

526 in eV/K.""" 

527 kT = units.kB * temperature 

528 energies = np.array(self.vib_energies) / kT # eV/ eV/K*K 

529 S_v = energies / (np.exp(energies) - 1.0) - np.log( 

530 1.0 - np.exp(-energies) 

531 ) 

532 S_v *= units.kB 

533 if return_list: 

534 return S_v 

535 else: 

536 return np.sum(S_v) 

537 

538 def _vprint(self, text): 

539 """Print output if verbose flag True.""" 

540 if self.verbose: 

541 sys.stdout.write(text + os.linesep) 

542 

543 def get_ideal_entropy( 

544 self, 

545 temperature: float, 

546 translation: bool = False, 

547 vibration: bool = False, 

548 rotation: bool = False, 

549 geometry: _GEOMETRY_OPTIONS | None = None, 

550 electronic: bool = False, 

551 pressure: float | None = None, 

552 symmetrynumber: int | None = None, 

553 ) -> _FLOATWITHDICT: 

554 """Returns the entropy, in eV/K and a dict of the contributions. 

555 

556 Parameters 

557 ---------- 

558 temperature : float 

559 The temperature in Kelvin. 

560 translation : bool 

561 Include translational entropy. 

562 vibration : bool 

563 Include vibrational entropy. 

564 rotation : bool 

565 Include rotational entropy. 

566 geometry : str 

567 The geometry of the molecule. Options are 'nonlinear', 

568 'linear', and 'monatomic'. 

569 electronic : bool 

570 Include electronic entropy. 

571 pressure : float 

572 The pressure in Pa. Only needed for the translational entropy. 

573 symmetrynumber : int 

574 The symmetry number of the molecule. Only needed for linear and 

575 nonlinear molecules. 

576 

577 Returns 

578 ------- 

579 Tuple of one float and one dict 

580 The float is the total entropy in eV/K. 

581 The dict contains the contributions to the entropy. 

582 """ 

583 

584 if (geometry in ['linear', 'nonlinear']) and (symmetrynumber is None): 

585 raise ValueError( 

586 'Symmetry number required for linear and nonlinear molecules.' 

587 ) 

588 

589 if not hasattr(self, 'atoms'): 

590 raise ValueError( 

591 'Atoms object required for ideal entropy calculation.' 

592 ) 

593 

594 if electronic and (self.spin is None): 

595 raise ValueError( 

596 'Spin value required for electronic entropy calculation.' 

597 ) 

598 

599 S: float = 0.0 

600 ret = {} 

601 

602 if translation: 

603 S_t = self.get_ideal_trans_entropy(self.atoms, temperature) 

604 ret['S_t'] = S_t 

605 S += S_t 

606 if pressure: 

607 # Pressure correction to translational entropy. 

608 S_p = -units.kB * np.log(pressure / self.referencepressure) 

609 S += S_p 

610 ret['S_p'] = S_p 

611 

612 if rotation: 

613 # Rotational entropy (term inside the log is in SI units). 

614 if geometry == 'monatomic': 

615 S_r = 0.0 

616 elif geometry == 'nonlinear': 

617 inertias = ( 

618 self.atoms.get_moments_of_inertia() * units._amu / 1e10**2 

619 ) # kg m^2 

620 S_r = np.sqrt(np.pi * np.prod(inertias)) / symmetrynumber 

621 S_r *= ( 

622 8.0 * np.pi**2 * units._k * temperature / units._hplanck**2 

623 ) ** (3.0 / 2.0) 

624 S_r = units.kB * (np.log(S_r) + 3.0 / 2.0) 

625 elif geometry == 'linear': 

626 inertias = ( 

627 self.atoms.get_moments_of_inertia() 

628 * units._amu 

629 / (10.0**10) ** 2 

630 ) # kg m^2 

631 inertia = max(inertias) # should be two identical and one zero 

632 S_r = ( 

633 8 

634 * np.pi**2 

635 * inertia 

636 * units._k 

637 * temperature 

638 / symmetrynumber 

639 / units._hplanck**2 

640 ) 

641 S_r = units.kB * (np.log(S_r) + 1.0) 

642 else: 

643 raise RuntimeError(f'Invalid geometry: {geometry}') 

644 S += S_r 

645 ret['S_r'] = S_r 

646 

647 # Electronic entropy. 

648 if electronic: 

649 assert self.spin is not None # for mypy, error is raised above 

650 S_e = units.kB * np.log(2 * self.spin + 1) 

651 S += S_e 

652 ret['S_e'] = S_e 

653 

654 # Vibrational entropy 

655 if vibration: 

656 S_v = self.get_vib_entropy_contribution( 

657 temperature, return_list=False 

658 ) 

659 assert isinstance(S_v, float) # make mypy happy 

660 S += S_v 

661 ret['S_v'] = S_v 

662 

663 return S, ret 

664 

665 

666class HarmonicThermo(BaseThermoChem): 

667 """Class for calculating thermodynamic properties in the approximation 

668 that all degrees of freedom are treated harmonically. Often used for 

669 adsorbates. 

670 

671 Note: This class does not include the translational and rotational 

672 contributions to the entropy by default. Use the get_ideal_entropy method 

673 for that and add them manually. 

674 

675 Inputs: 

676 

677 vib_energies : list 

678 a list of the harmonic energies of the adsorbate (e.g., from 

679 ase.vibrations.Vibrations.get_energies). The number of 

680 energies should match the number of degrees of freedom of the 

681 adsorbate; i.e., 3*n, where n is the number of atoms. Note that 

682 this class does not check that the user has supplied the correct 

683 number of energies. Units of energies are eV. Note, that if 'modes' 

684 are given, these energies are not used. 

685 potentialenergy : float 

686 the potential energy in eV (e.g., from atoms.get_potential_energy) 

687 (if potentialenergy is unspecified, then the methods of this 

688 class can be interpreted as the energy corrections) 

689 ignore_imag_modes : bool 

690 If 'True', any imaginary frequencies will be removed in the 

691 calculation of the thermochemical properties. 

692 If 'False' (default), an error will be raised if any imaginary 

693 frequencies are present. 

694 modes : list of AbstractMode 

695 A list of mode objects. If not provided, :class:`HarmonicMode` objects 

696 will be created from the vib_energies. This is useful if you want to 

697 replace individual modes with non-harmonic modes. 

698 """ 

699 

700 def __init__( 

701 self, 

702 vib_energies: Sequence[complex], 

703 potentialenergy: float = 0.0, 

704 ignore_imag_modes: bool = False, 

705 modes: Sequence[AbstractMode] | None = None, 

706 ) -> None: 

707 

708 # Check for imaginary frequencies. 

709 vib_energies, n_imag = _clean_vib_energies( 

710 vib_energies, ignore_imag_modes 

711 ) 

712 if modes is None: 

713 modes = [HarmonicMode(energy) for energy in vib_energies] 

714 super().__init__(modes=modes) 

715 

716 self.n_imag = n_imag 

717 

718 self.potentialenergy = potentialenergy 

719 

720 def get_internal_energy( 

721 self, temperature: float, verbose: bool = True 

722 ) -> float: 

723 """Returns the internal energy, in eV, in the harmonic approximation 

724 at a specified temperature (K).""" 

725 

726 self.verbose = verbose 

727 vprint = self._vprint 

728 fmt = '%-15s%13.3f eV' 

729 vprint('Internal energy components at T = %.2f K:' % temperature) 

730 vprint('=' * 31) 

731 

732 vprint(fmt % ('E_pot', self.potentialenergy)) 

733 

734 U, contribs = zip( 

735 *[ 

736 mode.get_internal_energy(temperature, contributions=True) 

737 for mode in self.modes 

738 ] 

739 ) 

740 U = np.sum(U) 

741 U += self.potentialenergy 

742 

743 self.print_contributions(self.combine_contributions(contribs), verbose) 

744 vprint('-' * 31) 

745 vprint(fmt % ('U', U)) 

746 vprint('=' * 31) 

747 

748 return U 

749 

750 def get_entropy( 

751 self, 

752 temperature: float, 

753 pressure: float = units.bar, 

754 verbose: bool = True, 

755 ) -> float: 

756 """Returns the entropy, in eV/K at a specified temperature (K). 

757 

758 Note: This does not include the translational and rotational 

759 contributions to the entropy. Use the get_ideal_entropy method 

760 for that. 

761 

762 Parameters 

763 ---------- 

764 temperature : float 

765 The temperature in Kelvin. 

766 pressure : float 

767 Not used, but kept for compatibility with other classes. 

768 verbose : bool 

769 If True, print the contributions to the entropy. 

770 

771 Returns 

772 ------- 

773 float 

774 """ 

775 

776 self.verbose = verbose 

777 vprint = self._vprint 

778 fmt = '%-15s%13.7f eV/K%13.3f eV' 

779 vprint('Entropy components at T = %.2f K:' % temperature) 

780 vprint('=' * 49) 

781 vprint('%15s%13s %13s' % ('', 'S', 'T*S')) 

782 

783 S, contribs = zip( 

784 *[ 

785 mode.get_entropy(temperature, contributions=True) 

786 for mode in self.modes 

787 ] 

788 ) 

789 S = np.sum(S) 

790 

791 self.print_contributions(self.combine_contributions(contribs), verbose) 

792 vprint('-' * 49) 

793 vprint(fmt % ('S', S, S * temperature)) 

794 vprint('=' * 49) 

795 

796 return S 

797 

798 def get_helmholtz_energy( 

799 self, temperature: float, verbose: bool = True 

800 ) -> float: 

801 """Returns the Helmholtz free energy, in eV, in the harmonic 

802 approximation at a specified temperature (K).""" 

803 

804 self.verbose = True 

805 vprint = self._vprint 

806 

807 U = self.get_internal_energy(temperature, verbose=verbose) 

808 vprint('') 

809 S = self.get_entropy(temperature, verbose=verbose) 

810 F = U - temperature * S 

811 

812 vprint('') 

813 vprint('Free energy components at T = %.2f K:' % temperature) 

814 vprint('=' * 23) 

815 fmt = '%5s%15.3f eV' 

816 vprint(fmt % ('U', U)) 

817 vprint(fmt % ('-T*S', -temperature * S)) 

818 vprint('-' * 23) 

819 vprint(fmt % ('F', F)) 

820 vprint('=' * 23) 

821 return F 

822 

823 

824class QuasiHarmonicThermo(HarmonicThermo): 

825 """Subclass of :class:`HarmonicThermo`, including the quasi-harmonic 

826 approximation of Cramer, Truhlar and coworkers :doi:`10.1021/jp205508z`. 

827 

828 Note: This class not include the translational and rotational 

829 contributions to the entropy by default. Use the get_ideal_entropy method 

830 for that and add them manually. 

831 

832 Inputs: 

833 

834 vib_energies : list 

835 a list of the energies of the vibrations (e.g., from 

836 ase.vibrations.Vibrations.get_energies). The number of 

837 energies should match the number of degrees of freedom of the 

838 adsorbate; i.e., 3*n, where n is the number of atoms. Note that 

839 this class does not check that the user has supplied the correct 

840 number of energies. Units of energies are eV. 

841 potentialenergy : float 

842 the potential energy in eV (e.g., from atoms.get_potential_energy) 

843 (if potentialenergy is unspecified, then the methods of this 

844 class can be interpreted as the energy corrections) 

845 ignore_imag_modes : bool 

846 If 'True', any imaginary frequencies will be removed in the 

847 calculation of the thermochemical properties. 

848 If 'False' (default), an error will be raised if any imaginary 

849 frequencies are present. 

850 modes : list of AbstractMode 

851 A list of mode objects. If not provided, :class:`HarmonicMode` objects 

852 will be created from the raised vib_energies. This is useful if you want 

853 to replace individual modes with non-harmonic modes. 

854 raise_to : float 

855 The value to which all frequencies smaller than this value will be 

856 raised. Unit is eV. Defaults to :math:`100cm^{-1} = 0.012398 eV`. 

857 

858 """ 

859 

860 @staticmethod 

861 def _raise(input: Sequence[float], raise_to: float) -> Sequence[float]: 

862 return [raise_to if x < raise_to else x for x in input] 

863 

864 def __init__( 

865 self, 

866 vib_energies: Sequence[complex], 

867 potentialenergy: float = 0.0, 

868 ignore_imag_modes: bool = False, 

869 modes: Sequence[AbstractMode] | None = None, 

870 raise_to: float = 100 * units.invcm, 

871 ) -> None: 

872 

873 # Check for imaginary frequencies. 

874 vib_energies, _ = _clean_vib_energies(vib_energies, ignore_imag_modes) 

875 # raise the low frequencies to a certain value 

876 vib_energies = self._raise(vib_energies, raise_to) 

877 if modes is None: 

878 modes = [HarmonicMode(energy) for energy in vib_energies] 

879 super().__init__( 

880 vib_energies, 

881 potentialenergy=potentialenergy, 

882 ignore_imag_modes=ignore_imag_modes, 

883 modes=modes, 

884 ) 

885 

886 

887class MSRRHOThermo(QuasiHarmonicThermo): 

888 """Subclass of :class:`QuasiHarmonicThermo`, 

889 including Grimme's scaling method based on 

890 :doi:`10.1002/chem.201200497` and :doi:`10.1039/D1SC00621E`. 

891 

892 Note: This class not include the translational and rotational 

893 contributions to the entropy by default. Use the get_ideal_entropy method 

894 for that and add them manually. 

895 

896 We enforce treating imaginary modes as Grimme suggests (converting 

897 them to real by multiplying them with :math:`-i`). So make sure to check 

898 your input energies. 

899 

900 Inputs: 

901 

902 vib_energies : list 

903 a list of the energies of the vibrations (e.g., from 

904 ase.vibrations.Vibrations.get_energies). The number of 

905 energies should match the number of degrees of freedom of the 

906 atoms object; i.e., 3*n, where n is the number of atoms. Note that 

907 this class does not check that the user has supplied the correct 

908 number of energies. Units of energies are eV. Note, that if 'modes' 

909 are given, these energies are not used. 

910 atoms: an ASE atoms object 

911 used to calculate rotational moments of inertia and molecular mass. 

912 Should not contain periodic boundary conditions. 

913 tau : float 

914 the vibrational energy threshold in :math:`cm^{-1}`, namcomplexed 

915 :math:`\\tau` in :doi:`10.1039/D1SC00621E`. 

916 Values close or equal to 0 will result in the standard harmonic 

917 approximation. Defaults to :math:`35cm^{-1}`. 

918 nu_scal : float 

919 Linear scaling factor for the vibrational frequencies. Named 

920 :math:`\\nu_{scal}` in :doi:`10.1039/D1SC00621E`. 

921 Defaults to 1.0, check the `Truhlar group database 

922 <https://comp.chem.umn.edu/freqscale/index.html>`_ 

923 for values corresponding to your level of theory. 

924 Note that for :math:`\\nu_{scal}=1.0` this method is equivalent to 

925 the quasi-RRHO method in :doi:`10.1002/chem.201200497`. 

926 treat_int_energy : bool 

927 Extend the msRRHO treatement to the internal energy. If False, only 

928 the entropy contribution as in Grimmmes paper is considered. 

929 If true, the approach of Otlyotov and Minenkov 

930 :doi:`10.1002/jcc.27129` is used. 

931 modes : list of AbstractMode 

932 A list of mode objects. If not provided, :class:`RRHOMode` objects will 

933 be created from the raised vib_energies. This is useful if you want to 

934 replace individual modes with non-harmonic modes. 

935 

936 """ 

937 

938 def __init__( 

939 self, 

940 vib_energies: Sequence[complex], 

941 atoms: Atoms, 

942 potentialenergy: float = 0.0, 

943 tau: float = 35.0, 

944 nu_scal: float = 1.0, 

945 treat_int_energy: bool = False, 

946 modes: Sequence[AbstractMode] | None = None, 

947 ) -> None: 

948 

949 # check that atoms has no periodic boundary conditions 

950 # moments of inertia are wrong otherwise. 

951 if atoms.pbc.any(): 

952 raise ValueError( 

953 'Atoms object should not have periodic ' 

954 'boundary conditions for MSRRHOThermo.' 

955 ) 

956 inertia = np.mean(atoms.get_moments_of_inertia()) 

957 self.atoms = atoms 

958 

959 # clean the energies by converting imaginary to real 

960 # i.e. multiply with -i 

961 vib_e: Sequence[float] # make mypy happy 

962 vib_e = [ 

963 np.imag(v) if np.iscomplex(v) else np.real(v) for v in vib_energies 

964 ] 

965 

966 self.nu_scal = nu_scal 

967 # scale the frequencies (i.e. energies) before passing them on 

968 vib_e_scaled = [float(v) for v in np.multiply(vib_e, nu_scal)] 

969 

970 if modes is None: 

971 modes = [ 

972 RRHOMode( 

973 energy, inertia, tau=tau, treat_int_energy=treat_int_energy 

974 ) 

975 for energy in vib_e_scaled 

976 ] 

977 

978 super().__init__( 

979 vib_e_scaled, 

980 potentialenergy=potentialenergy, 

981 ignore_imag_modes=False, 

982 modes=modes, 

983 raise_to=0.0, 

984 ) 

985 self.treat_int_energy = treat_int_energy 

986 

987 

988class HinderedThermo(BaseThermoChem): 

989 """Class for calculating thermodynamic properties in the hindered 

990 translator and hindered rotor model where all but three degrees of 

991 freedom are treated as harmonic vibrations, two are treated as 

992 hindered translations, and one is treated as a hindered rotation. 

993 

994 Inputs: 

995 

996 vib_energies : list 

997 a list of all the vibrational energies of the adsorbate (e.g., from 

998 ase.vibrations.Vibrations.get_energies). If atoms is not provided, 

999 then the number of energies must match the number of degrees of freedom 

1000 of the adsorbate; i.e., 3*n, where n is the number of atoms. Note 

1001 that this class does not check that the user has supplied the 

1002 correct number of energies. 

1003 Units of energies are eV. 

1004 trans_barrier_energy : float 

1005 the translational energy barrier in eV. This is the barrier for an 

1006 adsorbate to diffuse on the surface. 

1007 rot_barrier_energy : float 

1008 the rotational energy barrier in eV. This is the barrier for an 

1009 adsorbate to rotate about an axis perpendicular to the surface. 

1010 sitedensity : float 

1011 density of surface sites in cm^-2 

1012 rotationalminima : integer 

1013 the number of equivalent minima for an adsorbate's full rotation. 

1014 For example, 6 for an adsorbate on an fcc(111) top site 

1015 potentialenergy : float 

1016 the potential energy in eV (e.g., from atoms.get_potential_energy) 

1017 (if potentialenergy is unspecified, then the methods of this class 

1018 can be interpreted as the energy corrections) 

1019 mass : float 

1020 the mass of the adsorbate in amu (if mass is unspecified, then it will 

1021 be calculated from the atoms class) 

1022 inertia : float 

1023 the reduced moment of inertia of the adsorbate in amu*Ang^-2 

1024 (if inertia is unspecified, then it will be calculated from the 

1025 atoms class) 

1026 atoms : an ASE atoms object 

1027 used to calculate rotational moments of inertia and molecular mass 

1028 symmetrynumber : integer 

1029 symmetry number of the adsorbate. This is the number of symmetric arms 

1030 of the adsorbate and depends upon how it is bound to the surface. 

1031 For example, propane bound through its end carbon has a symmetry 

1032 number of 1 but propane bound through its middle carbon has a symmetry 

1033 number of 2. (if symmetrynumber is unspecified, then the default is 1) 

1034 ignore_imag_modes : bool 

1035 If 'True', any imaginary frequencies present after the 3N-3 cut will 

1036 be removed in the calculation of the thermochemical properties. 

1037 If 'False' (default), an error will be raised if imaginary frequencies 

1038 are present after the 3N-3 cut. 

1039 """ 

1040 

1041 def __init__( 

1042 self, 

1043 vib_energies, 

1044 trans_barrier_energy, 

1045 rot_barrier_energy, 

1046 sitedensity, 

1047 rotationalminima, 

1048 potentialenergy=0.0, 

1049 mass=None, 

1050 inertia=None, 

1051 atoms=None, 

1052 symmetrynumber=1, 

1053 ignore_imag_modes: bool = False, 

1054 ) -> None: 

1055 

1056 self.trans_barrier_energy = trans_barrier_energy * units._e 

1057 self.rot_barrier_energy = rot_barrier_energy * units._e 

1058 self.area = 1.0 / sitedensity / 100.0**2 

1059 self.rotationalminima = rotationalminima 

1060 self.potentialenergy = potentialenergy 

1061 self.atoms = atoms 

1062 self.symmetry = symmetrynumber 

1063 

1064 # Sort the vibrations 

1065 vib_energies = list(vib_energies) 

1066 vib_energies.sort(key=np.abs) 

1067 

1068 # Keep only the relevant vibrational energies (3N-3) 

1069 if atoms: 

1070 vib_energies = vib_energies[-(3 * len(atoms) - 3) :] 

1071 else: 

1072 vib_energies = vib_energies[-(len(vib_energies) - 3) :] 

1073 

1074 # Check for imaginary frequencies. 

1075 vib_energies, n_imag = _clean_vib_energies( 

1076 vib_energies, ignore_imag_modes 

1077 ) 

1078 super().__init__(vib_energies=vib_energies) 

1079 self.n_imag = n_imag 

1080 

1081 if (mass or atoms) and (inertia or atoms): 

1082 if mass: 

1083 self.mass = mass * units._amu 

1084 elif atoms: 

1085 self.mass = np.sum(atoms.get_masses()) * units._amu 

1086 if inertia: 

1087 self.inertia = inertia * units._amu / units.m**2 

1088 elif atoms: 

1089 # This is tricky because the moments of inertia 

1090 # only work for non-periodic systems. 

1091 # Check it here and raise an error if periodic 

1092 if atoms.get_pbc().any(): 

1093 raise RuntimeError( 

1094 'Atoms object with periodic ' 

1095 'boundary conditions cannot be ' 

1096 'used to calculate moments of ' 

1097 'inertia. Please provide ' 

1098 'a non-periodic Atoms object.' 

1099 ) 

1100 self.inertia = ( 

1101 atoms.get_moments_of_inertia()[2] * units._amu / units.m**2 

1102 ) 

1103 else: 

1104 raise RuntimeError( 

1105 'Either mass and inertia of the ' 

1106 'adsorbate must be specified or ' 

1107 'atoms must be specified.' 

1108 ) 

1109 

1110 # Calculate hindered translational and rotational frequencies 

1111 self.freq_t = np.sqrt( 

1112 self.trans_barrier_energy / (2 * self.mass * self.area) 

1113 ) 

1114 self.freq_r = ( 

1115 1.0 

1116 / (2 * np.pi) 

1117 * np.sqrt( 

1118 self.rotationalminima**2 

1119 * self.rot_barrier_energy 

1120 / (2 * self.inertia) 

1121 ) 

1122 ) 

1123 

1124 def get_internal_energy(self, temperature, verbose=True): 

1125 """Returns the internal energy (including the zero point energy), 

1126 in eV, in the hindered translator and hindered rotor model at a 

1127 specified temperature (K).""" 

1128 

1129 from scipy.special import iv 

1130 

1131 self.verbose = verbose 

1132 vprint = self._vprint 

1133 fmt = '%-15s%13.3f eV' 

1134 vprint('Internal energy components at T = %.2f K:' % temperature) 

1135 vprint('=' * 31) 

1136 

1137 U = 0.0 

1138 

1139 vprint(fmt % ('E_pot', self.potentialenergy)) 

1140 U += self.potentialenergy 

1141 

1142 # Translational Energy 

1143 T_t = units._k * temperature / (units._hplanck * self.freq_t) 

1144 R_t = self.trans_barrier_energy / (units._hplanck * self.freq_t) 

1145 dU_t = 2 * ( 

1146 -1.0 / 2 

1147 - 1.0 / T_t / (2 + 16 * R_t) 

1148 + R_t / 2 / T_t 

1149 - R_t / 2 / T_t * iv(1, R_t / 2 / T_t) / iv(0, R_t / 2 / T_t) 

1150 + 1.0 / T_t / (np.exp(1.0 / T_t) - 1) 

1151 ) 

1152 dU_t *= units.kB * temperature 

1153 vprint(fmt % ('E_trans', dU_t)) 

1154 U += dU_t 

1155 

1156 # Rotational Energy 

1157 T_r = units._k * temperature / (units._hplanck * self.freq_r) 

1158 R_r = self.rot_barrier_energy / (units._hplanck * self.freq_r) 

1159 dU_r = ( 

1160 -1.0 / 2 

1161 - 1.0 / T_r / (2 + 16 * R_r) 

1162 + R_r / 2 / T_r 

1163 - R_r / 2 / T_r * iv(1, R_r / 2 / T_r) / iv(0, R_r / 2 / T_r) 

1164 + 1.0 / T_r / (np.exp(1.0 / T_r) - 1) 

1165 ) 

1166 dU_r *= units.kB * temperature 

1167 vprint(fmt % ('E_rot', dU_r)) 

1168 U += dU_r 

1169 

1170 # Vibrational Energy 

1171 dU_v = self.get_vib_energy_contribution(temperature) 

1172 vprint(fmt % ('E_vib', dU_v)) 

1173 U += dU_v 

1174 

1175 # Zero Point Energy 

1176 dU_zpe = self.get_zero_point_energy() 

1177 vprint(fmt % ('E_ZPE', dU_zpe)) 

1178 U += dU_zpe 

1179 

1180 vprint('-' * 31) 

1181 vprint(fmt % ('U', U)) 

1182 vprint('=' * 31) 

1183 return U 

1184 

1185 def get_zero_point_energy(self, verbose=True): 

1186 """Returns the zero point energy, in eV, in the hindered 

1187 translator and hindered rotor model""" 

1188 

1189 zpe_t = 2 * (1.0 / 2 * self.freq_t * units._hplanck / units._e) 

1190 zpe_r = 1.0 / 2 * self.freq_r * units._hplanck / units._e 

1191 zpe_v = self.get_ZPE_correction() 

1192 zpe = zpe_t + zpe_r + zpe_v 

1193 return zpe 

1194 

1195 def get_entropy(self, temperature, pressure=units.bar, verbose=True): 

1196 """Returns the entropy, in eV/K, in the hindered translator 

1197 and hindered rotor model at a specified temperature (K).""" 

1198 

1199 from scipy.special import iv 

1200 

1201 self.verbose = verbose 

1202 vrpint = self._vprint 

1203 fmt = '%-15s%13.7f eV/K%13.3f eV' 

1204 vrpint('Entropy components at T = %.2f K:' % temperature) 

1205 vrpint('=' * 49) 

1206 vrpint('%15s%13s %13s' % ('', 'S', 'T*S')) 

1207 

1208 S = 0.0 

1209 

1210 # Translational Entropy 

1211 T_t = units._k * temperature / (units._hplanck * self.freq_t) 

1212 R_t = self.trans_barrier_energy / (units._hplanck * self.freq_t) 

1213 S_t = 2 * ( 

1214 -1.0 / 2 

1215 + 1.0 / 2 * np.log(np.pi * R_t / T_t) 

1216 - R_t / 2 / T_t * iv(1, R_t / 2 / T_t) / iv(0, R_t / 2 / T_t) 

1217 + np.log(iv(0, R_t / 2 / T_t)) 

1218 + 1.0 / T_t / (np.exp(1.0 / T_t) - 1) 

1219 - np.log(1 - np.exp(-1.0 / T_t)) 

1220 ) 

1221 S_t *= units.kB 

1222 vrpint(fmt % ('S_trans', S_t, S_t * temperature)) 

1223 S += S_t 

1224 

1225 # Rotational Entropy 

1226 T_r = units._k * temperature / (units._hplanck * self.freq_r) 

1227 R_r = self.rot_barrier_energy / (units._hplanck * self.freq_r) 

1228 S_r = ( 

1229 -1.0 / 2 

1230 + 1.0 / 2 * np.log(np.pi * R_r / T_r) 

1231 - np.log(self.symmetry) 

1232 - R_r / 2 / T_r * iv(1, R_r / 2 / T_r) / iv(0, R_r / 2 / T_r) 

1233 + np.log(iv(0, R_r / 2 / T_r)) 

1234 + 1.0 / T_r / (np.exp(1.0 / T_r) - 1) 

1235 - np.log(1 - np.exp(-1.0 / T_r)) 

1236 ) 

1237 S_r *= units.kB 

1238 vrpint(fmt % ('S_rot', S_r, S_r * temperature)) 

1239 S += S_r 

1240 

1241 # Vibrational Entropy 

1242 S_v = self.get_vib_entropy_contribution(temperature) 

1243 vrpint(fmt % ('S_vib', S_v, S_v * temperature)) 

1244 S += S_v 

1245 

1246 # Concentration Related Entropy 

1247 N_over_A = np.exp(1.0 / 3) * (10.0**5 / (units._k * temperature)) ** ( 

1248 2.0 / 3 

1249 ) 

1250 S_c = 1 - np.log(N_over_A) - np.log(self.area) 

1251 S_c *= units.kB 

1252 vrpint(fmt % ('S_con', S_c, S_c * temperature)) 

1253 S += S_c 

1254 

1255 vrpint('-' * 49) 

1256 vrpint(fmt % ('S', S, S * temperature)) 

1257 vrpint('=' * 49) 

1258 return S 

1259 

1260 def get_helmholtz_energy(self, temperature, verbose=True): 

1261 """Returns the Helmholtz free energy, in eV, in the hindered 

1262 translator and hindered rotor model at a specified temperature 

1263 (K).""" 

1264 

1265 self.verbose = True 

1266 vprint = self._vprint 

1267 

1268 U = self.get_internal_energy(temperature, verbose=verbose) 

1269 vprint('') 

1270 S = self.get_entropy(temperature, verbose=verbose) 

1271 F = U - temperature * S 

1272 

1273 vprint('') 

1274 vprint('Free energy components at T = %.2f K:' % temperature) 

1275 vprint('=' * 23) 

1276 fmt = '%5s%15.3f eV' 

1277 vprint(fmt % ('U', U)) 

1278 vprint(fmt % ('-T*S', -temperature * S)) 

1279 vprint('-' * 23) 

1280 vprint(fmt % ('F', F)) 

1281 vprint('=' * 23) 

1282 return F 

1283 

1284 

1285class IdealGasThermo(BaseThermoChem): 

1286 """Class for calculating thermodynamic properties of a molecule 

1287 based on statistical mechanical treatments in the ideal gas 

1288 approximation. 

1289 

1290 Inputs for enthalpy calculations: 

1291 

1292 vib_energies : list 

1293 a list of the vibrational energies of the molecule (e.g., from 

1294 ase.vibrations.Vibrations.get_energies). The number of expected 

1295 vibrations is calculated by the geometry and the number of atoms. 

1296 By default, the lowest energies are cut to enforce the expected 

1297 length. By setting vib_selection, this behaviour can be changed. 

1298 If either atoms and natoms is unspecified, the full list is used. 

1299 Units are eV. 

1300 geometry : 'monatomic', 'linear', or 'nonlinear' 

1301 geometry of the molecule 

1302 potentialenergy : float 

1303 the potential energy in eV (e.g., from atoms.get_potential_energy) 

1304 (if potentialenergy is unspecified, then the methods of this 

1305 class can be interpreted as the energy corrections) 

1306 natoms : integer 

1307 the number of atoms, used along with 'geometry' to determine how 

1308 many vibrations to use. (Not needed if an atoms object is supplied 

1309 in 'atoms' or if the user desires the entire list of vibrations 

1310 to be used.) 

1311 vib_selection : 'exact', 'highest' (default), 'abs_highest', 'all' 

1312 selection of input vibrational energies considered to be true 

1313 vibrations (excluding translations and rotations) implied by the 

1314 geometry and number of atoms. Only applied if number of atoms 

1315 is provided, either with natoms or atoms. 

1316 - 'exact': no selection; the number of input vibrational energies must 

1317 be equal to the number of true vibrations 

1318 - 'highest': select vibrational energies whose square is the highest 

1319 , i.e. large real energies followed by small real energies, small 

1320 imaginary energies and large imaginary energies. Will not catch 

1321 unrealistically large imaginary frequencies, resulting from e.g. 

1322 unrelaxed molecules. This is the default. 

1323 - 'abs_highest': select vibrational energies whose absolute number are 

1324 highest, real or imaginary. Will fail intentionally for 

1325 unrealistically large imaginary frequencies, but also unintentionally 

1326 for small real energies, corresponding e.g. to frustrated rotations 

1327 in a larger molecule. 

1328 - 'all': Use all input vibrational energies without checking the 

1329 number of them. 

1330 ignore_imag_modes : bool 

1331 If 'True', any imaginary frequencies present after the 3N-3 cut will 

1332 be removed in the calculation of the thermochemical properties. 

1333 If 'False' (default), an error will be raised if imaginary frequencies 

1334 are present after the 3N-3 cut. 

1335 

1336 Extra inputs needed for entropy / free energy calculations: 

1337 

1338 atoms : an ASE atoms object 

1339 used to calculate rotational moments of inertia and molecular mass 

1340 symmetrynumber : integer 

1341 symmetry number of the molecule. See, for example, Table 10.1 and 

1342 Appendix B of C. Cramer "Essentials of Computational Chemistry", 

1343 2nd Ed. 

1344 spin : float 

1345 the total electronic spin. (0 for molecules in which all electrons 

1346 are paired, 0.5 for a free radical with a single unpaired electron, 

1347 1.0 for a triplet with two unpaired electrons, such as O_2.) 

1348 This is a magnitude, not a spin z-projection, so it must be 

1349 non-negative; a negative value raises a ValueError. 

1350 

1351 """ 

1352 

1353 def __init__( 

1354 self, 

1355 vib_energies: Sequence[complex], 

1356 geometry: _GEOMETRY_OPTIONS, 

1357 potentialenergy: float = 0.0, 

1358 atoms: Atoms | None = None, 

1359 symmetrynumber: int | None = None, 

1360 spin: float | None = None, 

1361 natoms: int | None = None, 

1362 vib_selection: _VIB_SELECTION_OPTIONS | None = 'highest', 

1363 ignore_imag_modes: bool = False, 

1364 modes: Sequence[AbstractMode] | None = None, 

1365 ) -> None: 

1366 self.potentialenergy = potentialenergy 

1367 self.geometry = geometry 

1368 self.sigma = symmetrynumber 

1369 if natoms is None and atoms: 

1370 natoms = len(atoms) 

1371 

1372 # Preliminary sorting vibrations by square 

1373 vib_energies = list(vib_energies) 

1374 vib_energies.sort(key=lambda f: (f**2).real) 

1375 

1376 if natoms and vib_selection != 'all': 

1377 # Determine number of true vibrations from geometry 

1378 if geometry == 'nonlinear': 

1379 num_vibs = 3 * natoms - 6 

1380 elif geometry == 'linear': 

1381 num_vibs = 3 * natoms - 5 

1382 elif geometry == 'monatomic': 

1383 num_vibs = 0 

1384 else: 

1385 raise ValueError(f'Unsupported geometry: {geometry}') 

1386 if num_vibs < 0: 

1387 raise ValueError( 

1388 f'Number of atoms ({natoms}) too small for ' 

1389 + f"geometry '{geometry}'." 

1390 ) 

1391 

1392 if vib_selection == 'exact': 

1393 # Demand the expected number of true vibrations 

1394 if len(vib_energies) != num_vibs: 

1395 raise ValueError( 

1396 f'{num_vibs} vibrational energies expected, ' 

1397 + f'{len(vib_energies)} received.\n' 

1398 + 'To select true vibrational energies automatically,' 

1399 + ' set vib_selection.' 

1400 ) 

1401 

1402 elif vib_selection in ('highest', 'abs_highest'): 

1403 # Cut vibrations to get the expected number of true vibrations 

1404 if num_vibs == 0: 

1405 vib_energies = [] 

1406 else: 

1407 if vib_selection == 'abs_highest': 

1408 vib_energies.sort(key=np.abs) 

1409 vib_energies = vib_energies[-num_vibs:] 

1410 if len(vib_energies) != num_vibs: 

1411 raise ValueError( 

1412 f'Too few vibration modes ({len(vib_energies)}) ' 

1413 + f'after selection. {num_vibs} expected' 

1414 ) 

1415 else: 

1416 raise ValueError( 

1417 f'(Unsupported vib_selection: {vib_selection})' 

1418 ) 

1419 elif not natoms and not atoms and vib_selection != 'all': 

1420 raise ValueError( 

1421 'Either natoms or atoms must be specified to select ' 

1422 + "true vibrational energies. Else, set vib_selection to 'all'." 

1423 ) 

1424 

1425 # Check for imaginary frequencies. 

1426 vib_energies, n_imag = _clean_vib_energies( 

1427 vib_energies, ignore_imag_modes 

1428 ) 

1429 super().__init__(vib_energies=vib_energies, atoms=atoms, spin=spin) 

1430 self.n_imag = n_imag 

1431 

1432 def get_internal_energy( 

1433 self, temperature: float, verbose: bool = True 

1434 ) -> float: 

1435 """Returns the internal energy, in eV, in the ideal gas approximation 

1436 at a specified temperature (K).""" 

1437 

1438 self.verbose = verbose 

1439 vprint = self._vprint 

1440 fmt = '%-15s%13.3f eV' 

1441 vprint('Enthalpy components at T = %.2f K:' % temperature) 

1442 vprint('=' * 31) 

1443 

1444 U = 0.0 

1445 

1446 vprint(fmt % ('E_pot', self.potentialenergy)) 

1447 U += self.potentialenergy 

1448 

1449 zpe = self.get_ZPE_correction() 

1450 vprint(fmt % ('E_ZPE', zpe)) 

1451 U += zpe 

1452 

1453 Cv_tT = self.get_ideal_translational_energy(temperature) 

1454 vprint(fmt % ('Cv_trans (0->T)', Cv_tT)) 

1455 U += Cv_tT 

1456 

1457 Cv_rT = self.get_ideal_rotational_energy(self.geometry, temperature) 

1458 vprint(fmt % ('Cv_rot (0->T)', Cv_rT)) 

1459 U += Cv_rT 

1460 

1461 dU_v = self.get_vib_energy_contribution(temperature) 

1462 vprint(fmt % ('Cv_vib (0->T)', dU_v)) 

1463 U += dU_v 

1464 

1465 vprint('-' * 31) 

1466 vprint(fmt % ('U', U)) 

1467 vprint('=' * 31) 

1468 return U 

1469 

1470 def get_enthalpy(self, temperature: float, verbose: bool = True) -> float: 

1471 """Returns the enthalpy, in eV, in the ideal gas approximation 

1472 at a specified temperature (K).""" 

1473 

1474 self.verbose = verbose 

1475 vprint = self._vprint 

1476 fmt = '%-15s%13.3f eV' 

1477 vprint('Enthalpy components at T = %.2f K:' % temperature) 

1478 vprint('=' * 31) 

1479 

1480 H = 0.0 

1481 H += self.get_internal_energy(temperature, verbose=verbose) 

1482 

1483 Cp_corr = units.kB * temperature 

1484 vprint(fmt % ('(C_v -> C_p)', Cp_corr)) 

1485 H += Cp_corr 

1486 

1487 vprint('-' * 31) 

1488 vprint(fmt % ('H', H)) 

1489 vprint('=' * 31) 

1490 return H 

1491 

1492 def get_entropy( 

1493 self, 

1494 temperature: float, 

1495 pressure: float = units.bar, 

1496 verbose: bool = True, 

1497 ) -> float: 

1498 """Returns the entropy, in eV/K, in the ideal gas approximation 

1499 at a specified temperature (K) and pressure (Pa).""" 

1500 

1501 if self.atoms is None or self.sigma is None or self.spin is None: 

1502 raise RuntimeError( 

1503 'atoms, symmetrynumber, and spin must be ' 

1504 'specified for entropy and free energy ' 

1505 'calculations.' 

1506 ) 

1507 self.verbose = verbose 

1508 vprint = self._vprint 

1509 fmt = '%-15s%13.7f eV/K%13.3f eV' 

1510 vprint( 

1511 f'Entropy components at T = {temperature:.2f} K and' 

1512 f' P = {pressure:.1f} Pa:' 

1513 ) 

1514 vprint('=' * 49) 

1515 vprint('{"":15s}{"S":13s} {"T*S:13s}') 

1516 S, S_dict = self.get_ideal_entropy( 

1517 temperature, 

1518 translation=True, 

1519 vibration=True, 

1520 rotation=True, 

1521 geometry=self.geometry, 

1522 electronic=True, 

1523 pressure=pressure, 

1524 symmetrynumber=self.sigma, 

1525 ) 

1526 

1527 vprint( 

1528 fmt 

1529 % ('S_trans (1 bar)', S_dict['S_t'], S_dict['S_t'] * temperature) 

1530 ) 

1531 vprint(fmt % ('S_rot', S_dict['S_r'], S_dict['S_r'] * temperature)) 

1532 vprint(fmt % ('S_elec', S_dict['S_e'], S_dict['S_e'] * temperature)) 

1533 vprint(fmt % ('S_vib', S_dict['S_v'], S_dict['S_v'] * temperature)) 

1534 vprint( 

1535 fmt % ('S (1 bar -> P)', S_dict['S_p'], S_dict['S_p'] * temperature) 

1536 ) 

1537 vprint('-' * 49) 

1538 vprint(fmt % ('S', S, S * temperature)) 

1539 vprint('=' * 49) 

1540 return S 

1541 

1542 def get_gibbs_energy( 

1543 self, temperature: float, pressure: float, verbose: bool = True 

1544 ) -> float: 

1545 """Returns the Gibbs free energy, in eV, in the ideal gas 

1546 approximation at a specified temperature (K) and pressure (Pa).""" 

1547 

1548 self.verbose = verbose 

1549 vprint = self._vprint 

1550 

1551 H = self.get_enthalpy(temperature, verbose=verbose) 

1552 vprint('') 

1553 S = self.get_entropy(temperature, pressure=pressure, verbose=verbose) 

1554 G = H - temperature * S 

1555 

1556 vprint('') 

1557 vprint( 

1558 'Free energy components at T = %.2f K and P = %.1f Pa:' 

1559 % (temperature, pressure) 

1560 ) 

1561 vprint('=' * 23) 

1562 fmt = '%5s%15.3f eV' 

1563 vprint(fmt % ('H', H)) 

1564 vprint(fmt % ('-T*S', -temperature * S)) 

1565 vprint('-' * 23) 

1566 vprint(fmt % ('G', G)) 

1567 vprint('=' * 23) 

1568 return G 

1569 

1570 

1571class CrystalThermo(BaseThermoChem): 

1572 """Class for calculating thermodynamic properties of a crystalline 

1573 solid in the approximation that a lattice of N atoms behaves as a 

1574 system of 3N independent harmonic oscillators. 

1575 

1576 Inputs: 

1577 

1578 phonon_DOS : list 

1579 a list of the phonon density of states, 

1580 where each value represents the phonon DOS at the vibrational energy 

1581 value of the corresponding index in phonon_energies. 

1582 

1583 phonon_energies : list 

1584 a list of the range of vibrational energies (hbar*omega) over which 

1585 the phonon density of states has been evaluated. This list should be 

1586 the same length as phonon_DOS and integrating phonon_DOS over 

1587 phonon_energies should yield approximately 3N, where N is the number 

1588 of atoms per unit cell. If the first element of this list is 

1589 zero-valued it will be deleted along with the first element of 

1590 phonon_DOS. Units of vibrational energies are eV. 

1591 

1592 potentialenergy : float 

1593 the potential energy in eV (e.g., from atoms.get_potential_energy) 

1594 (if potentialenergy is unspecified, then the methods of this 

1595 class can be interpreted as the energy corrections) 

1596 

1597 formula_units : int 

1598 the number of formula units per unit cell. If unspecified, the 

1599 thermodynamic quantities calculated will be listed on a 

1600 per-unit-cell basis. 

1601 """ 

1602 

1603 @classmethod 

1604 def from_transition_state(cls, *args, **kwargs) -> 'CrystalThermo': 

1605 """ 

1606 Not yet implemented for CrystalThermo but needed to overwrite 

1607 BaseThermoChem method. 

1608 """ 

1609 raise NotImplementedError( 

1610 'from_transition_state is not implemented for CrystalThermo.' 

1611 ) 

1612 

1613 def __init__( 

1614 self, 

1615 phonon_DOS, 

1616 phonon_energies, 

1617 formula_units=None, 

1618 potentialenergy=0.0, 

1619 ): 

1620 self.phonon_energies = phonon_energies 

1621 self.phonon_DOS = phonon_DOS 

1622 

1623 if formula_units: 

1624 self.formula_units = formula_units 

1625 self.potentialenergy = potentialenergy / formula_units 

1626 else: 

1627 self.formula_units = 0 

1628 self.potentialenergy = potentialenergy 

1629 

1630 def get_internal_energy(self, temperature, verbose=True): 

1631 """Returns the internal energy, in eV, of crystalline solid 

1632 at a specified temperature (K).""" 

1633 

1634 self.verbose = verbose 

1635 vprint = self._vprint 

1636 fmt = '%-15s%13.4f eV' 

1637 if self.formula_units == 0: 

1638 vprint( 

1639 'Internal energy components at ' 

1640 'T = %.2f K,\non a per-unit-cell basis:' % temperature 

1641 ) 

1642 else: 

1643 vprint( 

1644 'Internal energy components at ' 

1645 'T = %.2f K,\non a per-formula-unit basis:' % temperature 

1646 ) 

1647 vprint('=' * 31) 

1648 

1649 U = 0.0 

1650 

1651 omega_e = self.phonon_energies 

1652 dos_e = self.phonon_DOS 

1653 if omega_e[0] == 0.0: 

1654 omega_e = np.delete(omega_e, 0) 

1655 dos_e = np.delete(dos_e, 0) 

1656 

1657 vprint(fmt % ('E_pot', self.potentialenergy)) 

1658 U += self.potentialenergy 

1659 

1660 zpe_list = omega_e / 2.0 

1661 if self.formula_units == 0: 

1662 zpe = trapezoid(zpe_list * dos_e, omega_e) 

1663 else: 

1664 zpe = trapezoid(zpe_list * dos_e, omega_e) / self.formula_units 

1665 vprint(fmt % ('E_ZPE', zpe)) 

1666 U += zpe 

1667 

1668 B = 1.0 / (units.kB * temperature) 

1669 E_vib = omega_e / (np.exp(omega_e * B) - 1.0) 

1670 if self.formula_units == 0: 

1671 E_phonon = trapezoid(E_vib * dos_e, omega_e) 

1672 else: 

1673 E_phonon = trapezoid(E_vib * dos_e, omega_e) / self.formula_units 

1674 vprint(fmt % ('E_phonon', E_phonon)) 

1675 U += E_phonon 

1676 

1677 vprint('-' * 31) 

1678 vprint(fmt % ('U', U)) 

1679 vprint('=' * 31) 

1680 return U 

1681 

1682 def get_entropy(self, temperature, verbose=True): 

1683 """Returns the entropy, in eV/K, of crystalline solid 

1684 at a specified temperature (K).""" 

1685 

1686 self.verbose = verbose 

1687 vprint = self._vprint 

1688 fmt = '%-15s%13.7f eV/K%13.4f eV' 

1689 if self.formula_units == 0: 

1690 vprint( 

1691 'Entropy components at ' 

1692 'T = %.2f K,\non a per-unit-cell basis:' % temperature 

1693 ) 

1694 else: 

1695 vprint( 

1696 'Entropy components at ' 

1697 'T = %.2f K,\non a per-formula-unit basis:' % temperature 

1698 ) 

1699 vprint('=' * 49) 

1700 vprint('%15s%13s %13s' % ('', 'S', 'T*S')) 

1701 

1702 omega_e = self.phonon_energies 

1703 dos_e = self.phonon_DOS 

1704 if omega_e[0] == 0.0: 

1705 omega_e = np.delete(omega_e, 0) 

1706 dos_e = np.delete(dos_e, 0) 

1707 

1708 B = 1.0 / (units.kB * temperature) 

1709 S_vib = omega_e / ( 

1710 temperature * (np.exp(omega_e * B) - 1.0) 

1711 ) - units.kB * np.log(1.0 - np.exp(-omega_e * B)) 

1712 if self.formula_units == 0: 

1713 S = trapezoid(S_vib * dos_e, omega_e) 

1714 else: 

1715 S = trapezoid(S_vib * dos_e, omega_e) / self.formula_units 

1716 

1717 vprint('-' * 49) 

1718 vprint(fmt % ('S', S, S * temperature)) 

1719 vprint('=' * 49) 

1720 return S 

1721 

1722 def get_helmholtz_energy(self, temperature, verbose=True): 

1723 """Returns the Helmholtz free energy, in eV, of crystalline solid 

1724 at a specified temperature (K).""" 

1725 

1726 self.verbose = True 

1727 vprint = self._vprint 

1728 

1729 U = self.get_internal_energy(temperature, verbose=verbose) 

1730 vprint('') 

1731 S = self.get_entropy(temperature, verbose=verbose) 

1732 F = U - temperature * S 

1733 

1734 vprint('') 

1735 if self.formula_units == 0: 

1736 vprint( 

1737 'Helmholtz free energy components at ' 

1738 'T = %.2f K,\non a per-unit-cell basis:' % temperature 

1739 ) 

1740 else: 

1741 vprint( 

1742 'Helmholtz free energy components at ' 

1743 'T = %.2f K,\non a per-formula-unit basis:' % temperature 

1744 ) 

1745 vprint('=' * 23) 

1746 fmt = '%5s%15.4f eV' 

1747 vprint(fmt % ('U', U)) 

1748 vprint(fmt % ('-T*S', -temperature * S)) 

1749 vprint('-' * 23) 

1750 vprint(fmt % ('F', F)) 

1751 vprint('=' * 23) 

1752 return F 

1753 

1754 

1755def _clean_vib_energies( 

1756 vib_energies: Sequence[complex], ignore_imag_modes: bool = False 

1757) -> tuple[Sequence[float], int]: 

1758 """Checks and deal with the presence of imaginary vibrational modes 

1759 

1760 Also removes +0.j from real vibrational energies. 

1761 

1762 Inputs: 

1763 

1764 vib_energies : list 

1765 a list of the vibrational energies 

1766 

1767 ignore_imag_modes : bool 

1768 If 'True', any imaginary frequencies will be removed. 

1769 If 'False' (default), an error will be raised if imaginary 

1770 frequencies are present. 

1771 

1772 Outputs: 

1773 

1774 vib_energies : list 

1775 a list of the real vibrational energies. 

1776 

1777 n_imag : int 

1778 the number of imaginary frequencies treated. 

1779 """ 

1780 # raise to a value, accept int and float in contrast to documentation 

1781 if ignore_imag_modes: 

1782 n_vib_energies = len(vib_energies) 

1783 vib_energies = [np.real(v) for v in vib_energies if np.real(v) > 0] 

1784 n_imag = n_vib_energies - len(vib_energies) 

1785 if n_imag > 0: 

1786 warn(f'{n_imag} imag modes removed', UserWarning) 

1787 else: 

1788 if sum(np.iscomplex(vib_energies)): 

1789 raise ValueError('Imaginary vibrational energies are present.') 

1790 n_imag = 0 

1791 ret = [np.real(v) for v in vib_energies] # clear +0.j 

1792 

1793 return ret, n_imag