Debian Codegraph @

goodvibes/pes_model.py

raw
1 """PES data model.
2
3 Pure data + arithmetic; no I/O, no parsing, no global state. The model
4 is what the legacy parser and the new YAML parser produce, and what
5 the output layer (Rich tables, JSON) consumes.
6
7 Three layers:
8 ConformerSet one species, ≥1 conformers (calc_bbe instances)
9 Point stoichiometric sum of species at one node of a path
10 Pathway ordered list of points + a designated zero
11 PESResult container of pathways + options + temperatures
12
13 Arithmetic on ThermoVector collapses the legacy nine-parallel-list
14 pattern into one expression: rel = point.thermo(T) - zero.thermo(T).
15 """
16 from __future__ import annotations
17
18 import math
19 import re
20 from dataclasses import dataclass, field
21 from typing import Any, List, Optional, Tuple
22
23 GAS_CONSTANT = 8.3144621 # J / K / mol
24 J_TO_AU = 4.184 * 627.509541 * 1000.0
25 KCAL_TO_AU = 627.509541
26
27
28 # ---------------------------------------------------------------------------
29 # ThermoVector
30 # ---------------------------------------------------------------------------
31
32 @dataclass(frozen=True)
33 class ThermoVector:
34 """Bundle of thermo quantities for one species at one temperature.
35
36 Energy fields are in Hartree; entropy fields are in Hartree/K (matching
37 calc_bbe). sp_energy is None when --spc was not used; arithmetic
38 propagates None (if either operand has sp_energy=None, the result does).
39 """
40 scf_energy: float
41 zpe: float
42 enthalpy: float
43 qh_enthalpy: float
44 entropy: float
45 qh_entropy: float
46 gibbs: float
47 qh_gibbs: float
48 sp_energy: Optional[float] = None
49
50 def __add__(self, other: "ThermoVector") -> "ThermoVector":
51 if not isinstance(other, ThermoVector):
52 return NotImplemented
53 return ThermoVector(
54 scf_energy=self.scf_energy + other.scf_energy,
55 zpe=self.zpe + other.zpe,
56 enthalpy=self.enthalpy + other.enthalpy,
57 qh_enthalpy=self.qh_enthalpy + other.qh_enthalpy,
58 entropy=self.entropy + other.entropy,
59 qh_entropy=self.qh_entropy + other.qh_entropy,
60 gibbs=self.gibbs + other.gibbs,
61 qh_gibbs=self.qh_gibbs + other.qh_gibbs,
62 sp_energy=_add_opt(self.sp_energy, other.sp_energy),
63 )
64
65 def __sub__(self, other: "ThermoVector") -> "ThermoVector":
66 if not isinstance(other, ThermoVector):
67 return NotImplemented
68 return ThermoVector(
69 scf_energy=self.scf_energy - other.scf_energy,
70 zpe=self.zpe - other.zpe,
71 enthalpy=self.enthalpy - other.enthalpy,
72 qh_enthalpy=self.qh_enthalpy - other.qh_enthalpy,
73 entropy=self.entropy - other.entropy,
74 qh_entropy=self.qh_entropy - other.qh_entropy,
75 gibbs=self.gibbs - other.gibbs,
76 qh_gibbs=self.qh_gibbs - other.qh_gibbs,
77 sp_energy=_sub_opt(self.sp_energy, other.sp_energy),
78 )
79
80 def __mul__(self, k) -> "ThermoVector":
81 if not isinstance(k, (int, float)):
82 return NotImplemented
83 return ThermoVector(
84 scf_energy=self.scf_energy * k,
85 zpe=self.zpe * k,
86 enthalpy=self.enthalpy * k,
87 qh_enthalpy=self.qh_enthalpy * k,
88 entropy=self.entropy * k,
89 qh_entropy=self.qh_entropy * k,
90 gibbs=self.gibbs * k,
91 qh_gibbs=self.qh_gibbs * k,
92 sp_energy=self.sp_energy * k if self.sp_energy is not None else None,
93 )
94
95 __rmul__ = __mul__
96
97 @classmethod
98 def zero(cls, with_sp: bool = False) -> "ThermoVector":
99 """Identity element for addition."""
100 return cls(
101 scf_energy=0.0, zpe=0.0, enthalpy=0.0, qh_enthalpy=0.0,
102 entropy=0.0, qh_entropy=0.0, gibbs=0.0, qh_gibbs=0.0,
103 sp_energy=0.0 if with_sp else None,
104 )
105
106
107 def _add_opt(a: Optional[float], b: Optional[float]) -> Optional[float]:
108 if a is None or b is None:
109 return None
110 return a + b
111
112
113 def _sub_opt(a: Optional[float], b: Optional[float]) -> Optional[float]:
114 if a is None or b is None:
115 return None
116 return a - b
117
118
119 def _bbe_to_vector(bbe: Any) -> ThermoVector:
120 """Project a calc_bbe instance into a ThermoVector.
121
122 Treats sp_energy=='!' (the sentinel for "SPC requested but missing")
123 as None — caller must decide whether that's an error.
124
125 `calc_bbe` leaves `qh_enthalpy` at 0.0 unless the CLI `--QH` flag was
126 set; in that case `qh_gibbs_free_energy` is computed from the plain
127 `enthalpy`. Mirror that fallback here so arithmetic on the model
128 produces correct relatives for both QH on and off runs.
129 """
130 sp = getattr(bbe, "sp_energy", None)
131 if sp == "!":
132 sp = None
133 qh_h = bbe.qh_enthalpy if bbe.qh_enthalpy else bbe.enthalpy
134 return ThermoVector(
135 scf_energy=bbe.scf_energy,
136 zpe=bbe.zpe,
137 enthalpy=bbe.enthalpy,
138 qh_enthalpy=qh_h,
139 entropy=bbe.entropy,
140 qh_entropy=bbe.qh_entropy,
141 gibbs=bbe.gibbs_free_energy,
142 qh_gibbs=bbe.qh_gibbs_free_energy,
143 sp_energy=sp,
144 )
145
146
147 # ---------------------------------------------------------------------------
148 # ConformerSet
149 # ---------------------------------------------------------------------------
150
151 @dataclass
152 class ConformerSet:
153 """A named species + ≥1 calc_bbe entries.
154
155 Encapsulates the rollup math: pure Boltzmann average, lowest-only,
156 or gconf-corrected (lowest + Boltzmann adjustment + mixing entropy).
157 """
158 name: str
159 files: List[str]
160 bbes: List[Any] # calc_bbe instances, parallel to `files`
161
162 def __post_init__(self):
163 if len(self.files) != len(self.bbes):
164 raise ValueError(
165 f"ConformerSet {self.name!r}: files and bbes length mismatch "
166 f"({len(self.files)} vs {len(self.bbes)})"
167 )
168 if not self.bbes:
169 raise ValueError(f"ConformerSet {self.name!r} has no conformers")
170
171 @property
172 def is_single(self) -> bool:
173 return len(self.bbes) == 1
174
175 def lowest_conformer(self) -> ThermoVector:
176 """Vector for the conformer with the lowest qh_gibbs_free_energy."""
177 idx = min(range(len(self.bbes)),
178 key=lambda i: self.bbes[i].qh_gibbs_free_energy)
179 return _bbe_to_vector(self.bbes[idx])
180
181 def boltzmann_weighted(self, T: float) -> ThermoVector:
182 """Pure Boltzmann-weighted average over conformers, weights from qh-G."""
183 if self.is_single:
184 return _bbe_to_vector(self.bbes[0])
185 probs = self._boltzmann_probs(T)
186 result: Optional[ThermoVector] = None
187 for p, bbe in zip(probs, self.bbes):
188 term = _bbe_to_vector(bbe) * p
189 result = term if result is None else result + term
190 return result # type: ignore[return-value]
191
192 def gconf_corrected(self, T: float, QH: bool = True) -> ThermoVector:
193 """Lowest conformer + Boltzmann adjustment + mixing entropy −R Σ pᵢ ln pᵢ.
194
195 Mirrors the legacy `pes.get_pes` algorithm:
196 H_tot = H_min + (Σ pᵢ Hᵢ − H_min)
197 S_tot = S_min + (Σ pᵢ Sᵢ + Σ −R pᵢ ln pᵢ − S_min)
198 G(T) = H_tot − T·S_tot (or qh-H/qh-S if QH)
199
200 ZPE/SCF/SPC follow the plain Boltzmann sum (no mixing-entropy
201 correction applies to those).
202 """
203 if self.is_single:
204 return _bbe_to_vector(self.bbes[0])
205
206 probs = self._boltzmann_probs(T)
207 boltz = self.boltzmann_weighted(T)
208 lowest = self.lowest_conformer()
209
210 # Mixing entropy (Hartree / K). Skip terms where p == 0.
211 mix_entropy = -GAS_CONSTANT / J_TO_AU * sum(
212 p * math.log(p) for p in probs if p > 0.0
213 )
214
215 # Lowest + (Boltzmann avg − lowest) reproduces "lowest + adjustment"
216 # in a way that is exact arithmetic on ThermoVectors.
217 adjusted = lowest + (boltz - lowest)
218 # adjusted == boltz exactly; the explicit form is here to mirror the
219 # legacy code's intent. Now add mixing entropy and recompute G(T).
220 s_total = adjusted.entropy + mix_entropy
221 qs_total = adjusted.qh_entropy + mix_entropy
222 h_for_g = adjusted.qh_enthalpy if QH else adjusted.enthalpy
223 return ThermoVector(
224 scf_energy=adjusted.scf_energy,
225 zpe=adjusted.zpe,
226 enthalpy=adjusted.enthalpy,
227 qh_enthalpy=adjusted.qh_enthalpy,
228 entropy=s_total,
229 qh_entropy=qs_total,
230 gibbs=adjusted.enthalpy - T * s_total,
231 qh_gibbs=h_for_g - T * qs_total,
232 sp_energy=adjusted.sp_energy,
233 )
234
235 def _boltzmann_probs(self, T: float) -> List[float]:
236 g_min = min(b.qh_gibbs_free_energy for b in self.bbes)
237 weights = [
238 math.exp(-(b.qh_gibbs_free_energy - g_min) * J_TO_AU / GAS_CONSTANT / T)
239 for b in self.bbes
240 ]
241 norm = sum(weights)
242 return [w / norm for w in weights]
243
244
245 # ---------------------------------------------------------------------------
246 # Point — stoichiometric sum of species
247 # ---------------------------------------------------------------------------
248
249 # Matches "2*A", "2 * A", or "A". Coefficient is optional; default 1.
250 _TERM_RE = re.compile(r"""
251 ^\s*
252 (?:(\d+)\s*\*\s*)? # optional integer coefficient
253 (.+?) # species name (lazy, trims trailing ws)
254 \s*$
255 """, re.VERBOSE)
256
257
258 def parse_point_label(label: str) -> List[Tuple[int, str]]:
259 """Parse a point label like "2*A + B + C" into [(2,'A'), (1,'B'), (1,'C')].
260
261 Whitespace-tolerant. Coefficients must be positive integers. Returns the
262 terms in source order; duplicate species are allowed (they'll be summed).
263 """
264 if not label or not label.strip():
265 raise ValueError("empty point label")
266 terms: List[Tuple[int, str]] = []
267 for chunk in label.split('+'):
268 m = _TERM_RE.match(chunk)
269 if m is None:
270 raise ValueError(f"could not parse term {chunk!r} in point {label!r}")
271 coeff_str, name = m.group(1), m.group(2).strip()
272 if not name:
273 raise ValueError(f"empty species name in point {label!r}")
274 coeff = int(coeff_str) if coeff_str else 1
275 if coeff < 1:
276 raise ValueError(
277 f"non-positive coefficient {coeff} in point {label!r}"
278 )
279 terms.append((coeff, name))
280 return terms
281
282
283 @dataclass
284 class Point:
285 """One node of a pathway: a stoichiometric sum of ConformerSets."""
286 label: str # original string, e.g. "2*A + B"
287 species: List[Tuple[int, ConformerSet]] # parsed: [(coeff, set), ...]
288
289 def thermo(
290 self,
291 T: float,
292 gconf: bool = True,
293 QH: bool = True,
294 lowest_only: bool = False,
295 ) -> ThermoVector:
296 """Total thermo at this point: Σ coeff_i × ConformerSet_i.thermo(T).
297
298 Per-species rollup precedence:
299 lowest_only=True → the species' lowest qh-G conformer only
300 else gconf=True → lowest + Boltzmann adjustment + mixing entropy
301 else → pure Boltzmann-weighted average
302 """
303 total: Optional[ThermoVector] = None
304 for coeff, cset in self.species:
305 if lowest_only:
306 term = cset.lowest_conformer() * coeff
307 elif gconf:
308 term = cset.gconf_corrected(T, QH=QH) * coeff
309 else:
310 term = cset.boltzmann_weighted(T) * coeff
311 total = term if total is None else total + term
312 if total is None:
313 raise ValueError(f"Point {self.label!r} has no species")
314 return total
315
316 @classmethod
317 def from_label(cls, label: str, species_map: dict) -> "Point":
318 """Build a Point from a label string and {name: ConformerSet} map."""
319 terms = parse_point_label(label)
320 resolved: List[Tuple[int, ConformerSet]] = []
321 missing = [name for _, name in terms if name not in species_map]
322 if missing:
323 raise KeyError(
324 f"unknown species in point {label!r}: {missing} "
325 f"(available: {sorted(species_map)})"
326 )
327 for coeff, name in terms:
328 resolved.append((coeff, species_map[name]))
329 return cls(label=label, species=resolved)
330
331
332 # ---------------------------------------------------------------------------
333 # Pathway / PESResult
334 # ---------------------------------------------------------------------------
335
336 @dataclass
337 class Pathway:
338 """Ordered points + a designated zero (defaults to points[0])."""
339 name: str
340 points: List[Point]
341 zero: Point = field(default=None) # type: ignore[assignment]
342
343 def __post_init__(self):
344 if not self.points:
345 raise ValueError(f"Pathway {self.name!r} has no points")
346 if self.zero is None:
347 self.zero = self.points[0]
348
349 def relative(
350 self, T: float, gconf: bool = True, QH: bool = True, lowest_only: bool = False,
351 ) -> List[ThermoVector]:
352 """Per-point ΔThermo relative to self.zero, in Hartree."""
353 kw = dict(gconf=gconf, QH=QH, lowest_only=lowest_only)
354 zero = self.zero.thermo(T, **kw)
355 return [p.thermo(T, **kw) - zero for p in self.points]
356
357
358 @dataclass
359 class PESOptions:
360 units: str = "kcal/mol" # 'kcal/mol' or 'kJ/mol'
361 decimals: int = 2
362 gconf: bool = True
363 QH: bool = True
364 spc_used: bool = False # True when --spc was set
365 lowest_only: bool = False # True when --lowest-only overrides gconf/Boltzmann
366
367 def to_user_units(self, hartree: Optional[float]) -> Optional[float]:
368 if hartree is None:
369 return None
370 if self.units == "kJ/mol":
371 return J_TO_AU / 1000.0 * hartree
372 return KCAL_TO_AU * hartree # default kcal/mol
373
374
375 @dataclass
376 class PESResult:
377 """Top-level container: pathways + options + temperatures."""
378 pathways: List[Pathway]
379 options: PESOptions
380 temperatures: List[float] = field(default_factory=lambda: [298.15])