| 1 |
"""Stable schema definitions for GoodVibes structured output. |
| 2 |
|
| 3 |
The shape of the JSON written by `--json` / `goodvibes.api.write_json_results` |
| 4 |
is now documented and stable. This module is the single source of truth |
| 5 |
for that schema: |
| 6 |
|
| 7 |
- `SCHEMA_VERSION` — the current shipping version. |
| 8 |
- `SCHEMA_MIN_COMPATIBLE` — readers tolerate any version ≥ this. |
| 9 |
- `validate(payload)` — runtime sanity check; raises `ValueError` |
| 10 |
with a clear message on shape/version mismatches. |
| 11 |
- TypedDicts (`Payload`, `ResultEntry`, `ThermoBlock`, ...) — give |
| 12 |
static checkers and editors completion when working with parsed |
| 13 |
payloads. |
| 14 |
|
| 15 |
The JSON file is also accepted by `--import` as a cache (skips |
| 16 |
re-parsing the underlying QC outputs); the same schema therefore plays |
| 17 |
two roles, which is item 10 of ROADMAP.md. |
| 18 |
|
| 19 |
## Version policy (v1.0+) |
| 20 |
|
| 21 |
Major bump (X.0) breaking change — fields removed or renamed, |
| 22 |
or value types changed. |
| 23 |
Minor bump (1.X) backwards-compatible addition — new fields, |
| 24 |
new optional blocks, new enum values. |
| 25 |
Patch bump (1.0.X) no-op (we don't bump for typo fixes etc.). |
| 26 |
|
| 27 |
Readers SHOULD accept any minor version ≥ their min and ignore unknown |
| 28 |
fields. Writers SHOULD emit the version they were built against. |
| 29 |
""" |
| 30 |
from __future__ import annotations |
| 31 |
|
| 32 |
from typing import Any, List, Optional |
| 33 |
|
| 34 |
try: |
| 35 |
from typing import TypedDict |
| 36 |
except ImportError: # pragma: no cover (py<3.8) |
| 37 |
from typing_extensions import TypedDict |
| 38 |
|
| 39 |
|
| 40 |
# --------------------------------------------------------------------------- |
| 41 |
# Version constants |
| 42 |
# --------------------------------------------------------------------------- |
| 43 |
|
| 44 |
#: The schema version this build of GoodVibes writes. |
| 45 |
SCHEMA_VERSION = "1.0" |
| 46 |
|
| 47 |
#: The oldest schema a reader in this build will accept. Bump only on |
| 48 |
#: a true breaking change (e.g. v2.0). |
| 49 |
SCHEMA_MIN_COMPATIBLE = "1.0" |
| 50 |
|
| 51 |
|
| 52 |
# --------------------------------------------------------------------------- |
| 53 |
# TypedDicts (for static analysis / editor support) |
| 54 |
# --------------------------------------------------------------------------- |
| 55 |
|
| 56 |
class ThermoBlock(TypedDict, total=False): |
| 57 |
"""Per-file thermochemical numbers in atomic units (Hartree, Hartree/K). |
| 58 |
|
| 59 |
Entries are `Optional[float]` — `None` when the QC output didn't |
| 60 |
expose that quantity (e.g. `sp_energy` is `None` unless `--spc` was |
| 61 |
used, frequencies are absent for SP-only outputs). |
| 62 |
""" |
| 63 |
scf_energy: Optional[float] |
| 64 |
sp_energy: Optional[float] |
| 65 |
zpe: Optional[float] |
| 66 |
zero_point_corr: Optional[float] |
| 67 |
enthalpy: Optional[float] |
| 68 |
qh_enthalpy: Optional[float] |
| 69 |
entropy: Optional[float] |
| 70 |
qh_entropy: Optional[float] |
| 71 |
gibbs_free_energy: Optional[float] |
| 72 |
qh_gibbs_free_energy: Optional[float] |
| 73 |
frequency_wn: Optional[List[float]] |
| 74 |
im_frequency_wn: Optional[List[float]] |
| 75 |
inverted_freqs: Optional[List[float]] |
| 76 |
point_group: Optional[str] |
| 77 |
symmno: Optional[int] |
| 78 |
linear_mol: Optional[bool] |
| 79 |
multiplicity: Optional[int] |
| 80 |
job_type: Optional[str] |
| 81 |
applied_freq_scale_factor: Optional[float] |
| 82 |
|
| 83 |
|
| 84 |
class ResultEntry(TypedDict, total=False): |
| 85 |
"""One per input QC file.""" |
| 86 |
file: str # absolute path |
| 87 |
name: str # display name (basename sans ext) |
| 88 |
qcdata: Optional[dict] # parsed QCData; reconstructable via io.dict_to_qcdata |
| 89 |
thermo: ThermoBlock # per-file thermochemistry |
| 90 |
media_conc: Optional[float] # neat-solvent concentration (mol/L) when --media matched |
| 91 |
boltzmann_factor: Optional[float] |
| 92 |
|
| 93 |
|
| 94 |
class SelectivityResult(TypedDict, total=False): |
| 95 |
"""One per temperature inside `selectivity`/`selectivity_lowest`.""" |
| 96 |
temperature: float |
| 97 |
populations: dict # {label: probability}, sums to 1.0 |
| 98 |
raw_boltzmann: dict # {label: un-normalised exp(-G/RT) sum} |
| 99 |
preferred: str # max-population label |
| 100 |
ee: Optional[float] # 2-label only; in % |
| 101 |
ddG: Optional[float] # 2-label only; in Hartree |
| 102 |
files_per_label: dict # {label: list[file path]} |
| 103 |
|
| 104 |
|
| 105 |
class SelectivityBlock(TypedDict): |
| 106 |
labels: List[str] # ordered species names |
| 107 |
key: str # 'gibbs' | 'energy' |
| 108 |
results: List[SelectivityResult] |
| 109 |
|
| 110 |
|
| 111 |
class PESPoint(TypedDict, total=False): |
| 112 |
label: str # original label, e.g. "2*A + B" |
| 113 |
species: List[dict] # [{coefficient, name, files}] |
| 114 |
relative: dict # {scf, zpe, h, qh_h, ts, qh_ts, g, qh_g, spc} |
| 115 |
|
| 116 |
|
| 117 |
class PESPathway(TypedDict, total=False): |
| 118 |
name: str |
| 119 |
temperature: float |
| 120 |
units: str # 'kcal/mol' or 'kJ/mol' |
| 121 |
zero_label: str |
| 122 |
points: List[PESPoint] |
| 123 |
|
| 124 |
|
| 125 |
class PESBlock(TypedDict): |
| 126 |
pathways: List[PESPathway] |
| 127 |
|
| 128 |
|
| 129 |
class Payload(TypedDict, total=False): |
| 130 |
"""The top-level JSON document GoodVibes writes.""" |
| 131 |
schema_version: str |
| 132 |
goodvibes_version: str |
| 133 |
generated_at: str # ISO 8601 UTC |
| 134 |
options: dict |
| 135 |
results: List[ResultEntry] |
| 136 |
selectivity: SelectivityBlock # optional |
| 137 |
selectivity_lowest: SelectivityBlock # optional |
| 138 |
pes: PESBlock # optional |
| 139 |
|
| 140 |
|
| 141 |
# --------------------------------------------------------------------------- |
| 142 |
# Runtime validation |
| 143 |
# --------------------------------------------------------------------------- |
| 144 |
|
| 145 |
def _parse_version(s: str) -> tuple: |
| 146 |
"""Parse '1.0' → (1, 0); '1.2.3' → (1, 2, 3). Tolerant of trailing junk.""" |
| 147 |
parts = [] |
| 148 |
for chunk in s.split('.'): |
| 149 |
try: |
| 150 |
parts.append(int(chunk)) |
| 151 |
except ValueError: |
| 152 |
break |
| 153 |
return tuple(parts) if parts else (0,) |
| 154 |
|
| 155 |
|
| 156 |
def validate(payload: Any) -> None: |
| 157 |
"""Light runtime sanity check on a loaded payload. |
| 158 |
|
| 159 |
Verifies the document has a schema_version that this build can read |
| 160 |
and that the required top-level fields are present. Does NOT |
| 161 |
deeply type-check every field — that's the consumer's responsibility |
| 162 |
via the TypedDicts above. |
| 163 |
|
| 164 |
Raises: |
| 165 |
ValueError: with a one-line, actionable message on any failure. |
| 166 |
""" |
| 167 |
if not isinstance(payload, dict): |
| 168 |
raise ValueError( |
| 169 |
f"GoodVibes payload must be a JSON object, got {type(payload).__name__}" |
| 170 |
) |
| 171 |
if 'schema_version' not in payload: |
| 172 |
raise ValueError( |
| 173 |
"GoodVibes payload missing required field 'schema_version'. " |
| 174 |
"Pre-v1.0 files (schema_version 0.x) are not accepted as input — " |
| 175 |
"regenerate with a v1.0+ build." |
| 176 |
) |
| 177 |
pv = _parse_version(payload['schema_version']) |
| 178 |
minv = _parse_version(SCHEMA_MIN_COMPATIBLE) |
| 179 |
cur = _parse_version(SCHEMA_VERSION) |
| 180 |
if pv < minv: |
| 181 |
raise ValueError( |
| 182 |
f"GoodVibes payload has schema_version={payload['schema_version']!r}; " |
| 183 |
f"this build accepts {SCHEMA_MIN_COMPATIBLE} or newer. " |
| 184 |
f"Regenerate the file with a recent GoodVibes." |
| 185 |
) |
| 186 |
if pv[0] > cur[0]: |
| 187 |
raise ValueError( |
| 188 |
f"GoodVibes payload has schema_version={payload['schema_version']!r}, " |
| 189 |
f"newer than this build understands ({SCHEMA_VERSION}). Upgrade GoodVibes." |
| 190 |
) |
| 191 |
for required in ('goodvibes_version', 'results'): |
| 192 |
if required not in payload: |
| 193 |
raise ValueError( |
| 194 |
f"GoodVibes payload missing required field {required!r}" |
| 195 |
) |
| 196 |
if not isinstance(payload['results'], list): |
| 197 |
raise ValueError( |
| 198 |
f"GoodVibes payload field 'results' must be a list, " |
| 199 |
f"got {type(payload['results']).__name__}" |
| 200 |
) |