Debian Codegraph @

goodvibes/api.py

raw
1 """Programmatic API façade for GoodVibes (v4.2 item 5).
2
3 A small import-friendly entry point for notebooks and scripts. Replaces
4 the 15-positional-arg `calc_bbe` constructor with kwargs that have the
5 same defaults as the CLI, and returns a structured `ThermoResult` rather
6 than the raw `calc_bbe` instance.
7
8 from goodvibes import compute_thermo, compute_batch
9 r = compute_thermo("file.log", QH=True, spc="TZ")
10 print(r.qh_gibbs_free_energy)
11
12 rs = compute_batch(glob.glob("*.log"))
13
14 Internally just calls `calc_bbe`; no behavior change relative to the CLI.
15 The underlying `calc_bbe` and `QCData` instances stay accessible via
16 `result.bbe` / `result.qcdata` for advanced use (e.g. PES analysis,
17 direct attribute reads not yet promoted to the result dataclass).
18 """
19 from __future__ import annotations
20
21 from dataclasses import dataclass
22 from typing import Any, List, Optional, Sequence
23
24 from .constants import ATMOS, GAS_CONSTANT
25 from .io import parse_qcdata, read_initial
26 from .thermo import ThermoOptions, calc_bbe
27 from .utils import display_name
28 from .vib_scale_factors import canonicalize_level, scaling_data_dict
29
30
31 @dataclass(frozen=True)
32 class ThermoResult:
33 """Bundle of thermochemistry for one structure.
34
35 All numeric fields are in atomic units (Hartree for energies,
36 Hartree/K for entropies); frequencies are cm⁻¹. Fields that aren't
37 available for the given file (e.g. `qh_enthalpy` when `QH=False`,
38 `sp_energy` when `spc=None`) are reported as `None` rather than
39 a sentinel.
40 """
41 file: str # absolute or as-passed path
42 name: str # display name (basename sans ext)
43
44 # Energies (Hartree)
45 scf_energy: Optional[float]
46 sp_energy: Optional[float]
47 zpe: Optional[float]
48 enthalpy: Optional[float]
49 qh_enthalpy: Optional[float]
50
51 # Entropies (Hartree/K)
52 entropy: Optional[float]
53 qh_entropy: Optional[float]
54
55 # Gibbs energies (Hartree)
56 gibbs_free_energy: Optional[float]
57 qh_gibbs_free_energy: Optional[float]
58
59 # Frequencies (cm⁻¹)
60 frequency_wn: Optional[List[float]]
61 im_frequency_wn: Optional[List[float]]
62 inverted_freqs: Optional[List[float]]
63
64 # Metadata pulled from the source QCData
65 point_group: Optional[str]
66 symmno: Optional[int]
67 linear_mol: bool
68 multiplicity: Optional[int]
69 job_type: Optional[str]
70 level_of_theory: Optional[str]
71 program: Optional[str]
72
73 # Original objects for advanced use (PES analysis, attribute reads
74 # that haven't been promoted to the result surface yet).
75 bbe: Any
76 qcdata: Any
77
78 @property
79 def has_thermo(self) -> bool:
80 """True when calc_bbe found enough information to compute G(T).
81 False for SP-only outputs (no frequency block)."""
82 return self.gibbs_free_energy is not None
83
84
85 def compute_thermo(
86 path: Optional[str] = None,
87 *,
88 qcdata: Any = None,
89 QS: str = "grimme",
90 QH: bool = False,
91 s_freq_cutoff: float = 100.0,
92 h_freq_cutoff: float = 100.0,
93 temperature: float = 298.15,
94 concentration: Optional[float] = None,
95 freq_scale_factor: Optional[float] = None,
96 zpe_scale_factor: Optional[float] = None,
97 solv: Optional[str] = None,
98 spc: Optional[str] = None,
99 invert: Optional[float] = None,
100 symm: bool = False,
101 mm_freq_scale_factor: Optional[float] = None,
102 inertia: str = "global",
103 ) -> ThermoResult:
104 """Compute thermochemistry for one QC output file.
105
106 Pass *either* `path` (a filesystem location) or a pre-parsed
107 `qcdata` (skips re-parsing). When `concentration` is None the
108 gas-phase reference at 1 atm is used (`P / RT`).
109
110 Parameters mirror the CLI:
111 QS 'grimme' (default) or 'truhlar' quasi-harmonic entropy
112 QH apply Head-Gordon quasi-harmonic enthalpy correction
113 s_freq_cutoff entropy cutoff (cm⁻¹)
114 h_freq_cutoff enthalpy cutoff (cm⁻¹) — only used when QH=True
115 temperature K
116 concentration mol/L. None → gas phase 1 atm.
117 freq_scale_factor None → auto-lookup harm_fac from level of theory.
118 Applied to the partition-function frequencies
119 (used in H_vib and S_vib).
120 zpe_scale_factor None → auto-lookup zpe_fac from level of theory.
121 Applied to ZPE only. If `freq_scale_factor` is
122 explicitly set but `zpe_scale_factor` is None,
123 ZPE inherits `freq_scale_factor` (back-compat).
124 solv 'none', or solvent name for free-space correction
125 spc None, 'link', or filename suffix for SPC files
126 invert None, or threshold for converting small imag → real
127 symm apply pymsym symmetry-number correction
128 """
129 if path is None and qcdata is None:
130 raise ValueError("compute_thermo requires either `path` or `qcdata`")
131 if concentration is None:
132 concentration = ATMOS / (GAS_CONSTANT * temperature)
133
134 options = ThermoOptions(
135 QS=QS, QH=QH,
136 s_freq_cutoff=s_freq_cutoff, h_freq_cutoff=h_freq_cutoff,
137 temperature=temperature, concentration=concentration,
138 freq_scale_factor=freq_scale_factor,
139 zpe_scale_factor=zpe_scale_factor,
140 solv=solv, spc=spc, invert=invert,
141 symm=symm, mm_freq_scale_factor=mm_freq_scale_factor,
142 inertia=inertia,
143 )
144 # from_options does the Truhlar-DB auto-lookup when freq/zpe scale
145 # factors are None; we just need the level-of-theory string for the
146 # result's `level_of_theory` field.
147 lot = None
148 if path is not None:
149 try:
150 scanned = read_initial(path)[0]
151 if scanned and scanned != "none":
152 lot = scanned
153 except (IOError, OSError):
154 pass
155 bbe = calc_bbe.from_options(qcdata if qcdata is not None else path, options)
156 return bbe_to_result(bbe, path, level_of_theory=lot)
157
158
159 def compute_batch(
160 paths: Sequence[str],
161 *,
162 jobs: int = 1,
163 **kwargs: Any,
164 ) -> List[ThermoResult]:
165 """Compute thermochemistry for a list of files.
166
167 Parameters:
168 paths: list of QC output file paths.
169 jobs: parallelism level. ``1`` (default) is sequential — no
170 process-pool overhead. ``> 1`` spawns that many worker
171 processes via ``concurrent.futures.ProcessPoolExecutor``.
172 ``0`` or negative uses ``os.cpu_count()`` (or 1 if unknown).
173 **kwargs: forwarded unchanged to every ``compute_thermo`` call.
174
175 Returns:
176 Results in input order (matches ``executor.map``'s contract).
177 Workers can't write to the orchestrator's logger, so per-file
178 ``log.info`` from inside ``calc_bbe`` is silenced under
179 ``jobs > 1``; warnings that surface through ``ThermoResult``
180 (e.g. missing-frequency files) still come through unchanged.
181 """
182 if not paths:
183 return []
184 if jobs <= 0:
185 import os
186 jobs = os.cpu_count() or 1
187 if jobs == 1 or len(paths) == 1:
188 return [compute_thermo(p, **kwargs) for p in paths]
189
190 from concurrent.futures import ProcessPoolExecutor
191 from functools import partial
192 fn = partial(compute_thermo, **kwargs)
193 with ProcessPoolExecutor(max_workers=jobs) as ex:
194 return list(ex.map(fn, paths))
195
196
197 def to_dataframe(results: Sequence[ThermoResult]):
198 """Convert a list of ThermoResults into a pandas DataFrame.
199
200 Pandas is an optional dependency; raises ImportError with an install
201 hint if it isn't available. The DataFrame has one row per result
202 and columns for every public scalar field on `ThermoResult`
203 (omits the `bbe` and `qcdata` references).
204 """
205 try:
206 import pandas as pd
207 except ImportError as exc: # pragma: no cover
208 raise ImportError(
209 "to_dataframe requires pandas; install with `pip install pandas`."
210 ) from exc
211 skip = {"bbe", "qcdata", "frequency_wn", "im_frequency_wn", "inverted_freqs"}
212 rows = []
213 for r in results:
214 rows.append({
215 f.name: getattr(r, f.name)
216 for f in r.__dataclass_fields__.values()
217 if f.name not in skip
218 })
219 return pd.DataFrame(rows)
220
221
222 def to_parquet(results: Sequence[ThermoResult], path: str) -> None:
223 """Write a list of ThermoResults to a Parquet file at `path`.
224
225 Same column set as `to_dataframe`. Requires pandas + a Parquet
226 engine (pyarrow or fastparquet); install with
227 `pip install goodvibes[full]` or `pip install pyarrow`.
228 """
229 df = to_dataframe(results)
230 try:
231 df.to_parquet(path, index=False)
232 except ImportError as exc: # pragma: no cover
233 raise ImportError(
234 "to_parquet requires a Parquet engine. Install pyarrow "
235 "(`pip install pyarrow`) or fastparquet, or use "
236 "`pip install goodvibes[full]`."
237 ) from exc
238
239
240 # ---------------------------------------------------------------------------
241 # helpers
242 # ---------------------------------------------------------------------------
243
244 def bbe_to_result(
245 bbe: Any,
246 path: Optional[str] = None,
247 *,
248 level_of_theory: Optional[str] = None,
249 ) -> ThermoResult:
250 """Project a `calc_bbe` instance into a `ThermoResult`.
251
252 Useful for adapting CLI internals (which keep `thermo_data` as a
253 `{path: calc_bbe}` dict) to the structured API without re-parsing.
254 `level_of_theory` is read from the file via `read_initial()` if not
255 supplied; pass it explicitly to avoid the extra file scan.
256 """
257 qc = getattr(bbe, "xyz", None)
258 file = path if path is not None else getattr(qc, "file", "<unknown>")
259 # Read level_of_theory from the file if it wasn't supplied (lookup
260 # was already done at compute_thermo entry when freq_scale_factor
261 # was None; for the explicit-factor path we still want the field
262 # populated on the result for display).
263 if level_of_theory is None and path is not None:
264 try:
265 lot = read_initial(path)[0]
266 if lot and lot != "none":
267 level_of_theory = lot
268 except (IOError, OSError):
269 pass
270
271 sp = getattr(bbe, "sp_energy", None)
272 if sp == "!":
273 sp = None
274
275 # calc_bbe leaves qh_enthalpy at 0.0 when CLI --QH is False; surface
276 # that as None (the user can still read .bbe.qh_enthalpy directly).
277 qh_h = getattr(bbe, "qh_enthalpy", None)
278 if qh_h == 0.0:
279 qh_h = None
280
281 return ThermoResult(
282 file=file,
283 name=display_name(file),
284 scf_energy=getattr(bbe, "scf_energy", None),
285 sp_energy=sp,
286 zpe=getattr(bbe, "zpe", None),
287 enthalpy=getattr(bbe, "enthalpy", None),
288 qh_enthalpy=qh_h,
289 entropy=getattr(bbe, "entropy", None),
290 qh_entropy=getattr(bbe, "qh_entropy", None),
291 gibbs_free_energy=getattr(bbe, "gibbs_free_energy", None),
292 qh_gibbs_free_energy=getattr(bbe, "qh_gibbs_free_energy", None),
293 frequency_wn=getattr(bbe, "frequency_wn", None) or None,
294 im_frequency_wn=getattr(bbe, "im_frequency_wn", None) or None,
295 inverted_freqs=getattr(bbe, "inverted_freqs", None) or None,
296 point_group=getattr(qc, "point_group", None) if qc else None,
297 symmno=getattr(qc, "symmno", None) if qc else None,
298 linear_mol=bool(getattr(qc, "linear_mol", False)) if qc else False,
299 multiplicity=getattr(qc, "multiplicity", None) if qc else None,
300 job_type=getattr(qc, "job_type", None) if qc else None,
301 level_of_theory=level_of_theory,
302 program=getattr(qc, "program", None) if qc else None,
303 bbe=bbe,
304 qcdata=qc,
305 )