Debian Codegraph @

goodvibes/thermo.py

raw
1 # -*- coding: utf-8 -*-
2
3 import math
4 import os.path
5 import sys
6 import warnings
7 from dataclasses import dataclass
8 from typing import Optional, Union
9
10 import numpy as np
11
12 from .io import parse_qcdata, parse_data, sp_cpu as _sp_cpu, find_spc_file
13
14 # PHYSICAL CONSTANTS & UNITS
15 GAS_CONSTANT = 8.3144621 # J / K / mol
16 PLANCK_CONSTANT = 6.62606957e-34 # J * s
17 BOLTZMANN_CONSTANT = 1.3806488e-23 # J / K
18 SPEED_OF_LIGHT = 2.99792458e10 # cm / s
19 AVOGADRO_CONSTANT = 6.0221415e23 # 1 / mol
20 AMU_to_KG = 1.66053886E-27 # UNIT CONVERSION
21 J_TO_AU = 4.184 * 627.509541 * 1000.0 # UNIT CONVERSION
22 GRIMME_BAV = 1.00e-44 # Default average moment of inertia (kg m^2) from Grimme
23
24 # Solvents supported by --freespace (Shakhnovich & Whitesides free-volume model).
25 # Case-sensitive — these are the literal strings the user must pass.
26 FREESPACE_SOLVENTS = ("H2O", "toluene", "DMF", "AcOH", "chloroform")
27
28
29 # Symmetry numbers for different point groups
30 pg_sm = {"C1": 1, "Cs": 1, "Ci": 1, "C2": 2, "C3": 3, "C4": 4, "C5": 5, "C6": 6, "C7": 7, "C8": 8, "D2": 4, "D3": 6,
31 "D4": 8, "D5": 10, "D6": 12, "D7": 14, "D8": 16, "C2v": 2, "C3v": 3, "C4v": 4, "C5v": 5, "C6v": 6, "C7v": 7,
32 "C8v": 8, "C2h": 2, "C3h": 3, "C4h": 4, "C5h": 5, "C6h": 6, "C7h": 7, "C8h": 8, "D2h": 4, "D3h": 6, "D4h": 8,
33 "D5h": 10, "D6h": 12, "D7h": 14, "D8h": 16, "D2d": 4, "D3d": 6, "D4d": 8, "D5d": 10, "D6d": 12, "D7d": 14,
34 "D8d": 16, "S4": 4, "S6": 6, "S8": 8, "T": 6, "Th": 12, "Td": 12, "O": 12, "Oh": 24, "Cinfv": 1, "Dinfh": 2,
35 "I": 30, "Ih": 60, "Kh": 1}
36
37
38
39
40 def calc_translational_energy(temperature):
41 """
42 Compute the ideal-gas translational molar energy at a specified temperature.
43
44 Parameters:
45 temperature (float): Temperature in kelvin (K).
46
47 Returns:
48 float: Translational energy in joules per mole (J/mol), equal to 3/2 · R · T.
49 """
50 energy = 1.5 * GAS_CONSTANT * temperature
51 return energy
52
53
54 def calc_rotational_energy(temperature, monatomic=False, linear=False):
55 """
56 Compute the rotational energy for a species at a given temperature.
57
58 Returns 0 for monatomic species, R*T for linear molecules, and 3/2*R*T for non-linear molecules.
59
60 Parameters:
61 temperature (float): Temperature in kelvin.
62 monatomic (bool): If True, treat as a single atom (zero rotational energy).
63 linear (bool): If True, treat as a linear molecule (use R*T).
64
65 Returns:
66 float: Rotational energy in joules per mole.
67 """
68 if monatomic:
69 energy = 0.0
70 elif linear:
71 energy = GAS_CONSTANT * temperature
72 else:
73 energy = 1.5 * GAS_CONSTANT * temperature
74 return energy
75
76
77 def calc_vibrational_energy(temperature, frequency_wn, freq_scale_factor=1.0, fract_modelsys=None):
78 """
79 Compute the vibrational energy (zero-point + thermal contributions) in joules per mole at a given temperature.
80
81 Parameters:
82 temperature (float): Temperature in kelvin; must be greater than 0.
83 frequency_wn (list[float]): Vibrational mode wavenumbers in cm^-1.
84 freq_scale_factor (float or list[float], optional): Frequency scaling factor. If ONIOM blending is used (fract_modelsys provided), supply [qm_scale, mm_scale]; otherwise a single scalar scale factor is applied to all modes.
85 fract_modelsys (list[float] or None, optional): Per-mode ONIOM fractions (values between 0 and 1). When provided, per-mode scale factors are computed by blending the two entries of `freq_scale_factor` according to these fractions. If None, no ONIOM blending is applied.
86
87 Returns:
88 float: Total vibrational energy (J/mol), including zero-point energy and thermal excitations.
89
90 Raises:
91 ValueError: If `temperature` is not greater than 0, or if mode energies produce numerical overflow (indicative of too-low temperature).
92 """
93 if temperature <= 0:
94 raise ValueError(
95 "Temperature must be positive for vibrational energy calculation."
96 )
97
98 if fract_modelsys is not None:
99 s0, s1 = freq_scale_factor[0], freq_scale_factor[1]
100 freq_scale_factor = [s0 * fm + s1 * (1.0 - fm) for fm in fract_modelsys]
101 factor = [(PLANCK_CONSTANT * f * SPEED_OF_LIGHT * s) / (BOLTZMANN_CONSTANT * temperature)
102 for f, s in zip(frequency_wn, freq_scale_factor)]
103 else:
104 factor = [(PLANCK_CONSTANT * freq * SPEED_OF_LIGHT * freq_scale_factor) /
105 (BOLTZMANN_CONSTANT * temperature) for freq in frequency_wn]
106
107 # Error occurs if T is too low when performing math.exp
108 for entry in factor:
109 if entry > math.log(sys.float_info.max):
110 raise ValueError(
111 "Temperature may be too low to calculate vibrational energy. "
112 "Please adjust using the `-t` option and try again."
113 )
114
115 energy = [entry * GAS_CONSTANT * temperature * (0.5 + (1.0 / (math.exp(entry) - 1.0)))
116 for entry in factor]
117
118 return sum(energy)
119
120
121 def calc_zeropoint_energy(frequency_wn, freq_scale_factor = 1.0, fract_modelsys = None):
122 """
123 Compute the vibrational zero-point energy for a set of vibrational modes.
124
125 When `fract_modelsys` is provided, `freq_scale_factor` is expected to be a two-element sequence
126 `[qm_scale, mm_scale]`; per-mode scale factors are blended using the fractions in `fract_modelsys`.
127
128 Parameters:
129 frequency_wn (list): Vibrational wavenumbers (cm^-1).
130 freq_scale_factor (float or sequence): Global scale factor or `[qm_scale, mm_scale]` for ONIOM blending.
131 fract_modelsys (list, optional): Per-mode fractions for ONIOM blending; if given, a per-mode
132 scale factor is computed by blending the two entries of `freq_scale_factor`.
133
134 Returns:
135 float: Vibrational zero-point energy (J/mol), computed as the sum over modes of 0.5 * h * nu.
136 """
137 if fract_modelsys is not None:
138 s0, s1 = freq_scale_factor[0], freq_scale_factor[1]
139 freq_scale_factor = [s0 * fm + s1 * (1.0 - fm) for fm in fract_modelsys]
140 factor = [(PLANCK_CONSTANT * f * SPEED_OF_LIGHT * s) / (BOLTZMANN_CONSTANT)
141 for f, s in zip(frequency_wn, freq_scale_factor)]
142 else:
143 factor = [(PLANCK_CONSTANT * freq * SPEED_OF_LIGHT * freq_scale_factor) / (BOLTZMANN_CONSTANT)
144 for freq in frequency_wn]
145 energy = [0.5 * entry * GAS_CONSTANT for entry in factor]
146 return sum(energy)
147
148
149 def get_free_space(solv):
150 """
151 Estimate the accessible free volume in a bulk solvent (mL per L).
152
153 Computes the volume fraction of a litre of solvent that is not occupied by solvent
154 molecules using literature molarities and molecular volumes (Shakhnovich & Whitesides).
155 This function is deprecated and experimental.
156
157 Parameters:
158 solv (str): Solvent name (case-sensitive) expected in the supported set.
159
160 Returns:
161 float: Estimated accessible free volume in milliliters per liter.
162
163 Notes:
164 - If `solv` is not recognized a UserWarning is emitted and the function
165 returns 1000.0 (gas-phase fallback).
166 - The function emits a DeprecationWarning on use.
167 """
168 import warnings
169 warnings.warn(
170 "get_free_space is experimental and no longer recommended.",
171 DeprecationWarning,
172 stacklevel=2,
173 )
174 solvent_list = list(FREESPACE_SOLVENTS)
175 molarity = [55.6, 9.4, 12.9, 17.4, 12.5] # mol/l
176 molecular_vol = [27.944, 149.070, 77.442, 86.10, 97.0] # Angstrom^3
177
178 if solv not in solvent_list:
179 warnings.warn(
180 f"Solvent '{solv}' not recognized. Supported solvents: "
181 f"{', '.join(solvent_list)}. Returning gas-phase free space.",
182 UserWarning,
183 stacklevel=2,
184 )
185 return 1000.0
186
187 idx = solvent_list.index(solv)
188 solv_molarity = molarity[idx]
189 solv_volume = molecular_vol[idx]
190 v_free = 8 * ((1E27 / (solv_molarity * AVOGADRO_CONSTANT)) ** 0.333333 - solv_volume ** 0.333333) ** 3
191 freespace = v_free * solv_molarity * AVOGADRO_CONSTANT * 1E-24
192 return freespace
193
194
195 def calc_translational_entropy(molecular_mass, conc, temperature, solvent = None):
196 """
197 Calculate the translational entropy for a species at a given temperature and concentration.
198
199 Parameters:
200 molecular_mass (float): Molecular mass in atomic mass units (amu).
201 conc (float): Concentration in moles per liter (mol/L).
202 temperature (float): Temperature in kelvin (K).
203 solvent (str, optional): If provided, adjusts the effective free volume using the solvent name via get_free_space; if None, assumes ideal-gas volume.
204
205 Returns:
206 float: Translational entropy in joules per mole per kelvin (J/(mol·K)).
207 """
208 lmda = ((2.0 * math.pi * molecular_mass * AMU_to_KG * BOLTZMANN_CONSTANT * temperature) ** 0.5) / PLANCK_CONSTANT
209 if solvent is not None:
210 freespace = get_free_space(solvent)
211 ndens = conc * 1000 * AVOGADRO_CONSTANT / (freespace / 1000.0)
212 else:
213 ndens = conc * 1000 * AVOGADRO_CONSTANT # number per m^3
214
215 entropy = GAS_CONSTANT * (2.5 + math.log(lmda ** 3 / ndens))
216 return entropy
217
218
219 def calc_electronic_entropy(multiplicity):
220 """
221 Compute the electronic entropy contribution from spin multiplicity.
222
223 Parameters:
224 multiplicity (int): Spin multiplicity (number of degenerate electronic states).
225
226 Returns:
227 float: Electronic entropy in J/(mol*K), equal to R * ln(multiplicity).
228 """
229 entropy = GAS_CONSTANT * (math.log(multiplicity))
230 return entropy
231
232
233 def calc_rotational_entropy(temperature, rotemp, symmno=1, monatomic=False, linear=False):
234 """
235 Calculate the rotational entropy of a species at a given temperature.
236
237 Parameters:
238 temperature (float): Temperature in kelvin.
239 rotemp (Sequence[float]): Rotational temperatures (K). For linear molecules provide at least one value; for non-linear provide three principal rotational temperatures.
240 symmno (int): Molecular symmetry number (default 1).
241 monatomic (bool): If True, treat as a single atom (entropy = 0).
242 linear (bool): If True, treat as a linear molecule.
243
244 Returns:
245 float: Rotational entropy in J/(mol·K).
246 """
247 if monatomic:
248 return 0.0
249
250 if linear:
251 if rotemp is None or len(rotemp) < 1:
252 raise ValueError(
253 "calc_rotational_entropy: invalid `rotemp` for linear molecule "
254 "(monatomic=False, linear=True). Expected len(rotemp) >= 1."
255 )
256 qrot = temperature / rotemp[0]
257 return GAS_CONSTANT * (math.log(qrot / symmno) + 1)
258
259 if rotemp is None or len(rotemp) < 3:
260 raise ValueError(
261 "calc_rotational_entropy: invalid `rotemp` for non-linear molecule "
262 "(monatomic=False, linear=False). Expected len(rotemp) >= 3."
263 )
264 qrot = (math.pi * temperature ** 3 / (rotemp[0] * rotemp[1] * rotemp[2])) ** 0.5
265 return GAS_CONSTANT * (math.log(qrot / symmno) + 1.5)
266
267
268 def calc_rrho_entropy(temperature, frequency_wn, freq_scale_factor = 1.0, fract_modelsys=None):
269 """
270 Compute per-mode vibrational entropies using the rigid-rotor harmonic-oscillator (RRHO) model.
271
272 Supports ONIOM-style blending of QM/MM scale factors when `fract_modelsys` is provided: in that case `freq_scale_factor` is expected to be a two-element iterable [qm_scale, mm_scale] and per-mode scale factors are blended by the fractions in `fract_modelsys`.
273
274 Parameters:
275 temperature (float): Temperature in kelvin.
276 frequency_wn (iterable): Vibrational wavenumbers in cm⁻¹.
277 freq_scale_factor (float or iterable): Frequency scaling factor applied to each mode, or a two-element sequence [qm_scale, mm_scale] when using ONIOM blending.
278 fract_modelsys (iterable, optional): Per-mode fractions for ONIOM blending; when provided, per-mode scale = qm_scale*frac + mm_scale*(1-frac).
279
280 Returns:
281 List of per-mode vibrational entropies in J/(mol*K).
282 """
283 if fract_modelsys is not None:
284 s0, s1 = freq_scale_factor[0], freq_scale_factor[1]
285 freq_scale_factor = [s0 * fm + s1 * (1.0 - fm) for fm in fract_modelsys]
286 factor = [(PLANCK_CONSTANT * f * SPEED_OF_LIGHT * s) / (BOLTZMANN_CONSTANT * temperature)
287 for f, s in zip(frequency_wn, freq_scale_factor)]
288 else:
289 factor = [(PLANCK_CONSTANT * freq * SPEED_OF_LIGHT * freq_scale_factor) / (BOLTZMANN_CONSTANT * temperature)
290 for freq in frequency_wn]
291 entropy = [entry * GAS_CONSTANT / (math.exp(entry) - 1) - GAS_CONSTANT * math.log(1 - math.exp(-entry))
292 for entry in factor]
293 return entropy
294
295
296 def calc_qRRHO_energy(temperature, frequency_wn, freq_scale_factor = 1.0):
297 """
298 Compute per-mode quasi-rigid-rotor harmonic-oscillator (qRRHO) vibrational energy terms.
299
300 Parameters:
301 temperature (float): Temperature in kelvin used for thermal factors.
302 frequency_wn (list[float]): Vibrational frequencies in cm⁻¹.
303 freq_scale_factor (float | list[float], optional): Global frequency scaling factor (or list of per-mode factors) applied to each frequency.
304
305 Returns:
306 list[float]: Per-mode qRRHO vibrational energy terms in J/mol.
307 """
308 factor = [PLANCK_CONSTANT * freq * SPEED_OF_LIGHT * freq_scale_factor for freq in frequency_wn]
309 energy = [0.5 * AVOGADRO_CONSTANT * entry + GAS_CONSTANT * temperature * entry / BOLTZMANN_CONSTANT
310 / temperature * math.exp(-entry / BOLTZMANN_CONSTANT / temperature) /
311 (1 - math.exp(-entry / BOLTZMANN_CONSTANT / temperature)) for entry in factor]
312 return energy
313
314
315 def calc_avg_moment_of_inertia(roconst):
316 """
317 Compute the average moment of inertia from a sequence of rotational constants.
318
319 Parameters:
320 roconst (list[float]): Rotational constants in gigahertz (GHz).
321
322 Returns:
323 float: Average moment of inertia in kilogram square meters (kg·m^2).
324
325 Raises:
326 ValueError: If `roconst` is empty or if the mean rotational constant is not greater than zero.
327 """
328 if not roconst:
329 raise ValueError("roconst list cannot be empty")
330 av_roconst_ghz = sum(roconst) / len(roconst) # GHz
331 if av_roconst_ghz <= 0:
332 raise ValueError("Average rotational constant must be positive")
333 av_roconst_hz = av_roconst_ghz * 1e9 # Hz
334 return PLANCK_CONSTANT / av_roconst_hz # kg m^2
335
336
337 def calc_freerot_entropy(temperature, frequency_wn, bav=GRIMME_BAV, freq_scale_factor=1.0, fract_modelsys=None):
338 """
339 Compute per-mode free-rotor vibrational entropies for a list of vibrational modes.
340
341 Parameters:
342 temperature (float): Temperature in kelvin.
343 frequency_wn (Sequence[float]): Vibrational frequencies in cm^-1.
344 bav (float): Reference average moment of inertia in kg·m^2 (defaults to GRIMME_BAV).
345 freq_scale_factor (float or Sequence[float]): Frequency scale factor applied to modes. If ONIOM blending is used (fract_modelsys provided), this should be a two-item sequence [qm_scale, mm_scale].
346 fract_modelsys (Sequence[float] or None): Per-mode ONIOM fractions (values in [0,1]) to blend QM/MM scale factors; pass None to disable ONIOM blending.
347
348 Returns:
349 list[float]: Per-mode free-rotor entropies in J/(mol·K).
350 """
351 if fract_modelsys is not None:
352 s0, s1 = freq_scale_factor[0], freq_scale_factor[1]
353 freq_scale_factor = [s0 * fm + s1 * (1.0 - fm) for fm in fract_modelsys]
354 mu = [PLANCK_CONSTANT / (8 * math.pi ** 2 * f * SPEED_OF_LIGHT * s)
355 for f, s in zip(frequency_wn, freq_scale_factor)]
356 else:
357 mu = [PLANCK_CONSTANT / (8 * math.pi ** 2 * freq * SPEED_OF_LIGHT * freq_scale_factor) for freq in frequency_wn]
358 mu_primed = [entry * bav / (entry + bav) for entry in mu]
359 factor = [8 * math.pi ** 3 * entry * BOLTZMANN_CONSTANT * temperature / PLANCK_CONSTANT ** 2 for entry in mu_primed]
360 entropy = [(0.5 + math.log(entry ** 0.5)) * GAS_CONSTANT for entry in factor]
361 return entropy
362
363
364 def calc_damp(frequency_wn, freq_cutoff):
365 """
366 Compute per-mode damping factors for quasi-harmonic interpolation between RRHO and free-rotor entropy regimes.
367
368 Parameters:
369 frequency_wn (list[float]): Vibrational frequencies in cm^-1.
370 freq_cutoff (float): Cutoff frequency in cm^-1 at which the damping factor is approximately 0.5.
371
372 Returns:
373 list[float]: Damping factors (0 to 1) for each input frequency; values near 1 indicate RRHO behavior, values near 0 indicate free-rotor behavior.
374 """
375 alpha = 4
376 damp = [1 / (1 + (freq_cutoff / entry) ** alpha) for entry in frequency_wn]
377 return damp
378
379
380 def _apply_frequency_inversion(raw_freqs, raw_im_freqs, invert, job_type):
381 """
382 Decide which parsed imaginary vibrational frequencies to keep as imaginary and which to invert to positive values based on the user-specified inversion policy.
383
384 Parameters:
385 raw_freqs (iterable[float]): Parsed non-imaginary (positive) vibrational frequencies (cm⁻¹).
386 raw_im_freqs (iterable[float]): Parsed imaginary (negative) vibrational frequencies (cm⁻¹).
387 invert (None | str | numeric): Inversion policy:
388 - None: leave all imaginary frequencies as imaginary.
389 - 'auto': invert imaginary frequencies to positive except that for job types containing "TSFreq" the single most-negative mode is retained as imaginary.
390 - numeric (or numeric string): invert imaginary frequencies whose value is greater than this numeric threshold; others remain imaginary.
391 job_type (str): Job type string used to detect transition-state frequency handling (looks for substring "TSFreq").
392
393 Returns:
394 tuple:
395 frequency_wn (list[float]): Final list of positive frequencies (original positives plus any inverted modes).
396 im_frequency_wn (list[float]): Imaginary frequencies retained as negative values.
397 inverted_freqs (list[float]): Imaginary frequencies that were inverted (original negative values).
398 """
399 im_freq_cutoff = 0.0
400 frequency_wn = []
401 im_frequency_wn = []
402 inverted_freqs = []
403
404 # Copy positive frequencies directly
405 frequency_wn = list(raw_freqs)
406
407 # Apply inversion policy to imaginary frequencies
408 # Determine the most negative frequency for TS auto-inversion
409 all_raw = list(raw_freqs) + list(raw_im_freqs)
410 most_low_freq = min(all_raw) if all_raw else 0.0
411
412 for x in raw_im_freqs:
413 if x < -1 * im_freq_cutoff:
414 if invert is not None:
415 if invert == 'auto':
416 if "TSFreq" in job_type:
417 if x == most_low_freq:
418 im_frequency_wn.append(x)
419 else:
420 frequency_wn.append(x * -1.)
421 inverted_freqs.append(x)
422 else:
423 frequency_wn.append(x * -1.)
424 inverted_freqs.append(x)
425 elif x > float(invert):
426 frequency_wn.append(x * -1.)
427 inverted_freqs.append(x)
428 else:
429 im_frequency_wn.append(x)
430 else:
431 im_frequency_wn.append(x)
432
433 return frequency_wn, im_frequency_wn, inverted_freqs
434
435
436 @dataclass(frozen=True)
437 class ThermoOptions:
438 """Bundle of thermochemistry options for `calc_bbe.from_options`.
439
440 Frozen so it's safe to share across worker processes (parallel
441 parsing) and across multiple `calc_bbe` calls without accidental
442 mutation. Field names match the v4.2 façade `compute_thermo` kwargs;
443 the older `calc_bbe.__init__` parameter names are mapped internally.
444 """
445 QS: str = "grimme" # 'grimme' or 'truhlar'
446 QH: bool = False # Head-Gordon enthalpy correction
447 s_freq_cutoff: float = 100.0 # entropy cutoff (cm⁻¹)
448 h_freq_cutoff: float = 100.0 # enthalpy cutoff (cm⁻¹)
449 temperature: float = 298.15 # K
450 concentration: Optional[float] = None # mol/L; None → gas-phase 1 atm
451 freq_scale_factor: Optional[float] = None # None → auto-lookup harm_fac
452 zpe_scale_factor: Optional[float] = None # None → auto-lookup zpe_fac
453 solv: Optional[str] = None # solvent name for free-space corr
454 spc: Optional[str] = None # 'link' or filename suffix
455 invert: Optional[float] = None # imag → real cutoff (cm⁻¹)
456 symm: bool = False # pymsym symmetry-number correction
457 mm_freq_scale_factor: Optional[float] = None
458 inertia: str = "global"
459
460 def _to_calc_bbe_kwargs(self):
461 """Map ThermoOptions fields onto the calc_bbe constructor's
462 (older, less consistent) parameter names. Resolves
463 concentration to the gas-phase 1 atm value when not supplied,
464 so calc_bbe never receives None for `conc`."""
465 conc = self.concentration
466 if conc is None:
467 # Inline the gas-phase reference to avoid a constants import here.
468 ATMOS_kPa = 101.325
469 R_J_per_K_per_mol = 8.3144621
470 conc = ATMOS_kPa / (R_J_per_K_per_mol * self.temperature)
471 return {
472 "QS": self.QS, "QH": self.QH,
473 "cutoff": self.s_freq_cutoff,
474 "H_FREQ_CUTOFF": self.h_freq_cutoff,
475 "temp": self.temperature,
476 "conc": conc,
477 "scale_fac": self.freq_scale_factor,
478 "solv": self.solv,
479 "spc": self.spc, "invert": self.invert,
480 "symm": self.symm,
481 "mm_freq_scale_factor": self.mm_freq_scale_factor,
482 "inertia": self.inertia,
483 "zpe_scale_fac": self.zpe_scale_factor,
484 }
485
486
487 class calc_bbe:
488 """
489 Compute "black box" entropy and enthalpy values along with all
490 other thermochemical quantities.
491
492 Computes H, S from partition functions, applying quasi-harmonic corrections
493
494 Attributes:
495 xyz (QCData): contains Cartesian coordinates and atom data.
496 job_type (str): contains information on the type of Gaussian
497 job such as ground or transition state optimization, frequency.
498 roconst (list): list of parsed rotational constants from Gaussian calculations.
499 program (str): program used in chemical computation.
500 version_program (str): program version used in chemical computation.
501 solvation_model (str): solvation model used in chemical computation.
502 file (str): input chemical computation output file.
503 charge (int): overall charge of molecule.
504 empirical_dispersion (str): empirical dispersion model used in computation.
505 multiplicity (int): multiplicity of molecule or chemical system.
506 mult (int): multiplicity of molecule or chemical system.
507 point_group (str): point group of molecule or chemical system used for symmetry corrections.
508 sp_energy (float): single-point energy parsed from output file.
509 sp_program (str): program used for single-point energy calculation.
510 sp_version_program (str): version of program used for single-point energy calculation.
511 sp_solvation_model (str): solvation model used for single-point energy calculation.
512 sp_file (str): single-point energy calculation output file.
513 sp_charge (int): overall charge of molecule in single-point energy calculation.
514 sp_empirical_dispersion (str): empirical dispersion model used in single-point energy computation.
515 sp_multiplicity (int): multiplicity of molecule or chemical system in single-point energy computation.
516 cpu (list): days, hours, mins, secs, msecs of computation time.
517 scf_energy (float): self-consistent field energy.
518 frequency_wn (list): frequencies parsed from chemical computation output file.
519 im_freq (list): imaginary frequencies parsed from chemical computation output file.
520 inverted_freqs (list): frequencies inverted from imaginary to real numbers.
521 zero_point_corr (float): thermal corrections for zero-point energy parsed from file.
522 zpe (float): vibrational zero point energy computed from frequencies.
523 enthalpy (float): enthalpy computed from partition functions.
524 qh_enthalpy (float): enthalpy computed from partition functions, quasi-harmonic corrections applied.
525 entropy (float): entropy of chemical system computed from partition functions.
526 qh_entropy (float): entropy of chemical system computed from
527 partition functions, quasi-harmonic corrections applied.
528 gibbs_free_energy (float): Gibbs free energy of chemical system
529 computed from enthalpy and entropy.
530 qh_gibbs_free_energy (float): Gibbs free energy of chemical system
531 computed from quasi-harmonic enthalpy and/or entropy.
532 linear_warning (bool): flag for linear molecules, may be missing a rotational constant.
533 """
534 def __init__(self, file, QS = "grimme", QH=False, cutoff=100.0, H_FREQ_CUTOFF=100.0, temp=298.15, conc=None, scale_fac=None, solv=None, spc=None,
535 invert=None, symm=False, mm_freq_scale_factor=None, inertia='global', qcdata=None,
536 zpe_scale_fac=None, _from_options=False):
537 """
538 Initialize a calc_bbe instance by parsing QC output (or using provided qcdata) and computing thermochemical quantities (enthalpy, entropy, Gibbs free energy, ZPE, frequency lists, and related intermediate values).
539
540 Parameters:
541 file (str): Path to the quantum-chemistry output file used for parsing when qcdata is not supplied.
542 QS (str): Vibrational entropy scheme; either "grimme" or "truhlar".
543 QH (bool): If True, compute quasi-harmonic (qRRHO/qRRHO enthalpy) corrections.
544 cutoff (float): Frequency cutoff (cm⁻¹) used for quasi-RRHO damping / RRQHO selection.
545 H_FREQ_CUTOFF (float): Frequency cutoff (cm⁻¹) used for quasi-harmonic enthalpy damping.
546 temp (float): Temperature in kelvin for all thermal calculations.
547 conc (float or None): Concentration in mol/L used for translational entropy; None leaves behavior to defaults.
548 scale_fac (float or list or None): Frequency scaling factor (or list for ONIOM: [qm_scale, mm_scale]).
549 solv (str or None): Solvent identifier; if None or 'none', translational entropy is computed as ideal gas.
550 spc (None, bool, or str): Single-point correction control. If not None and not 'link', a single-point file is sought/applied.
551 invert (None, str, or numeric): Policy for handling imaginary frequencies; passed to _apply_frequency_inversion.
552 symm (bool): If True, attempt a symmetry entropy correction via pymsym and add it to computed entropies.
553 mm_freq_scale_factor (float or None): MM frequency scale factor for ONIOM blending; when provided, enables ONIOM blending.
554 inertia (str): 'global' to use the global GRIMME_BAV moment of inertia, otherwise attempt to derive from rotational constants.
555 qcdata (QCData or None): Pre-parsed QC data object; when provided, parsing of file is skipped.
556
557 Notes:
558 - On successful initialization the instance will have computed attributes including (but not limited to)
559 enthalpy, qh_enthalpy, entropy, qh_entropy, gibbs_free_energy, qh_gibbs_free_energy, zpe,
560 frequency_wn, im_frequency_wn, inverted_freqs, and various intermediate thermal terms.
561 - If required frequency/ZPE/rotational data are missing or unparsable, thermal quantities remain unset or zeroed
562 according to the module's behavior.
563 """
564 # The 15-arg constructor is deprecated in v5.0+; new code should use
565 # `calc_bbe.from_options(qcdata_or_path, ThermoOptions(...))` or, at
566 # the highest level, `goodvibes.compute_thermo(...)`. Internal
567 # callers (compute_thermo, the parallel worker) set
568 # `_from_options=True` to suppress the warning.
569 if not _from_options:
570 warnings.warn(
571 "Calling calc_bbe(file, QS, QH, ...) directly is deprecated. "
572 "Use calc_bbe.from_options(qcdata_or_path, ThermoOptions(...)) "
573 "or goodvibes.compute_thermo(path, ...) instead. The legacy "
574 "constructor will be removed in v6.0.",
575 DeprecationWarning,
576 stacklevel=2,
577 )
578 # 1. Parse all data from file (program-agnostic), or use provided cache
579 if qcdata is None:
580 qcdata = parse_qcdata(file)
581
582 # 2. Geometry data (from native parser via qcdata)
583 self.xyz = qcdata
584 self.atom_types = qcdata.atom_types
585 self.atom_nums = qcdata.atom_nums
586 self.cartesians = qcdata.cartesians
587
588 # 3. Populate self attributes from qcdata
589 self.program = qcdata.program
590 self.version_program = qcdata.version_program
591 self.solvation_model = qcdata.solvation_model
592 self.file = qcdata.file
593 self.charge = qcdata.charge
594 self.empirical_dispersion = qcdata.empirical_dispersion
595 self.multiplicity = qcdata.multiplicity
596 self.scf_energy = qcdata.scf_energy
597 self.sp_energy = qcdata.scf_energy
598 self.zero_point_corr = qcdata.zero_point_corr
599 self.job_type = qcdata.job_type
600 self.roconst = qcdata.roconst
601 self.point_group = qcdata.point_group
602 self.cpu = qcdata.cpu
603 self.sp_cpu = None
604
605 molecular_mass = qcdata.molecular_mass
606 symmno = qcdata.symmno
607 linear_mol = 1 if qcdata.linear_mol else 0
608 rotemp = qcdata.rotemp
609 linear_warning = qcdata.linear_warning
610
611 # ONIOM fract_modelsys setup
612 if mm_freq_scale_factor is None:
613 fract_modelsys = None
614 else:
615 fract_modelsys = qcdata.fract_modelsys if qcdata.fract_modelsys else []
616 scale_fac = [scale_fac, mm_freq_scale_factor]
617
618 # 4. Read any single point energies if requested.
619 #
620 # SPC cache: when --spc was used in a previous run that produced
621 # the QCData we're now reading from, the parsed SPC numbers are
622 # carried on qcdata.sp_*. Reuse them when the suffix matches so
623 # `--import` doesn't re-parse the SPC file from disk.
624 if spc and spc != 'link':
625 cached_sp_hit = (
626 qcdata is not None
627 and qcdata.sp_energy is not None
628 and qcdata.sp_suffix == spc
629 )
630 if cached_sp_hit:
631 self.sp_energy = qcdata.sp_energy
632 self.sp_version_program = qcdata.sp_version_program
633 self.sp_solvation_model = qcdata.sp_solvation_model
634 self.sp_charge = qcdata.sp_charge
635 self.sp_empirical_dispersion = qcdata.sp_empirical_dispersion
636 self.sp_multiplicity = qcdata.sp_multiplicity
637 else:
638 name, _ = os.path.splitext(file)
639 sp_file = find_spc_file(name, spc)
640 if sp_file is None:
641 self.sp_energy = '!'
642 else:
643 try:
644 (self.sp_energy, _,
645 self.sp_version_program, self.sp_solvation_model,
646 _, self.sp_charge,
647 self.sp_empirical_dispersion,
648 self.sp_multiplicity) = parse_data(sp_file)
649 self.sp_cpu = _sp_cpu(sp_file)
650 # Persist into qcdata so a subsequent --export
651 # captures the SPC alongside the parent parse.
652 if qcdata is not None:
653 qcdata.sp_energy = self.sp_energy
654 qcdata.sp_version_program = self.sp_version_program
655 qcdata.sp_solvation_model = self.sp_solvation_model
656 qcdata.sp_charge = self.sp_charge
657 qcdata.sp_empirical_dispersion = self.sp_empirical_dispersion
658 qcdata.sp_multiplicity = self.sp_multiplicity
659 qcdata.sp_suffix = spc
660 qcdata.sp_file = os.path.abspath(sp_file)
661 except ValueError:
662 self.sp_energy = '!'
663 elif qcdata is not None and not os.path.exists(file):
664 # Cache-only mode: derive sp_* fields from cached QCData
665 self.sp_energy = qcdata.scf_energy
666 self.sp_version_program = qcdata.version_program
667 self.sp_solvation_model = qcdata.solvation_model
668 self.sp_charge = qcdata.charge
669 self.sp_empirical_dispersion = qcdata.empirical_dispersion
670 self.sp_multiplicity = qcdata.multiplicity
671 else:
672 (self.sp_energy, _,
673 self.sp_version_program, self.sp_solvation_model,
674 _, self.sp_charge,
675 self.sp_empirical_dispersion,
676 self.sp_multiplicity) = parse_data(file)
677
678 # 5. Apply frequency inversion policy (user option, not file parsing)
679 frequency_wn, im_frequency_wn, inverted_freqs = _apply_frequency_inversion(
680 qcdata.frequency_wn, qcdata.im_frequency_wn,
681 invert, self.job_type)
682
683 self.inverted_freqs = inverted_freqs
684
685 # Skip the calculation if unable to parse the frequencies or zpe from the output file
686 if self.zero_point_corr is not None and rotemp and self.scf_energy is not None:
687 cutoffs = [cutoff for freq in frequency_wn]
688
689 # Translational and electronic contributions to the energy and entropy do not depend on frequencies
690 u_trans = calc_translational_energy(temp)
691 solvent = solv if solv not in (None, 'none') else None
692 s_trans = calc_translational_entropy(molecular_mass, conc, temp, solvent)
693 s_elec = calc_electronic_entropy(self.multiplicity)
694
695 # Rotational and Vibrational contributions to the energy entropy.
696 #
697 # The Truhlar database (Alecu et al., JCTC 2010) calibrates ZPE
698 # and harmonic-frequency scale factors *separately* — they
699 # correct for slightly different systematic errors. When
700 # `zpe_scale_fac` is supplied, ZPE uses it; the partition-function
701 # frequencies (H_vib, S_vib) keep using `scale_fac`. When None,
702 # ZPE falls back to `scale_fac` (preserves v4.x.0 behavior).
703 effective_zpe_scale = zpe_scale_fac if zpe_scale_fac is not None else scale_fac
704 if len(frequency_wn) > 0:
705 zpe = calc_zeropoint_energy(frequency_wn, effective_zpe_scale, fract_modelsys)
706 u_rot = calc_rotational_energy(temp, monatomic=(self.zero_point_corr == 0.0), linear=(linear_mol == 1))
707 u_vib = calc_vibrational_energy(temp, frequency_wn, scale_fac, fract_modelsys)
708 s_rot = calc_rotational_entropy(temp, rotemp,
709 symmno=symmno,
710 monatomic=(self.zero_point_corr == 0.0),
711 linear=(linear_mol == 1))
712
713 # Calculate harmonic entropy, free-rotor entropy and damping function for each frequency
714 Svib_rrho = calc_rrho_entropy(temp, frequency_wn, scale_fac, fract_modelsys)
715
716 if cutoff > 0.0:
717 Svib_rrqho = calc_rrho_entropy(temp, cutoffs, scale_fac, fract_modelsys)
718 if inertia != "global" and len(self.roconst) > 0 and any(x != 0.0 for x in self.roconst):
719 try:
720 bav = calc_avg_moment_of_inertia(self.roconst)
721 except (ValueError, ZeroDivisionError):
722 bav = GRIMME_BAV
723 else:
724 bav = GRIMME_BAV
725 Svib_free_rot = calc_freerot_entropy(
726 temp, frequency_wn, bav,
727 scale_fac, fract_modelsys)
728 S_damp = calc_damp(frequency_wn, cutoff)
729
730 # check for qh
731 if QH:
732 Uvib_qrrho = calc_qRRHO_energy(temp, frequency_wn, scale_fac)
733 H_damp = calc_damp(frequency_wn, H_FREQ_CUTOFF)
734
735 # Compute entropy (cal/mol/K) using the two values and damping function
736 vib_entropy = []
737 vib_energy = []
738 for j in range(0, len(frequency_wn)):
739 # Entropy correction
740 if QS == "grimme":
741 vib_entropy.append(Svib_rrho[j] * S_damp[j] + (1 - S_damp[j]) * Svib_free_rot[j])
742 elif QS == "truhlar":
743 if cutoff > 0.0:
744 if frequency_wn[j] > cutoff:
745 vib_entropy.append(Svib_rrho[j])
746 else:
747 vib_entropy.append(Svib_rrqho[j])
748 else:
749 vib_entropy.append(Svib_rrho[j])
750 # Enthalpy correction
751 if QH:
752 vib_energy.append(
753 H_damp[j] * Uvib_qrrho[j] +
754 (1 - H_damp[j]) * 0.5 * GAS_CONSTANT * temp)
755
756 qh_s_vib, h_s_vib = sum(vib_entropy), sum(Svib_rrho)
757 if QH:
758 qh_u_vib = sum(vib_energy)
759 else:
760 zpe, u_rot, u_vib, qh_u_vib, s_rot, h_s_vib, qh_s_vib = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
761
762 # Add terms (converted to au) to get Free energy - perform separately
763 # for harmonic and quasi-harmonic values out of interest
764 self.enthalpy = self.scf_energy + (u_trans + u_rot + u_vib + GAS_CONSTANT * temp) / J_TO_AU
765 self.qh_enthalpy = 0.0
766 if QH:
767 self.qh_enthalpy = self.scf_energy + (u_trans + u_rot + qh_u_vib + GAS_CONSTANT * temp) / J_TO_AU
768 # Single point correction replaces energy from optimization with single point value
769 if spc is not None:
770 try:
771 spc_correction = self.sp_energy - self.scf_energy
772 self.enthalpy += spc_correction
773 if QH:
774 self.qh_enthalpy += spc_correction
775 except TypeError:
776 pass
777
778 self.zpe = zpe / J_TO_AU
779 self.entropy = (s_trans + s_rot + h_s_vib + s_elec) / J_TO_AU
780 self.qh_entropy = (s_trans + s_rot + qh_s_vib + s_elec) / J_TO_AU
781
782 # Symmetry - entropy correction for molecular symmetry
783 if symm:
784 sym_entropy_correction, pgroup = self.sym_correction(file.split('.')[0].replace('/', '_'))
785 self.point_group = pgroup
786 self.entropy += sym_entropy_correction
787 self.qh_entropy += sym_entropy_correction
788
789 # Calculate Free Energy
790 if QH:
791 self.gibbs_free_energy = self.enthalpy - temp * self.entropy
792 self.qh_gibbs_free_energy = self.qh_enthalpy - temp * self.qh_entropy
793 else:
794 self.gibbs_free_energy = self.enthalpy - temp * self.entropy
795 self.qh_gibbs_free_energy = self.enthalpy - temp * self.qh_entropy
796
797 self.frequency_wn = frequency_wn
798 self.im_frequency_wn = im_frequency_wn
799 self.linear_warning = linear_warning
800
801 @classmethod
802 def from_options(cls, qcdata_or_path, options):
803 """Construct a `calc_bbe` from a `ThermoOptions` bundle.
804
805 Recommended v5.0+ entry point — replaces the legacy 15-argument
806 positional constructor (which still works but emits a
807 `DeprecationWarning`). Accepts either a parsed `QCData`
808 instance (skips re-parsing) or a filesystem path (parses
809 internally, like the old constructor).
810
811 When `options.freq_scale_factor` and/or `options.zpe_scale_factor`
812 are `None`, this method auto-looks them up from the file's
813 level of theory via the Truhlar database (mirroring the CLI's
814 behavior). Pass explicit floats to skip the lookup.
815 """
816 if isinstance(qcdata_or_path, str):
817 file = qcdata_or_path
818 qcdata = None
819 else:
820 qcdata = qcdata_or_path
821 file = qcdata.file
822 # Resolve scale factors. Three cases, matching the documented
823 # CLI semantics:
824 # neither set → auto-lookup harm_fac (freq) and zpe_fac
825 # (zpe) from the level of theory
826 # freq set, zpe None → zpe inherits freq (v3.x back-compat:
827 # --vscal X scales everything by X)
828 # freq None, zpe set → freq auto-lookup, zpe explicit
829 # both set → use as-is
830 if options.freq_scale_factor is None or options.zpe_scale_factor is None:
831 from dataclasses import replace
832 harm = options.freq_scale_factor
833 zpe = options.zpe_scale_factor
834 if harm is None and zpe is None:
835 from .io import read_initial
836 from .vib_scale_factors import canonicalize_level, scaling_data_dict
837 entry = None
838 try:
839 lot = read_initial(file)[0]
840 if lot and lot != "none":
841 entry = scaling_data_dict.get(canonicalize_level(lot))
842 except (IOError, OSError):
843 pass
844 harm = entry.harm_fac if entry is not None else 1.0
845 zpe = entry.zpe_fac if entry is not None else 1.0
846 elif harm is not None and zpe is None:
847 # --vscal alone: ZPE inherits (matches v3.x and v4.x.0
848 # behaviour where vscal was the single scale factor).
849 zpe = harm
850 elif harm is None and zpe is not None:
851 from .io import read_initial
852 from .vib_scale_factors import canonicalize_level, scaling_data_dict
853 entry = None
854 try:
855 lot = read_initial(file)[0]
856 if lot and lot != "none":
857 entry = scaling_data_dict.get(canonicalize_level(lot))
858 except (IOError, OSError):
859 pass
860 harm = entry.harm_fac if entry is not None else 1.0
861 options = replace(options, freq_scale_factor=harm, zpe_scale_factor=zpe)
862 return cls(
863 file,
864 qcdata=qcdata,
865 _from_options=True,
866 **options._to_calc_bbe_kwargs(),
867 )
868
869 # Get external symmetry number and point group using pymsym, if available, for symmetry corrections to entropy
870 def ex_sym(self, file):
871 """
872 Determine the molecular point group and symmetry number using pymsym.
873
874 Parameters:
875 file (str): Ignored by this method; present for API compatibility.
876
877 Returns:
878 tuple: (symmetry_number, point_group) where `symmetry_number` is an int and `point_group` is a string.
879
880 Raises:
881 RuntimeError: If the `pymsym` package is not installed.
882 """
883 try:
884 import pymsym
885 except ImportError as e:
886 raise RuntimeError(
887 "pymsym is required for symmetry detection but is not installed. "
888 "Install it with: pip install pymsym"
889 ) from e
890 atom_nums = np.array(self.xyz.atom_nums)
891 positions = np.array(self.xyz.cartesians)
892 pgroup = pymsym.get_point_group(atom_nums, positions)
893 sym_num = pymsym.get_symmetry_number(atom_nums, positions)
894 return sym_num, pgroup
895
896 def sym_correction(self, file):
897 """
898 Compute and return the symmetry entropy correction and detected point group for the structure identified by file.
899
900 Parameters:
901 file (str): Filename or identifier for the structure passed to ex_sym to determine symmetry number and point group.
902
903 Returns:
904 tuple:
905 sym_correction (float): Symmetry entropy correction converted to internal energy units (J/mol divided by J_TO_AU, i.e., same units used elsewhere in the module).
906 pgroup (str): Detected molecular point-group symbol.
907 """
908 ex_sym, pgroup = self.ex_sym(file)
909 sym_correction = (-GAS_CONSTANT * math.log(ex_sym)) / J_TO_AU
910 return sym_correction, pgroup