| 1 |
"""Output formatting and printing functions for GoodVibes.""" |
| 2 |
import json |
| 3 |
import logging |
| 4 |
import math |
| 5 |
import os.path |
| 6 |
import sys |
| 7 |
from datetime import datetime, timedelta, timezone |
| 8 |
|
| 9 |
from .utils import display_name, get_console_stdout, get_console_dat |
| 10 |
from .selectivity import get_selectivity |
| 11 |
from .constants import GAS_CONSTANT, ATMOS, J_TO_AU, KCAL_TO_AU, __version__ |
| 12 |
from .io import qcdata_to_dict |
| 13 |
|
| 14 |
from .pes import get_pes, graph_reaction_profile |
| 15 |
from .thermo import calc_bbe |
| 16 |
from .media import solvents |
| 17 |
|
| 18 |
|
| 19 |
# -------------------------------------------------------------------------- |
| 20 |
# Structured (JSON) output |
| 21 |
# -------------------------------------------------------------------------- |
| 22 |
# Schema is now stable from v1.0 onward — see goodvibes.schema for the |
| 23 |
# single source of truth (TypedDicts, version constants, validator). |
| 24 |
# Re-exported here as a module attribute for back-compat with anything |
| 25 |
# that imports `JSON_SCHEMA_VERSION` directly. |
| 26 |
from .schema import SCHEMA_VERSION as JSON_SCHEMA_VERSION |
| 27 |
|
| 28 |
# Run-level option keys that should appear in the JSON header, mapped from |
| 29 |
# their Namespace attribute names. Any options not in this list are dropped |
| 30 |
# (avoids leaking nuisance flags like --output, --custom_ext, etc.). |
| 31 |
_JSON_OPTION_KEYS = ( |
| 32 |
'temperature', 'temperature_interval', 'conc', |
| 33 |
'QS', 'QH', 'freq_cutoff', 'S_freq_cutoff', 'H_freq_cutoff', |
| 34 |
'freq_scale_factor', 'media', 'freespace', 'spc', |
| 35 |
'invert', 'symm', 'duplicate', 'boltz', 'inertia', |
| 36 |
'mm_freq_scale_factor', |
| 37 |
) |
| 38 |
|
| 39 |
# calc_bbe attributes whose names match exactly between the object and the |
| 40 |
# JSON output. Optional — None when calc_bbe didn't compute them (SP-only). |
| 41 |
_THERMO_FIELDS = ( |
| 42 |
'scf_energy', 'sp_energy', 'zpe', 'zero_point_corr', |
| 43 |
'enthalpy', 'qh_enthalpy', |
| 44 |
'entropy', 'qh_entropy', |
| 45 |
'gibbs_free_energy', 'qh_gibbs_free_energy', |
| 46 |
'frequency_wn', 'im_frequency_wn', 'inverted_freqs', |
| 47 |
'point_group', 'symmno', 'linear_mol', |
| 48 |
'multiplicity', 'job_type', 'applied_freq_scale_factor', |
| 49 |
) |
| 50 |
|
| 51 |
|
| 52 |
def _options_to_json(options): |
| 53 |
"""Project the argparse Namespace down to the JSON-relevant subset.""" |
| 54 |
out = {} |
| 55 |
for key in _JSON_OPTION_KEYS: |
| 56 |
out[key] = getattr(options, key, None) |
| 57 |
return out |
| 58 |
|
| 59 |
|
| 60 |
def _bbe_to_json(bbe, file_path, media_conc=None, boltz_factor=None): |
| 61 |
"""Serialize one calc_bbe instance + its underlying QCData to a dict.""" |
| 62 |
entry = { |
| 63 |
'file': os.path.abspath(file_path), |
| 64 |
'name': display_name(file_path), |
| 65 |
} |
| 66 |
qcdata = getattr(bbe, 'xyz', None) |
| 67 |
if qcdata is not None: |
| 68 |
d = qcdata_to_dict(qcdata) |
| 69 |
d.pop('_cache_version', None) |
| 70 |
entry['qcdata'] = d |
| 71 |
thermo = {} |
| 72 |
for field_name in _THERMO_FIELDS: |
| 73 |
thermo[field_name] = getattr(bbe, field_name, None) |
| 74 |
entry['thermo'] = thermo |
| 75 |
entry['media_conc'] = media_conc |
| 76 |
entry['boltzmann_factor'] = boltz_factor |
| 77 |
return entry |
| 78 |
|
| 79 |
|
| 80 |
def print_selectivity_results(results_by_method): |
| 81 |
"""Print one or more selectivity tables, one block per method. |
| 82 |
|
| 83 |
Parameters: |
| 84 |
results_by_method (dict[str, list[SelectivityResult]]): ordered |
| 85 |
mapping of method name (e.g. "Boltzmann-averaged", |
| 86 |
"Lowest conformer only") to its list of SelectivityResults. |
| 87 |
Single-temperature mode passes a one-element list per method; |
| 88 |
scan mode passes one per temperature. |
| 89 |
""" |
| 90 |
if not results_by_method or Table is None: |
| 91 |
return |
| 92 |
for method, results in results_by_method.items(): |
| 93 |
if not results: |
| 94 |
continue |
| 95 |
if len(results) == 1: |
| 96 |
_print_selectivity_single(results[0], method=method) |
| 97 |
else: |
| 98 |
_print_selectivity_scan(results, method=method) |
| 99 |
|
| 100 |
|
| 101 |
def _format_ratio(populations, labels, scale=100): |
| 102 |
"""Format populations as integer-percent ratio string ('60:40' or '40:30:20:10').""" |
| 103 |
rounded = [round(populations[label] * scale) for label in labels] |
| 104 |
return ':'.join(str(v) for v in rounded) |
| 105 |
|
| 106 |
|
| 107 |
def _print_selectivity_single(result, method=""): |
| 108 |
"""Per-species table + summary footer for a single SelectivityResult.""" |
| 109 |
HA_TO_KCAL = 627.509541 |
| 110 |
suffix = f", {method}" if method else "" |
| 111 |
log.info(f"\n Selectivity{suffix} ({result.key}, T = {result.temperature:.2f} K)") |
| 112 |
|
| 113 |
# Per-species table: leading marker column (★ for major) | Species | |
| 114 |
# Files | Population (%) | ΔΔG (kcal/mol, vs. major). |
| 115 |
table = Table( |
| 116 |
box=rich_box.SIMPLE_HEAD, |
| 117 |
show_header=True, |
| 118 |
show_edge=False, |
| 119 |
pad_edge=False, |
| 120 |
highlight=False, |
| 121 |
header_style="", |
| 122 |
) |
| 123 |
table.add_column("", width=3) # marker col, mirrors print_results |
| 124 |
table.add_column("Species", no_wrap=True) |
| 125 |
table.add_column("Files", justify="right") |
| 126 |
table.add_column("Population (%)", justify="right") |
| 127 |
table.add_column("ΔΔG (kcal/mol)", justify="right") |
| 128 |
|
| 129 |
# ΔΔG = -RT ln(p / p_max); the major species is 0 by construction, |
| 130 |
# others are positive (less stable). Skip when p == 0 (printed as "—"). |
| 131 |
ref_pop = max(result.populations.values()) |
| 132 |
rt_kcal = 8.3144621 * result.temperature / 1000.0 / 4.184 # kcal/mol |
| 133 |
for label in result.labels: |
| 134 |
p = result.populations[label] |
| 135 |
n_files = len(result.files_per_label.get(label, [])) |
| 136 |
marker = "★" if label == result.preferred else " " |
| 137 |
if p > 0: |
| 138 |
dG = -rt_kcal * math.log(p / ref_pop) |
| 139 |
# The major species's dG can be -0.0 from float math; force +0.000. |
| 140 |
if abs(dG) < 1e-9: |
| 141 |
dG = 0.0 |
| 142 |
dG_str = f"{dG:.3f}" |
| 143 |
else: |
| 144 |
dG_str = "—" |
| 145 |
table.add_row(marker, label, str(n_files), f"{p * 100:.2f}", dG_str) |
| 146 |
|
| 147 |
_print_rich_table(table) |
| 148 |
|
| 149 |
# Summary line: ratio (always); excess + ΔΔG for N=2. |
| 150 |
n = len(result.labels) |
| 151 |
ratio_str = _format_ratio(result.populations, result.labels) |
| 152 |
pieces = [f"Ratio {':'.join(result.labels)} = {ratio_str}"] |
| 153 |
pieces.append(f"Major: {result.preferred}") |
| 154 |
if n == 2 and result.ee is not None: |
| 155 |
pieces.append(f"excess = {result.ee:.2f}%") |
| 156 |
if n == 2 and result.ddG is not None: |
| 157 |
pieces.append(f"ΔΔG = {result.ddG * HA_TO_KCAL:.2f} kcal/mol") |
| 158 |
log.info("\n " + " ".join(pieces) + "\n") |
| 159 |
|
| 160 |
|
| 161 |
def _print_selectivity_scan(results, method=""): |
| 162 |
"""One row per temperature: excess/ΔΔG for N=2, populations only for N>2.""" |
| 163 |
HA_TO_KCAL = 627.509541 |
| 164 |
labels = results[0].labels |
| 165 |
n = len(labels) |
| 166 |
suffix = f", {method}" if method else "" |
| 167 |
log.info(f"\n Selectivity scan{suffix} ({results[0].key})") |
| 168 |
|
| 169 |
table = Table( |
| 170 |
box=rich_box.SIMPLE_HEAD, |
| 171 |
show_header=True, |
| 172 |
show_edge=False, |
| 173 |
pad_edge=False, |
| 174 |
highlight=False, |
| 175 |
header_style="", |
| 176 |
) |
| 177 |
table.add_column("", width=3) # leading indent, mirrors single-T |
| 178 |
table.add_column("T (K)", justify="right") |
| 179 |
for label in labels: |
| 180 |
table.add_column(f"{label} (%)", justify="right") |
| 181 |
if n == 2: |
| 182 |
table.add_column("excess (%)", justify="right") |
| 183 |
table.add_column("ΔΔG (kcal/mol)", justify="right") |
| 184 |
table.add_column("Major", justify="center") |
| 185 |
|
| 186 |
for r in results: |
| 187 |
row = ["", f"{r.temperature:g}"] |
| 188 |
for label in labels: |
| 189 |
row.append(f"{r.populations[label] * 100:.2f}") |
| 190 |
if n == 2: |
| 191 |
row.append(f"{r.ee:.2f}" if r.ee is not None else "—") |
| 192 |
ddG_kc = r.ddG * HA_TO_KCAL if r.ddG is not None else None |
| 193 |
row.append(f"{ddG_kc:.2f}" if ddG_kc is not None else "—") |
| 194 |
row.append(r.preferred) |
| 195 |
table.add_row(*row) |
| 196 |
|
| 197 |
_print_rich_table(table) |
| 198 |
log.info("\n") |
| 199 |
|
| 200 |
|
| 201 |
def _selectivity_to_json(selectivity_results): |
| 202 |
"""Serialize a list of SelectivityResult instances for the JSON payload. |
| 203 |
|
| 204 |
For N=2 each entry includes ee + ddG; for N>2 those fields are null |
| 205 |
and consumers derive any ratios they need from `populations`. |
| 206 |
""" |
| 207 |
if not selectivity_results: |
| 208 |
return None |
| 209 |
first = selectivity_results[0] |
| 210 |
return { |
| 211 |
'labels': list(first.labels), |
| 212 |
'key': first.key, |
| 213 |
'results': [ |
| 214 |
{ |
| 215 |
'temperature': r.temperature, |
| 216 |
'populations': dict(r.populations), |
| 217 |
'raw_boltzmann': dict(r.raw_boltzmann), |
| 218 |
'preferred': r.preferred, |
| 219 |
'ee': r.ee, |
| 220 |
'ddG': r.ddG, |
| 221 |
'files_per_label': {k: list(v) for k, v in r.files_per_label.items()}, |
| 222 |
} |
| 223 |
for r in selectivity_results |
| 224 |
], |
| 225 |
} |
| 226 |
|
| 227 |
|
| 228 |
def _pes_to_json(result, temperature): |
| 229 |
"""Serialize a PESResult into the v0.4 JSON `pes` block. |
| 230 |
|
| 231 |
Per-pathway, per-point: the original label, the species breakdown |
| 232 |
(with coefficient and resolved files), and the relative thermo bundle |
| 233 |
(Hartree internally, converted to user units in the `units` field). |
| 234 |
""" |
| 235 |
if result is None or not result.pathways: |
| 236 |
return None |
| 237 |
pathways_out = [] |
| 238 |
units_factor = result.options.to_user_units(1.0) # Hartree → kcal/mol or kJ/mol |
| 239 |
lowest_only = getattr(result.options, 'lowest_only', False) |
| 240 |
rollup_kw = dict(gconf=result.options.gconf, QH=result.options.QH, |
| 241 |
lowest_only=lowest_only) |
| 242 |
for pathway in result.pathways: |
| 243 |
zero_th = pathway.zero.thermo(temperature, **rollup_kw) |
| 244 |
points_out = [] |
| 245 |
for point in pathway.points: |
| 246 |
pt_th = point.thermo(temperature, **rollup_kw) |
| 247 |
rel = pt_th - zero_th |
| 248 |
points_out.append({ |
| 249 |
'label': point.label, |
| 250 |
'species': [ |
| 251 |
{ |
| 252 |
'coefficient': coeff, |
| 253 |
'name': cset.name, |
| 254 |
'files': list(cset.files), |
| 255 |
} |
| 256 |
for coeff, cset in point.species |
| 257 |
], |
| 258 |
'relative': { |
| 259 |
'scf': rel.scf_energy * units_factor, |
| 260 |
'zpe': rel.zpe * units_factor, |
| 261 |
'h': rel.enthalpy * units_factor, |
| 262 |
'qh_h': rel.qh_enthalpy * units_factor, |
| 263 |
'ts': temperature * rel.entropy * units_factor, |
| 264 |
'qh_ts': temperature * rel.qh_entropy * units_factor, |
| 265 |
'g': rel.gibbs * units_factor, |
| 266 |
'qh_g': rel.qh_gibbs * units_factor, |
| 267 |
'spc': (rel.sp_energy * units_factor) if rel.sp_energy is not None else None, |
| 268 |
}, |
| 269 |
}) |
| 270 |
pathways_out.append({ |
| 271 |
'name': pathway.name, |
| 272 |
'temperature': temperature, |
| 273 |
'units': result.options.units, |
| 274 |
'zero_label': pathway.zero.label, |
| 275 |
'points': points_out, |
| 276 |
}) |
| 277 |
return {'pathways': pathways_out} |
| 278 |
|
| 279 |
|
| 280 |
def write_json_results(thermo_data, options, path, media_conc_per_file=None, |
| 281 |
boltz_facs=None, selectivity_results=None, |
| 282 |
selectivity_lowest_results=None, |
| 283 |
pes_result=None): |
| 284 |
"""Write structured run results to *path* as JSON. |
| 285 |
|
| 286 |
Captures every parsed QCData field plus computed thermo per file, the |
| 287 |
schema version, the goodvibes version, and the run options. Schema is |
| 288 |
preview/v0.x — fields may shift before v5.0 stabilizes it. |
| 289 |
|
| 290 |
Parameters: |
| 291 |
thermo_data (dict): file path -> calc_bbe. |
| 292 |
options (Namespace): the parsed CLI options. |
| 293 |
path (str): output JSON file path. |
| 294 |
media_conc_per_file (dict, optional): file path -> neat solvent |
| 295 |
concentration applied to that specific file (None for files |
| 296 |
where --media didn't match). |
| 297 |
boltz_facs (dict, optional): file path -> Boltzmann factor. |
| 298 |
selectivity_results (list[SelectivityResult], optional): one entry |
| 299 |
per temperature; included as a top-level "selectivity" block. |
| 300 |
""" |
| 301 |
media_conc_per_file = media_conc_per_file or {} |
| 302 |
boltz_facs = boltz_facs or {} |
| 303 |
payload = { |
| 304 |
'schema_version': JSON_SCHEMA_VERSION, |
| 305 |
'goodvibes_version': __version__, |
| 306 |
'generated_at': datetime.now(timezone.utc).isoformat(timespec='seconds'), |
| 307 |
'options': _options_to_json(options), |
| 308 |
'results': [ |
| 309 |
_bbe_to_json( |
| 310 |
bbe, file, |
| 311 |
media_conc=media_conc_per_file.get(file), |
| 312 |
boltz_factor=boltz_facs.get(file), |
| 313 |
) |
| 314 |
for file, bbe in thermo_data.items() |
| 315 |
], |
| 316 |
} |
| 317 |
sel_block = _selectivity_to_json(selectivity_results) |
| 318 |
if sel_block is not None: |
| 319 |
payload['selectivity'] = sel_block |
| 320 |
sel_low_block = _selectivity_to_json(selectivity_lowest_results) |
| 321 |
if sel_low_block is not None: |
| 322 |
payload['selectivity_lowest'] = sel_low_block |
| 323 |
pes_block = _pes_to_json(pes_result, getattr(options, 'temperature', 298.15)) |
| 324 |
if pes_block is not None: |
| 325 |
payload['pes'] = pes_block |
| 326 |
# default=str catches anything stringifiable that json doesn't natively |
| 327 |
# know about (e.g., the '!' sentinel value calc_bbe uses for failed SPC). |
| 328 |
with open(path, 'w', encoding='utf-8') as f: |
| 329 |
json.dump(payload, f, indent=2, default=str) |
| 330 |
log.info(f"\n ✔ Structured results written to {path} (schema v{JSON_SCHEMA_VERSION}).") |
| 331 |
|
| 332 |
try: |
| 333 |
from rich.table import Table |
| 334 |
from rich import box as rich_box |
| 335 |
except ImportError: |
| 336 |
Table = None |
| 337 |
rich_box = None |
| 338 |
|
| 339 |
log = logging.getLogger('goodvibes') |
| 340 |
|
| 341 |
|
| 342 |
def _print_rich_table(table: "Table") -> None: |
| 343 |
"""Print a Rich Table to both stdout and .dat file consoles. |
| 344 |
|
| 345 |
Renders to a buffer per console, strips Rich's trailing blank padding |
| 346 |
row (`box.SIMPLE` always adds one), and writes directly so the |
| 347 |
separator that follows lands immediately under the data. |
| 348 |
""" |
| 349 |
if Table is None: |
| 350 |
return |
| 351 |
import re |
| 352 |
from io import StringIO |
| 353 |
from rich.console import Console |
| 354 |
ANSI_RE = re.compile(r"\x1b\[[0-9;]*[mGK]") |
| 355 |
|
| 356 |
def _render(console): |
| 357 |
buf = StringIO() |
| 358 |
Console( |
| 359 |
file=buf, |
| 360 |
force_terminal=console.is_terminal, |
| 361 |
color_system=console.color_system, |
| 362 |
width=console.width, |
| 363 |
).print(table) |
| 364 |
text = buf.getvalue().rstrip("\n") |
| 365 |
lines = text.split("\n") |
| 366 |
# Drop trailing visually-blank lines (Rich SIMPLE-box padding). |
| 367 |
while lines and not ANSI_RE.sub("", lines[-1]).strip(): |
| 368 |
lines.pop() |
| 369 |
# Leading "\n\n" gives exactly one blank line before the table: |
| 370 |
# the logger uses terminator='' so the prior message has no trailing |
| 371 |
# \n; the first \n closes that line, the second is the blank line. |
| 372 |
return "\n\n" + "\n".join(lines) + "\n" |
| 373 |
|
| 374 |
for console in (get_console_stdout(), get_console_dat()): |
| 375 |
console.file.write(_render(console)) |
| 376 |
console.file.flush() |
| 377 |
|
| 378 |
# Measure visible width via a plain render (no escape codes). |
| 379 |
stdout_console = get_console_stdout() |
| 380 |
plain_buf = StringIO() |
| 381 |
Console(file=plain_buf, color_system=None, width=stdout_console.width).print(table) |
| 382 |
line_width = max( |
| 383 |
(len(line.rstrip()) for line in plain_buf.getvalue().split("\n")), |
| 384 |
default=0, |
| 385 |
) |
| 386 |
log.info("─" * line_width) |
| 387 |
log.info("\n") |
| 388 |
|
| 389 |
|
| 390 |
# --------------------------------------------------------------------------- |
| 391 |
# PES tables (v4.2 Rich renderer; see Sub-plan B in ROADMAP.md) |
| 392 |
# --------------------------------------------------------------------------- |
| 393 |
|
| 394 |
def _pes_column_spec(spc_used: bool, QH: bool): |
| 395 |
"""Column headers + which ThermoVector field each one reads. |
| 396 |
|
| 397 |
Returns a list of (header, field, scale_by_T) tuples. `field` is the |
| 398 |
attribute on a ThermoVector; `scale_by_T` indicates the column is T·S |
| 399 |
rather than raw S/H/G (i.e. needs an extra multiplication at render). |
| 400 |
Without --spc the energy/H/G columns use their plain names; with |
| 401 |
--spc, H and G are SPC-substituted in calc_bbe so the labels are |
| 402 |
annotated `_SPC` to signal that to the reader (the values themselves |
| 403 |
are taken from the same fields). |
| 404 |
""" |
| 405 |
cols = [] |
| 406 |
if spc_used: |
| 407 |
cols.append(("ΔE_SPC", "sp_energy", False)) |
| 408 |
cols.append(("ΔE", "scf_energy", False)) |
| 409 |
cols.append(("ΔZPE", "zpe", False)) |
| 410 |
h_label = "ΔH_SPC" if spc_used else "ΔH" |
| 411 |
cols.append((h_label, "enthalpy", False)) |
| 412 |
if QH: |
| 413 |
qh_h_label = "Δqh-H_SPC" if spc_used else "Δqh-H" |
| 414 |
cols.append((qh_h_label, "qh_enthalpy", False)) |
| 415 |
cols.append(("T·ΔS", "entropy", True)) |
| 416 |
cols.append(("T·Δqh-S", "qh_entropy", True)) |
| 417 |
g_label = "ΔG(T)_SPC" if spc_used else "ΔG(T)" |
| 418 |
cols.append((g_label, "gibbs", False)) |
| 419 |
qhg_label = "Δqh-G(T)_SPC" if spc_used else "Δqh-G(T)" |
| 420 |
cols.append((qhg_label, "qh_gibbs", False)) |
| 421 |
return cols |
| 422 |
|
| 423 |
|
| 424 |
def _build_pes_table(pathway, options, temperature, pes_options) -> "Table": |
| 425 |
"""Build a Rich Table for one Pathway at one temperature.""" |
| 426 |
spc_used = bool(getattr(options, 'spc', None)) |
| 427 |
cols = _pes_column_spec(spc_used, options.QH) |
| 428 |
# Concentration: when --conc isn't set the default is gas-phase 1 atm, |
| 429 |
# so report "p = 1 atm" rather than its numeric P/RT equivalent. |
| 430 |
user_conc = getattr(options, 'conc', None) |
| 431 |
state_str = f"c = {user_conc:.4g} mol/L" if user_conc else "p = 1 atm" |
| 432 |
if getattr(pes_options, 'lowest_only', False): |
| 433 |
mode_str = " — lowest conformer per species" |
| 434 |
elif not pes_options.gconf: |
| 435 |
mode_str = " — Boltzmann-averaged (no gconf)" |
| 436 |
else: |
| 437 |
mode_str = "" |
| 438 |
title = ( |
| 439 |
f"RXN: {pathway.name} ({pes_options.units}) " |
| 440 |
f"at T = {temperature:g} K, {state_str}{mode_str}" |
| 441 |
) |
| 442 |
table = Table(title=title, box=rich_box.SIMPLE, header_style="bold") |
| 443 |
table.add_column("", justify="left", no_wrap=True) # leading marker (matches selectivity tables) |
| 444 |
table.add_column("Species", justify="left", no_wrap=True) |
| 445 |
for header, _, _ in cols: |
| 446 |
table.add_column(header, justify="right") |
| 447 |
|
| 448 |
units_factor = pes_options.to_user_units(1.0) |
| 449 |
fmt = f"{{:.{pes_options.decimals}f}}" |
| 450 |
rollup_kw = dict( |
| 451 |
gconf=pes_options.gconf, |
| 452 |
QH=pes_options.QH, |
| 453 |
lowest_only=getattr(pes_options, 'lowest_only', False), |
| 454 |
) |
| 455 |
zero_th = pathway.zero.thermo(temperature, **rollup_kw) |
| 456 |
for point in pathway.points: |
| 457 |
pt_th = point.thermo(temperature, **rollup_kw) |
| 458 |
rel = pt_th - zero_th |
| 459 |
row = ["", point.label] |
| 460 |
for _header, field, scale_by_T in cols: |
| 461 |
value = getattr(rel, field) |
| 462 |
if value is None: |
| 463 |
row.append("—") |
| 464 |
continue |
| 465 |
if scale_by_T: |
| 466 |
value = temperature * value |
| 467 |
row.append(fmt.format(value * units_factor)) |
| 468 |
table.add_row(*row) |
| 469 |
return table |
| 470 |
|
| 471 |
|
| 472 |
def print_pes_tables(result, options, temperature=None): |
| 473 |
"""Render PES results as Rich tables (one per pathway). |
| 474 |
|
| 475 |
Parameters: |
| 476 |
result: PESResult instance (from goodvibes.pes_loader.load_pes). |
| 477 |
options: argparse Namespace; reads .QH, .spc, .gconf. |
| 478 |
temperature: K. Defaults to result.temperatures[0]. |
| 479 |
""" |
| 480 |
if Table is None: # pragma: no cover |
| 481 |
log.warning("Rich not installed; falling back to legacy text PES output.") |
| 482 |
return |
| 483 |
if temperature is None: |
| 484 |
temperature = result.temperatures[0] if result.temperatures else 298.15 |
| 485 |
# Sync run-time flags into the model's options so the column spec and |
| 486 |
# rollup math agree with what the user requested on the CLI. |
| 487 |
result.options.gconf = bool(getattr(options, 'gconf', True)) |
| 488 |
result.options.QH = bool(getattr(options, 'QH', False)) |
| 489 |
result.options.spc_used = bool(getattr(options, 'spc', None)) |
| 490 |
result.options.lowest_only = bool(getattr(options, 'lowest_only', False)) |
| 491 |
if result.options.lowest_only: |
| 492 |
log.info("\n Lowest conformer per species (no Boltzmann averaging, no gconf)") |
| 493 |
elif options.gconf: |
| 494 |
log.info("\n Gconf correction applied to relative values") |
| 495 |
for pathway in result.pathways: |
| 496 |
table = _build_pes_table(pathway, options, temperature, result.options) |
| 497 |
_print_rich_table(table) |
| 498 |
|
| 499 |
|
| 500 |
def print_cpu_time(thermo_data, exclude=None): |
| 501 |
""" |
| 502 |
Aggregate and log total CPU time across the provided thermochemistry results. |
| 503 |
|
| 504 |
Parameters: |
| 505 |
thermo_data (dict): Mapping of file path to calc_bbe-like objects whose `cpu` and optional `sp_cpu` attributes contribute to the total. |
| 506 |
exclude (str, optional): Glob pattern; files matching this pattern are omitted from the summed total. |
| 507 |
""" |
| 508 |
from fnmatch import fnmatch |
| 509 |
|
| 510 |
def _to_timedelta(cpu): |
| 511 |
d, h, m, s, ms = cpu |
| 512 |
return timedelta(days=d, hours=h, minutes=m, seconds=s, microseconds=ms * 1000) |
| 513 |
|
| 514 |
total = timedelta() |
| 515 |
has_orca_scaled = False |
| 516 |
for file, bbe in thermo_data.items(): |
| 517 |
if exclude and fnmatch(file, exclude): |
| 518 |
continue |
| 519 |
if hasattr(bbe, "cpu") and bbe.cpu is not None: |
| 520 |
total += _to_timedelta(bbe.cpu) |
| 521 |
if hasattr(bbe, "sp_cpu") and bbe.sp_cpu is not None: |
| 522 |
total += _to_timedelta(bbe.sp_cpu) |
| 523 |
# Detect ORCA wall-time-scaled-by-nprocs entries via QCData. |
| 524 |
qc = getattr(bbe, "xyz", None) |
| 525 |
if qc is not None and getattr(qc, "program", None) == "Orca" and getattr(qc, "nprocs", 1) > 1: |
| 526 |
has_orca_scaled = True |
| 527 |
total_secs = int(total.total_seconds()) |
| 528 |
days, rem = divmod(total_secs, 86400) |
| 529 |
hrs, rem = divmod(rem, 3600) |
| 530 |
mins, secs = divmod(rem, 60) |
| 531 |
log.info(f' {"TOTAL CPU":<13} {days:>2} {"days":>4} ' |
| 532 |
f'{hrs:>2} {"hrs":>3} {mins:>2} {"mins":>4} ' |
| 533 |
f'{secs:>2} {"secs":>4}') |
| 534 |
if has_orca_scaled: |
| 535 |
log.info("\n † ORCA wall-time × nprocs counted as CPU time (ORCA does not " |
| 536 |
"report a summed CPU time).\n") |
| 537 |
else: |
| 538 |
log.info("\n") |
| 539 |
|
| 540 |
|
| 541 |
def _build_results_table(options) -> "Table": |
| 542 |
""" |
| 543 |
Create a Rich Table configured for thermochemistry result columns based on the provided options. |
| 544 |
|
| 545 |
Columns included depend on the options flags: QH, spc, boltz, symm/pg, and imag_freq. Column widths and numeric precision are derived from options.dp when present. |
| 546 |
|
| 547 |
Parameters: |
| 548 |
options: An object with attributes used to determine the table layout (commonly includes |
| 549 |
`dp`, `QH`, `spc`, `boltz`, `symm`, `pg`, and `imag_freq`). |
| 550 |
|
| 551 |
Returns: |
| 552 |
table (Table | None): A configured rich.table.Table ready for rows, or `None` if Rich is not available. |
| 553 |
""" |
| 554 |
if Table is None: |
| 555 |
return None |
| 556 |
|
| 557 |
dp = getattr(options, 'dp', 6) |
| 558 |
dw = dp - 6 |
| 559 |
ew = 11 + dw # wide numeric column (energies) |
| 560 |
sw = 2 + dp # small column (ZPE, T.S, T.qh-S - always 0.xxx) |
| 561 |
|
| 562 |
table = Table( |
| 563 |
box=rich_box.SIMPLE_HEAD, |
| 564 |
show_header=True, |
| 565 |
show_edge=False, |
| 566 |
pad_edge=False, |
| 567 |
highlight=False, |
| 568 |
header_style="", # Disable bold header styling |
| 569 |
) |
| 570 |
|
| 571 |
# Status column (o/x markers) |
| 572 |
table.add_column("", width=3) |
| 573 |
table.add_column("Structure", no_wrap=True) |
| 574 |
|
| 575 |
if options.spc is not None: |
| 576 |
table.add_column("E_SPC", min_width=ew, justify="right") |
| 577 |
table.add_column("E", min_width=ew, justify="right") |
| 578 |
table.add_column("ZPE", min_width=sw, justify="right") |
| 579 |
|
| 580 |
h_col = "H_SPC" if options.spc is not None else "H" |
| 581 |
if options.QH: |
| 582 |
table.add_column(h_col, min_width=ew, justify="right") |
| 583 |
table.add_column("qh-H", min_width=ew, justify="right") |
| 584 |
else: |
| 585 |
table.add_column(h_col, min_width=ew, justify="right") |
| 586 |
|
| 587 |
table.add_column("T.S", min_width=sw, justify="right") |
| 588 |
table.add_column("T.qh-S", min_width=sw, justify="right") |
| 589 |
|
| 590 |
if options.spc is not None: |
| 591 |
table.add_column("G(T)_SPC", min_width=ew, justify="right") |
| 592 |
table.add_column("qh-G(T)_SPC", min_width=ew, justify="right") |
| 593 |
else: |
| 594 |
table.add_column("G(T)", min_width=ew, justify="right") |
| 595 |
table.add_column("qh-G(T)", min_width=ew, justify="right") |
| 596 |
|
| 597 |
if options.boltz: |
| 598 |
table.add_column("Boltz", min_width=7, justify="right") |
| 599 |
if options.symm or options.pg: |
| 600 |
table.add_column("Point Group", min_width=13, justify="right") |
| 601 |
if options.imag_freq is True: |
| 602 |
table.add_column("im freq", min_width=8, justify="right") |
| 603 |
if _selectivity_active(options): |
| 604 |
table.add_column("Grel (kcal/mol)", min_width=8, justify="right") |
| 605 |
|
| 606 |
return table |
| 607 |
|
| 608 |
|
| 609 |
def _selectivity_active(options): |
| 610 |
"""True when any selectivity flag is on (--label / --selectivity / --ee).""" |
| 611 |
return bool(getattr(options, 'labels', None) |
| 612 |
or getattr(options, 'selectivity_spec', None) |
| 613 |
or getattr(options, 'ee', None)) |
| 614 |
|
| 615 |
|
| 616 |
def print_results(thermo_data, options, media_conc=None, |
| 617 |
dup_list=None, boltz_facs=None): |
| 618 |
"""Print the single-temperature thermochemistry results table. |
| 619 |
|
| 620 |
Outputs energies, enthalpies, entropies and free energies for each file. |
| 621 |
Optionally includes Boltzmann weighting, imaginary frequencies, symmetry |
| 622 |
point groups, CPU times, and media concentration annotations. |
| 623 |
|
| 624 |
Parameters: |
| 625 |
thermo_data (dict): file path → calc_bbe mapping. |
| 626 |
options (Namespace): parsed CLI options. Uses: dp, QH, invert, spc, |
| 627 |
imag_freq, boltz, symm, duplicate, temperature, cputime, media. |
| 628 |
media_conc (float, optional): neat solvent concentration for display. |
| 629 |
dup_list (list, optional): pairs of duplicate/enantiomer file paths. |
| 630 |
Computed by deduplicate() in the orchestrator. Defaults to []. |
| 631 |
boltz_facs (dict, optional): Boltzmann factors keyed by file path. |
| 632 |
Computed by get_boltz() in the orchestrator. None when --boltz is off. |
| 633 |
""" |
| 634 |
files = list(thermo_data) |
| 635 |
dp = getattr(options, 'dp', 6) |
| 636 |
|
| 637 |
# Surface files lacking frequency info up front (one summary line, not |
| 638 |
# one per file). Truncated to first 3 + count when it gets long. |
| 639 |
no_freq_files = [ |
| 640 |
display_name(f) for f in files |
| 641 |
if not hasattr(thermo_data[f], "gibbs_free_energy") |
| 642 |
] |
| 643 |
if no_freq_files: |
| 644 |
if len(no_freq_files) > 3: |
| 645 |
n_more = len(no_freq_files) - 3 |
| 646 |
list_str = ', '.join(no_freq_files[:3]) + f', and {n_more} others' |
| 647 |
else: |
| 648 |
list_str = ', '.join(no_freq_files) |
| 649 |
log.info(f'\n\n ! No frequency information found: {list_str}') |
| 650 |
|
| 651 |
# Check if user has chosen to make any low lying imaginary frequencies positive |
| 652 |
inverted_freqs, inverted_files = [], [] |
| 653 |
for file in files: |
| 654 |
if thermo_data[file].inverted_freqs: |
| 655 |
inverted_freqs.append(thermo_data[file].inverted_freqs) |
| 656 |
inverted_files.append(file) |
| 657 |
if options.invert is not None: |
| 658 |
for i, file in enumerate(inverted_files): |
| 659 |
if len(inverted_freqs[i]) == 1: |
| 660 |
log.info("\n\n The following frequency was made positive and used in calculations: " + |
| 661 |
str(inverted_freqs[i][0]) + " from " + file) |
| 662 |
elif len(inverted_freqs[i]) > 1: |
| 663 |
log.info("\n\n The following frequencies were made positive and used in calculations: " + |
| 664 |
str(inverted_freqs[i]) + " from " + file) |
| 665 |
|
| 666 |
# Build the Rich table |
| 667 |
table = _build_results_table(options) |
| 668 |
if table is None: |
| 669 |
# Fallback if Rich is not available (shouldn't happen, but safe) |
| 670 |
log.info("\n\nWarning: Rich not available, falling back to ASCII output") |
| 671 |
return |
| 672 |
|
| 673 |
# Default dup_list if not passed by caller |
| 674 |
if dup_list is None: |
| 675 |
dup_list = [] |
| 676 |
|
| 677 |
# Reference qh-G for the optional Grel column (selectivity mode only). |
| 678 |
min_qhg = None |
| 679 |
if _selectivity_active(options): |
| 680 |
dup_files = {dup[0] for dup in dup_list} |
| 681 |
candidates = [ |
| 682 |
thermo_data[f].qh_gibbs_free_energy |
| 683 |
for f in files |
| 684 |
if f not in dup_files |
| 685 |
and hasattr(thermo_data[f], "gibbs_free_energy") |
| 686 |
and not getattr(thermo_data[f], "linear_warning", False) |
| 687 |
] |
| 688 |
if candidates: |
| 689 |
min_qhg = min(candidates) |
| 690 |
|
| 691 |
for file in files: |
| 692 |
duplicate = False |
| 693 |
if dup_list: |
| 694 |
for dup in dup_list: |
| 695 |
if dup[0] == file: |
| 696 |
duplicate = True |
| 697 |
log.info('\n x {} is a duplicate or enantiomer of {}'.format(dup[0].rsplit('.', 1)[0], |
| 698 |
dup[1].rsplit('.', 1)[0])) |
| 699 |
break |
| 700 |
if not duplicate: |
| 701 |
bbe = thermo_data[file] |
| 702 |
# Handle linear molecule warning separately (not a table row) |
| 703 |
if bbe.linear_warning: |
| 704 |
log.info('\n x {} — Caution! Potential invalid linear molecule calculation in Gaussian'.format( |
| 705 |
display_name(file))) |
| 706 |
continue |
| 707 |
|
| 708 |
# Build row for this file |
| 709 |
row = [] |
| 710 |
marker = "o" if hasattr(bbe, "gibbs_free_energy") else "x" |
| 711 |
name = display_name(file) |
| 712 |
|
| 713 |
# No gibbs free energy — already reported in the summary above. |
| 714 |
if not hasattr(bbe, "gibbs_free_energy"): |
| 715 |
continue |
| 716 |
|
| 717 |
row.append(marker) |
| 718 |
row.append(name) |
| 719 |
|
| 720 |
# E_SPC column (if applicable) |
| 721 |
if options.spc is not None: |
| 722 |
if bbe.sp_energy != '!': |
| 723 |
row.append(f"{bbe.sp_energy:.{dp}f}") |
| 724 |
else: |
| 725 |
row.append("----") |
| 726 |
|
| 727 |
# E column |
| 728 |
if bbe.scf_energy is not None: |
| 729 |
row.append(f"{bbe.scf_energy:.{dp}f}") |
| 730 |
else: |
| 731 |
row.append("----") |
| 732 |
|
| 733 |
# ZPE column |
| 734 |
row.append(f"{bbe.zpe:.{dp}f}") |
| 735 |
|
| 736 |
# H and optionally qh-H |
| 737 |
row.append(f"{bbe.enthalpy:.{dp}f}") |
| 738 |
if options.QH: |
| 739 |
row.append(f"{bbe.qh_enthalpy:.{dp}f}") |
| 740 |
|
| 741 |
# T.S and T.qh-S |
| 742 |
row.append(f"{options.temperature * bbe.entropy:.{dp}f}") |
| 743 |
row.append(f"{options.temperature * bbe.qh_entropy:.{dp}f}") |
| 744 |
|
| 745 |
# G(T) and qh-G(T) (or with _SPC suffix) |
| 746 |
row.append(f"{bbe.gibbs_free_energy:.{dp}f}") |
| 747 |
row.append(f"{bbe.qh_gibbs_free_energy:.{dp}f}") |
| 748 |
|
| 749 |
# Optional columns |
| 750 |
if options.boltz: |
| 751 |
row.append(f"{boltz_facs[file]:.3f}") |
| 752 |
if options.symm or options.pg: |
| 753 |
pg = getattr(bbe, "point_group", None) or "---" |
| 754 |
row.append(pg) |
| 755 |
if options.imag_freq is True: |
| 756 |
if hasattr(bbe, "im_frequency_wn") and bbe.im_frequency_wn: |
| 757 |
freq_str = " ".join(f"{f:.2f}" for f in bbe.im_frequency_wn) |
| 758 |
row.append(freq_str) |
| 759 |
else: |
| 760 |
row.append("") |
| 761 |
if min_qhg is not None: |
| 762 |
grel = (bbe.qh_gibbs_free_energy - min_qhg) * 627.509541 |
| 763 |
row.append(f"{grel:.3f}") |
| 764 |
|
| 765 |
table.add_row(*row) |
| 766 |
|
| 767 |
# Media annotation (print after table, not in it) |
| 768 |
if options.media is not None and options.media.lower() in solvents and options.media.lower() == \ |
| 769 |
display_name(file).lower(): |
| 770 |
log.info(" Solvent: {:4.2f}M ".format(media_conc)) |
| 771 |
|
| 772 |
# Print the table |
| 773 |
_print_rich_table(table) |
| 774 |
|
| 775 |
|
| 776 |
def print_temperature_interval(thermo_data, options, media_conc=None, qcdata_cache=None): |
| 777 |
""" |
| 778 |
Recompute thermochemical properties over a temperature interval, log formatted results for each structure and return the computed per-temperature data. |
| 779 |
|
| 780 |
For each file in `thermo_data` this function evaluates thermochemistry at every temperature in the interval (derived from options.temperature_interval), logs a human-readable table of H, T·S, G(T) and their quasi-harmonic variants when requested, and collects the resulting computed objects. |
| 781 |
|
| 782 |
Parameters: |
| 783 |
thermo_data (dict): Mapping of file path → previously computed thermochemistry object (used to determine file order). |
| 784 |
options (Namespace): Parsed CLI/options object. Uses these attributes: temperature_interval, dp, QH, QS, S_freq_cutoff, H_freq_cutoff, spc, conc, freq_scale_factor, freespace, invert, inertia, media. |
| 785 |
media_conc (float, optional): Solvent concentration (M) to annotate solvent-matching structures when media is enabled. |
| 786 |
qcdata_cache (dict, optional): Optional mapping from file basename → pre-parsed QCData to pass through to the recomputation routine. |
| 787 |
|
| 788 |
Returns: |
| 789 |
tuple: (interval_bbe_data, interval, file_list) |
| 790 |
- interval_bbe_data (list[list]): Outer list indexed by file; each inner list contains the recomputed thermochemistry objects (one per temperature). |
| 791 |
- interval (range): Python range object describing the temperatures iterated. |
| 792 |
- file_list (list): List of file paths in the order processed. |
| 793 |
""" |
| 794 |
files = list(thermo_data) |
| 795 |
dp = getattr(options, 'dp', 6) |
| 796 |
dw = dp - 6 |
| 797 |
ef = '{{:{w}.{d}f}}'.format(w=13 + dw, d=dp) |
| 798 |
nf = '{{:{w}.{d}f}}'.format(w=10 + dw, d=dp) |
| 799 |
hf = '{{:{w}.{d}f}}'.format(w=24 + dw, d=dp) # wide H column in temp interval |
| 800 |
ew = 13 + dw |
| 801 |
nw = 10 + dw |
| 802 |
hw = 24 + dw |
| 803 |
# Set up stars separator based on QH option and decimal places |
| 804 |
if options.QH: |
| 805 |
stars = " " + "*" * (142 + 8 * dw) # 8 energy columns with QH |
| 806 |
else: |
| 807 |
stars = " " + "*" * (128 + 7 * dw) # 7 energy columns without QH |
| 808 |
|
| 809 |
log.info("\n\n Variable-Temperature analysis of the enthalpy, entropy and the entropy at a constant pressure between") |
| 810 |
temperature_interval = [float(temp) for temp in options.temperature_interval.split(',')] |
| 811 |
# If no temperature step was defined, divide the region into 10 |
| 812 |
if len(temperature_interval) == 2: |
| 813 |
temperature_interval.append((temperature_interval[1] - temperature_interval[0]) / 10.0) |
| 814 |
interval = range(int(temperature_interval[0]), int(temperature_interval[1] + 1), |
| 815 |
int(temperature_interval[2])) |
| 816 |
log.info("\n T init: %.1f, T final: %.1f, T interval: %.1f" % ( |
| 817 |
temperature_interval[0], temperature_interval[1], temperature_interval[2])) |
| 818 |
if options.QH: |
| 819 |
qh_print_format = ('\n\n {{:<39}} {{:>13}} {{:>{hw}}} {{:>{ew}}} {{:>{nw}}} {{:>{nw}}} ' |
| 820 |
'{{:>{ew}}} {{:>{ew}}}').format(hw=hw, ew=ew, nw=nw) |
| 821 |
if options.spc: |
| 822 |
log.info(qh_print_format.format("Structure", "Temp/K", "H_SPC", "qh-H_SPC", "T.S", "T.qh-S", |
| 823 |
"G(T)_SPC", "qh-G(T)_SPC")) |
| 824 |
else: |
| 825 |
log.info(qh_print_format.format("Structure", "Temp/K", "H", "qh-H", "T.S", "T.qh-S", "G(T)", |
| 826 |
"qh-G(T)")) |
| 827 |
else: |
| 828 |
print_format_3 = ('\n\n {{:<39}} {{:>13}} {{:>{hw}}} {{:>{nw}}} {{:>{nw}}} ' |
| 829 |
'{{:>{ew}}} {{:>{ew}}}').format(hw=hw, nw=nw, ew=ew) |
| 830 |
if options.spc: |
| 831 |
log.info(print_format_3.format("Structure", "Temp/K", "H_SPC", "T.S", "T.qh-S", "G(T)_SPC", |
| 832 |
"qh-G(T)_SPC")) |
| 833 |
else: |
| 834 |
log.info(print_format_3.format("Structure", "Temp/K", "H", "T.S", "T.qh-S", "G(T)", "qh-G(T)"), |
| 835 |
) |
| 836 |
|
| 837 |
interval_bbe_data = [] |
| 838 |
for h, file in enumerate(files): # Temperature interval |
| 839 |
log.info("\n" + stars) |
| 840 |
interval_bbe_data.append([]) |
| 841 |
for temp in interval: # Iterate through the temperature range |
| 842 |
conc = options.conc if options.conc else ATMOS / GAS_CONSTANT / temp |
| 843 |
linear_warning = [] |
| 844 |
# Look up cached QCData if available |
| 845 |
cached_qcdata = None |
| 846 |
if qcdata_cache is not None: |
| 847 |
key = os.path.splitext(os.path.basename(file))[0] |
| 848 |
cached_qcdata = qcdata_cache.get(key) |
| 849 |
bbe = calc_bbe(file, options.QS, options.QH, options.S_freq_cutoff, options.H_freq_cutoff, temp, |
| 850 |
conc, options.freq_scale_factor, options.freespace, options.spc, options.invert, |
| 851 |
inertia=options.inertia, qcdata=cached_qcdata) |
| 852 |
interval_bbe_data[h].append(bbe) |
| 853 |
linear_warning.append(bbe.linear_warning) |
| 854 |
if linear_warning == [['Warning! Potential invalid calculation of linear molecule from Gaussian.']]: |
| 855 |
log.info("\n x ") |
| 856 |
log.info('{:<39}'.format(display_name(file))) |
| 857 |
log.info(' Warning! Potential invalid calculation of linear molecule from Gaussian ...') |
| 858 |
else: |
| 859 |
# Gaussian spc files |
| 860 |
if bbe.scf_energy is not None and not hasattr(bbe, "gibbs_free_energy"): |
| 861 |
log.info("\n x " + '{:<39}'.format(display_name(file))) |
| 862 |
# ORCA spc files |
| 863 |
elif bbe.scf_energy is None and not hasattr(bbe, "gibbs_free_energy"): |
| 864 |
log.info("\n x " + '{:<39}'.format(display_name(file))) |
| 865 |
if not hasattr(bbe, "gibbs_free_energy"): |
| 866 |
log.info("Warning! Couldn't find frequency information ...") |
| 867 |
else: |
| 868 |
log.info("\no ") |
| 869 |
log.info('{:<39} {:13.1f}'.format(display_name(file), temp), |
| 870 |
) |
| 871 |
# if not options.media: |
| 872 |
if all(getattr(bbe, attrib) for attrib in |
| 873 |
["enthalpy", "entropy", "qh_entropy", "gibbs_free_energy", "qh_gibbs_free_energy"]): |
| 874 |
if options.QH: |
| 875 |
log.info((' ' + hf + ' ' + ef + ' ' + nf + ' ' + nf + ' ' + ef + ' ' + ef).format( |
| 876 |
bbe.enthalpy, bbe.qh_enthalpy, (temp * bbe.entropy), |
| 877 |
(temp * bbe.qh_entropy), bbe.gibbs_free_energy, bbe.qh_gibbs_free_energy), |
| 878 |
) |
| 879 |
else: |
| 880 |
log.info((' ' + hf + ' ' + nf + ' ' + nf + ' ' + ef + ' ' + ef).format(bbe.enthalpy, ( |
| 881 |
temp * bbe.entropy), (temp * bbe.qh_entropy), bbe.gibbs_free_energy, bbe.qh_gibbs_free_energy), |
| 882 |
) |
| 883 |
if options.media is not None and options.media.lower() in solvents and options.media.lower() == \ |
| 884 |
display_name(file).lower(): |
| 885 |
log.info(" Solvent: {:4.2f}M ".format(media_conc)) |
| 886 |
|
| 887 |
log.info("\n" + stars + "\n") |
| 888 |
|
| 889 |
return interval_bbe_data, interval, list(files) |
| 890 |
|
| 891 |
|
| 892 |
def print_pes_results(thermo_data, options, dup_list, |
| 893 |
boltz_facs=None, |
| 894 |
interval_bbe_data=None, interval=None, file_list=None): |
| 895 |
"""Print relative PES energies from a YAML-defined reaction pathway. |
| 896 |
|
| 897 |
Reads the PES definition, computes relative energies with optional Boltzmann |
| 898 |
weighting and conformational corrections, and prints formatted tables. |
| 899 |
Optionally computes enantioselectivity and generates reaction profile graphs. |
| 900 |
|
| 901 |
Parameters: |
| 902 |
thermo_data (dict): file path → calc_bbe mapping. |
| 903 |
options (Namespace): parsed CLI options. Uses: dp, QH, spc, gconf, |
| 904 |
temperature_interval, pes, temperature, ee, graph. |
| 905 |
dup_list (list): pairs of duplicate/enantiomer file paths. |
| 906 |
boltz_facs (dict, optional): Boltzmann factors keyed by file path. |
| 907 |
Computed by get_boltz() in the orchestrator. None when --ee is off. |
| 908 |
interval_bbe_data (list, optional): per-file, per-temperature calc_bbe data. |
| 909 |
interval (range, optional): temperature steps for variable-T PES. |
| 910 |
file_list (list, optional): file list from temperature interval analysis. |
| 911 |
""" |
| 912 |
files = list(thermo_data) |
| 913 |
dp = getattr(options, 'dp', 6) |
| 914 |
dw = dp - 6 |
| 915 |
# Set up stars separator based on QH option and decimal places |
| 916 |
if options.QH: |
| 917 |
stars = " " + "*" * (142 + 8 * dw) # 8 energy columns with QH |
| 918 |
else: |
| 919 |
stars = " " + "*" * (128 + 7 * dw) # 7 energy columns without QH |
| 920 |
|
| 921 |
# Validate thermodynamic data once |
| 922 |
for key in thermo_data: |
| 923 |
if not hasattr(thermo_data[key], "qh_gibbs_free_energy"): |
| 924 |
pes_error = "\nWarning! Could not find thermodynamic data for " + key + "\n" |
| 925 |
sys.exit(pes_error) |
| 926 |
if not hasattr(thermo_data[key], "sp_energy") and options.spc is not None: |
| 927 |
pes_error = "\nWarning! Could not find thermodynamic data for " + key + "\n" |
| 928 |
sys.exit(pes_error) |
| 929 |
|
| 930 |
if options.gconf: |
| 931 |
log.info('\n Gconf correction requested to be applied to below relative values using quasi-harmonic Boltzmann factors\n') |
| 932 |
|
| 933 |
# Interval applied to PES |
| 934 |
if options.temperature_interval: |
| 935 |
stars = stars + '*' * 22 |
| 936 |
interval_thermo_data = [dict(zip(file_list, bbe_vals)) |
| 937 |
for bbe_vals in zip(*interval_bbe_data)] |
| 938 |
j = 0 |
| 939 |
for i in interval: |
| 940 |
temp = float(i) |
| 941 |
pes = get_pes(options.pes, interval_thermo_data[j], temp, options.gconf, options.QH) |
| 942 |
for k, path in enumerate(pes.path): |
| 943 |
if options.QH: |
| 944 |
zero_vals = [pes.spc_zero[k][0], pes.e_zero[k][0], pes.zpe_zero[k][0], pes.h_zero[k][0], |
| 945 |
pes.qh_zero[k][0], temp * pes.ts_zero[k][0], temp * pes.qhts_zero[k][0], |
| 946 |
pes.g_zero[k][0], pes.qhg_zero[k][0]] |
| 947 |
else: |
| 948 |
zero_vals = [pes.spc_zero[k][0], pes.e_zero[k][0], pes.zpe_zero[k][0], pes.h_zero[k][0], |
| 949 |
temp * pes.ts_zero[k][0], temp * pes.qhts_zero[k][0], pes.g_zero[k][0], |
| 950 |
pes.qhg_zero[k][0]] |
| 951 |
if pes.boltz: |
| 952 |
e_sum, h_sum, g_sum, qhg_sum = 0.0, 0.0, 0.0, 0.0 |
| 953 |
sels = [] |
| 954 |
for m, e_abs in enumerate(pes.e_abs[k]): |
| 955 |
if options.QH: |
| 956 |
species = [pes.spc_abs[k][m], pes.e_abs[k][m], pes.zpe_abs[k][m], pes.h_abs[k][m], |
| 957 |
pes.qh_abs[k][m], temp * pes.s_abs[k][m], temp * pes.qs_abs[k][m], |
| 958 |
pes.g_abs[k][m], pes.qhg_abs[k][m]] |
| 959 |
else: |
| 960 |
species = [pes.spc_abs[k][m], pes.e_abs[k][m], pes.zpe_abs[k][m], pes.h_abs[k][m], |
| 961 |
temp * pes.s_abs[k][m], temp * pes.qs_abs[k][m], pes.g_abs[k][m], |
| 962 |
pes.qhg_abs[k][m]] |
| 963 |
relative = [s - z for s, z in zip(species, zero_vals)] |
| 964 |
e_sum += math.exp(-relative[1] * J_TO_AU / GAS_CONSTANT / temp) |
| 965 |
h_sum += math.exp(-relative[3] * J_TO_AU / GAS_CONSTANT / temp) |
| 966 |
g_sum += math.exp(-relative[7] * J_TO_AU / GAS_CONSTANT / temp) |
| 967 |
qhg_sum += math.exp(-relative[8] * J_TO_AU / GAS_CONSTANT / temp) |
| 968 |
if options.spc is None: |
| 969 |
log.info("\n " + '{:<40}'.format("RXN: " + path + " (" + pes.units + ") at T: " + str(temp))) |
| 970 |
if options.QH: |
| 971 |
log.info('{:>13} {:>10} {:>13} {:>13} {:>10} {:>10} {:>13} ' |
| 972 |
'{:>13}'.format(" DE", "DZPE", "DH", "qh-DH", "T.DS", "T.qh-DS", "DG(T)", |
| 973 |
"qh-DG(T)")) |
| 974 |
else: |
| 975 |
log.info('{:>13} {:>10} {:>13} {:>10} {:>10} {:>13} ' |
| 976 |
'{:>13}'.format(" DE", "DZPE", "DH", "T.DS", "T.qh-DS", "DG(T)", "qh-DG(T)"), |
| 977 |
) |
| 978 |
else: |
| 979 |
log.info("\n " + '{:<40}'.format("RXN: " + path + " (" + pes.units + ") at T: " + |
| 980 |
str(temp))) |
| 981 |
if options.QH: |
| 982 |
log.info('{:>13} {:>13} {:>10} {:>13} {:>13} {:>10} {:>10} {:>14} ' |
| 983 |
'{:>14}'.format(" DE_SPC", "DE", "DZPE", "DH_SPC", "qh-DH_SPC", "T.DS", |
| 984 |
"T.qh-DS", "DG(T)_SPC", "qh-DG(T)_SPC")) |
| 985 |
else: |
| 986 |
log.info('{:>13} {:>13} {:>10} {:>13} {:>10} {:>10} {:>14} ' |
| 987 |
'{:>14}'.format(" DE_SPC", "DE", "DZPE", "DH_SPC", "T.DS", "T.qh-DS", |
| 988 |
"DG(T)_SPC", "qh-DG(T)_SPC")) |
| 989 |
log.info("\n" + stars) |
| 990 |
|
| 991 |
for m, e_abs in enumerate(pes.e_abs[k]): |
| 992 |
if options.QH: |
| 993 |
species = [pes.spc_abs[k][m], pes.e_abs[k][m], pes.zpe_abs[k][m], pes.h_abs[k][m], |
| 994 |
pes.qh_abs[k][m], temp * pes.s_abs[k][m], temp * pes.qs_abs[k][m], |
| 995 |
pes.g_abs[k][m], pes.qhg_abs[k][m]] |
| 996 |
else: |
| 997 |
species = [pes.spc_abs[k][m], pes.e_abs[k][m], pes.zpe_abs[k][m], pes.h_abs[k][m], |
| 998 |
temp * pes.s_abs[k][m], temp * pes.qs_abs[k][m], pes.g_abs[k][m], |
| 999 |
pes.qhg_abs[k][m]] |
| 1000 |
relative = [s - z for s, z in zip(species, zero_vals)] |
| 1001 |
if pes.units == 'kJ/mol': |
| 1002 |
formatted_list = [J_TO_AU / 1000.0 * x for x in relative] |
| 1003 |
else: |
| 1004 |
formatted_list = [KCAL_TO_AU * x for x in relative] # Defaults to kcal/mol |
| 1005 |
log.info("\no ") |
| 1006 |
if options.spc is None: |
| 1007 |
formatted_list = formatted_list[1:] |
| 1008 |
if options.QH: |
| 1009 |
format_1 = '{:<39} {:13.1f} {:10.1f} {:13.1f} {:13.1f} {:10.1f} {:10.1f} {:13.1f} {:13.1f}' |
| 1010 |
format_2 = '{:<39} {:13.2f} {:10.2f} {:13.2f} {:13.2f} {:10.2f} {:10.2f} {:13.2f} {:13.2f}' |
| 1011 |
else: |
| 1012 |
format_1 = '{:<39} {:13.1f} {:10.1f} {:13.1f} {:10.1f} {:10.1f} {:13.1f} {:13.1f}' |
| 1013 |
format_2 = '{:<39} {:13.2f} {:10.2f} {:13.2f} {:10.2f} {:10.2f} {:13.2f} {:13.2f}' |
| 1014 |
if pes.dec == 1: |
| 1015 |
log.info(format_1.format(pes.species[k][m], *formatted_list)) |
| 1016 |
if pes.dec == 2: |
| 1017 |
log.info(format_2.format(pes.species[k][m], *formatted_list)) |
| 1018 |
else: |
| 1019 |
if options.QH: |
| 1020 |
if pes.dec == 1: |
| 1021 |
log.info('{:<39} {:13.1f} {:13.1f} {:10.1f} {:13.1f} {:13.1f} {:10.1f} {:10.1f} {:13.1f} {:13.1f}'.format( |
| 1022 |
pes.species[k][m], *formatted_list)) |
| 1023 |
if pes.dec == 2: |
| 1024 |
log.info('{:<39} {:13.1f} {:13.2f} {:10.2f} {:13.2f} {:13.2f} {:10.2f} {:10.2f} {:13.2f} {:13.2f}'.format( |
| 1025 |
pes.species[k][m], *formatted_list)) |
| 1026 |
else: |
| 1027 |
if pes.dec == 1: |
| 1028 |
log.info('{:<39} {:13.1f} {:13.1f} {:10.1f} {:13.1f} {:10.1f} {:10.1f} {:13.1f} {:13.1f}'.format( |
| 1029 |
pes.species[k][m], *formatted_list)) |
| 1030 |
if pes.dec == 2: |
| 1031 |
log.info('{:<39} {:13.2f} {:13.2f} {:10.2f} {:13.2f} {:10.2f} {:10.2f} {:13.2f} {:13.2f}'.format( |
| 1032 |
pes.species[k][m], *formatted_list)) |
| 1033 |
if pes.boltz: |
| 1034 |
boltz = [math.exp(-relative[1] * J_TO_AU / GAS_CONSTANT / options.temperature) / e_sum, |
| 1035 |
math.exp(-relative[3] * J_TO_AU / GAS_CONSTANT / options.temperature) / h_sum, |
| 1036 |
math.exp(-relative[6] * J_TO_AU / GAS_CONSTANT / options.temperature) / g_sum, |
| 1037 |
math.exp(-relative[7] * J_TO_AU / GAS_CONSTANT / options.temperature) / qhg_sum] |
| 1038 |
selectivity = [b * 100.0 for b in boltz] |
| 1039 |
log.info("\n " + '{:<39} {:13.2f}%{:24.2f}%{:35.2f}%{:13.2f}%'.format('', *selectivity)) |
| 1040 |
sels.append(selectivity) |
| 1041 |
formatted_list = [round(v, 6) for v in formatted_list] |
| 1042 |
if pes.boltz == 'ee' and len(sels) == 2: |
| 1043 |
ee = [a - b for a, b in zip(sels[0], sels[1])] |
| 1044 |
if options.spc is None: |
| 1045 |
log.info("\n" + stars + "\n " + '{:<39} {:13.1f}%{:24.1f}%{:35.1f}%{:13.1f}%'.format('ee (%)', |
| 1046 |
*ee)) |
| 1047 |
else: |
| 1048 |
log.info("\n" + stars + "\n " + '{:<39} {:27.1f} {:24.1f} {:35.1f} {:13.1f} '.format('ee (%)', |
| 1049 |
*ee)) |
| 1050 |
log.info("\n" + stars + "\n") |
| 1051 |
j += 1 |
| 1052 |
else: |
| 1053 |
pes = get_pes(options.pes, thermo_data, options.temperature, options.gconf, options.QH) |
| 1054 |
# Output the relative energy data |
| 1055 |
for i, path in enumerate(pes.path): |
| 1056 |
if options.QH: |
| 1057 |
zero_vals = [pes.spc_zero[i][0], pes.e_zero[i][0], pes.zpe_zero[i][0], pes.h_zero[i][0], |
| 1058 |
pes.qh_zero[i][0], options.temperature * pes.ts_zero[i][0], |
| 1059 |
options.temperature * pes.qhts_zero[i][0], pes.g_zero[i][0], pes.qhg_zero[i][0]] |
| 1060 |
else: |
| 1061 |
zero_vals = [pes.spc_zero[i][0], pes.e_zero[i][0], pes.zpe_zero[i][0], pes.h_zero[i][0], |
| 1062 |
options.temperature * pes.ts_zero[i][0], options.temperature * pes.qhts_zero[i][0], |
| 1063 |
pes.g_zero[i][0], pes.qhg_zero[i][0]] |
| 1064 |
if pes.boltz: |
| 1065 |
e_sum, h_sum, g_sum, qhg_sum = 0.0, 0.0, 0.0, 0.0 |
| 1066 |
sels = [] |
| 1067 |
for j, e_abs in enumerate(pes.e_abs[i]): |
| 1068 |
if options.QH: |
| 1069 |
species = [pes.spc_abs[i][j], pes.e_abs[i][j], pes.zpe_abs[i][j], pes.h_abs[i][j], |
| 1070 |
pes.qh_abs[i][j], options.temperature * pes.s_abs[i][j], |
| 1071 |
options.temperature * pes.qs_abs[i][j], pes.g_abs[i][j], pes.qhg_abs[i][j]] |
| 1072 |
else: |
| 1073 |
species = [pes.spc_abs[i][j], pes.e_abs[i][j], pes.zpe_abs[i][j], pes.h_abs[i][j], |
| 1074 |
options.temperature * pes.s_abs[i][j], options.temperature * pes.qs_abs[i][j], |
| 1075 |
pes.g_abs[i][j], pes.qhg_abs[i][j]] |
| 1076 |
relative = [s - z for s, z in zip(species, zero_vals)] |
| 1077 |
e_sum += math.exp(-relative[1] * J_TO_AU / GAS_CONSTANT / options.temperature) |
| 1078 |
h_sum += math.exp(-relative[3] * J_TO_AU / GAS_CONSTANT / options.temperature) |
| 1079 |
g_sum += math.exp(-relative[7] * J_TO_AU / GAS_CONSTANT / options.temperature) |
| 1080 |
qhg_sum += math.exp(-relative[8] * J_TO_AU / GAS_CONSTANT / options.temperature) |
| 1081 |
|
| 1082 |
if options.spc is None: |
| 1083 |
log.info("\n " + '{:<40}'.format("RXN: " + path + " (" + pes.units + ") ", )) |
| 1084 |
if options.QH: |
| 1085 |
log.info('{:>13} {:>10} {:>13} {:>13} {:>10} {:>10} {:>13} ' |
| 1086 |
'{:>13}'.format(" DE", "DZPE", "DH", "qh-DH", "T.DS", "T.qh-DS", "DG(T)", "qh-DG(T)"), |
| 1087 |
) |
| 1088 |
else: |
| 1089 |
log.info('{:>13} {:>10} {:>13} {:>10} {:>10} {:>13} ' |
| 1090 |
'{:>13}'.format(" DE", "DZPE", "DH", "T.DS", "T.qh-DS", "DG(T)", "qh-DG(T)"), |
| 1091 |
) |
| 1092 |
else: |
| 1093 |
log.info("\n " + '{:<40}'.format("RXN: " + path + " (" + pes.units + ") ", )) |
| 1094 |
if options.QH: |
| 1095 |
log.info('{:>13} {:>13} {:>10} {:>13} {:>13} {:>10} {:>10} {:>14} ' |
| 1096 |
'{:>14}'.format(" DE_SPC", "DE", "DZPE", "DH_SPC", "qh-DH_SPC", "T.DS", "T.qh-DS", |
| 1097 |
"DG(T)_SPC", "qh-DG(T)_SPC")) |
| 1098 |
else: |
| 1099 |
log.info('{:>13} {:>13} {:>10} {:>13} {:>10} {:>10} {:>14} ' |
| 1100 |
'{:>14}'.format(" DE_SPC", "DE", "DZPE", "DH_SPC", "T.DS", "T.qh-DS", "DG(T)_SPC", |
| 1101 |
"qh-DG(T)_SPC")) |
| 1102 |
log.info("\n" + stars) |
| 1103 |
|
| 1104 |
for j, e_abs in enumerate(pes.e_abs[i]): |
| 1105 |
if options.QH: |
| 1106 |
species = [pes.spc_abs[i][j], pes.e_abs[i][j], pes.zpe_abs[i][j], pes.h_abs[i][j], |
| 1107 |
pes.qh_abs[i][j], options.temperature * pes.s_abs[i][j], |
| 1108 |
options.temperature * pes.qs_abs[i][j], pes.g_abs[i][j], pes.qhg_abs[i][j]] |
| 1109 |
else: |
| 1110 |
species = [pes.spc_abs[i][j], pes.e_abs[i][j], pes.zpe_abs[i][j], pes.h_abs[i][j], |
| 1111 |
options.temperature * pes.s_abs[i][j], options.temperature * pes.qs_abs[i][j], |
| 1112 |
pes.g_abs[i][j], pes.qhg_abs[i][j]] |
| 1113 |
relative = [s - z for s, z in zip(species, zero_vals)] |
| 1114 |
if pes.units == 'kJ/mol': |
| 1115 |
formatted_list = [J_TO_AU / 1000.0 * x for x in relative] |
| 1116 |
else: |
| 1117 |
formatted_list = [KCAL_TO_AU * x for x in relative] # Defaults to kcal/mol |
| 1118 |
log.info("\no ") |
| 1119 |
if options.spc is None: |
| 1120 |
formatted_list = formatted_list[1:] |
| 1121 |
if options.QH: |
| 1122 |
if pes.dec == 1: |
| 1123 |
log.info('{:<39} {:13.1f} {:10.1f} {:13.1f} {:13.1f} {:10.1f} {:10.1f} {:13.1f} ' |
| 1124 |
'{:13.1f}'.format(pes.species[i][j], *formatted_list)) |
| 1125 |
if pes.dec == 2: |
| 1126 |
log.info('{:<39} {:13.2f} {:10.2f} {:13.2f} {:13.2f} {:10.2f} {:10.2f} {:13.2f} ' |
| 1127 |
'{:13.2f}'.format(pes.species[i][j], *formatted_list)) |
| 1128 |
else: |
| 1129 |
if pes.dec == 1: |
| 1130 |
log.info('{:<39} {:13.1f} {:10.1f} {:13.1f} {:10.1f} {:10.1f} {:13.1f} ' |
| 1131 |
'{:13.1f}'.format(pes.species[i][j], *formatted_list)) |
| 1132 |
if pes.dec == 2: |
| 1133 |
log.info('{:<39} {:13.2f} {:10.2f} {:13.2f} {:10.2f} {:10.2f} {:13.2f} ' |
| 1134 |
'{:13.2f}'.format(pes.species[i][j], *formatted_list)) |
| 1135 |
else: |
| 1136 |
if options.QH: |
| 1137 |
if pes.dec == 1: |
| 1138 |
log.info('{:<39} {:13.1f} {:13.1f} {:10.1f} {:13.1f} {:13.1f} {:10.1f} {:10.1f} ' |
| 1139 |
'{:13.1f} {:13.1f}'.format(pes.species[i][j], *formatted_list), |
| 1140 |
) |
| 1141 |
if pes.dec == 2: |
| 1142 |
log.info('{:<39} {:13.1f} {:13.2f} {:10.2f} {:13.2f} {:13.2f} {:10.2f} {:10.2f} ' |
| 1143 |
'{:13.2f} {:13.2f}'.format(pes.species[i][j], *formatted_list), |
| 1144 |
) |
| 1145 |
else: |
| 1146 |
if pes.dec == 1: |
| 1147 |
log.info('{:<39} {:13.1f} {:13.1f} {:10.1f} {:13.1f} {:10.1f} {:10.1f} {:13.1f} ' |
| 1148 |
'{:13.1f}'.format(pes.species[i][j], *formatted_list)) |
| 1149 |
if pes.dec == 2: |
| 1150 |
log.info('{:<39} {:13.2f} {:13.2f} {:10.2f} {:13.2f} {:10.2f} {:10.2f} {:13.2f} ' |
| 1151 |
'{:13.2f}'.format(pes.species[i][j], *formatted_list)) |
| 1152 |
if pes.boltz: |
| 1153 |
boltz = [math.exp(-relative[1] * J_TO_AU / GAS_CONSTANT / options.temperature) / e_sum, |
| 1154 |
math.exp(-relative[3] * J_TO_AU / GAS_CONSTANT / options.temperature) / h_sum, |
| 1155 |
math.exp(-relative[6] * J_TO_AU / GAS_CONSTANT / options.temperature) / g_sum, |
| 1156 |
math.exp(-relative[7] * J_TO_AU / GAS_CONSTANT / options.temperature) / qhg_sum] |
| 1157 |
selectivity = [b * 100.0 for b in boltz] |
| 1158 |
log.info("\n " + '{:<39} {:13.2f}%{:24.2f}%{:35.2f}%{:13.2f}%'.format('', *selectivity)) |
| 1159 |
sels.append(selectivity) |
| 1160 |
formatted_list = [round(v, 6) for v in formatted_list] |
| 1161 |
if pes.boltz == 'ee' and len(sels) == 2: |
| 1162 |
ee = [a - b for a, b in zip(sels[0], sels[1])] |
| 1163 |
if options.spc is None: |
| 1164 |
log.info("\n" + stars + "\n " + '{:<39} {:13.1f}%{:24.1f}%{:35.1f}%{:13.1f}%'.format('ee (%)', *ee)) |
| 1165 |
else: |
| 1166 |
log.info("\n" + stars + "\n " + '{:<39} {:27.1f} {:24.1f} {:35.1f} {:13.1f} '.format('ee (%)', *ee)) |
| 1167 |
log.info("\n" + stars + "\n") |
| 1168 |
|
| 1169 |
# Compute enantiomeric excess |
| 1170 |
if options.ee is not None: |
| 1171 |
selec_stars = " " + '*' * 109 |
| 1172 |
ee, er, ratio, dd_free_energy, failed, preference = get_selectivity(options.ee, files, boltz_facs, |
| 1173 |
options.temperature, dup_list) |
| 1174 |
if not failed: |
| 1175 |
log.info("\n " + '{:<39} {:>13} {:>13} {:>13} {:>13} {:>13}'.format("Selectivity", "Excess (%)", "Ratio (%)", "Ratio", "Major Iso", "ddG")) |
| 1176 |
log.info("\n" + selec_stars) |
| 1177 |
log.info('\no {:<40} {:13.2f} {:>13} {:>13} {:>13} {:13.2f}'.format('', ee, er, ratio, preference, |
| 1178 |
dd_free_energy)) |
| 1179 |
log.info("\n" + selec_stars + "\n") |
| 1180 |
# --graph rendering moved up to GoodVibes.main() in v5.0 so it |
| 1181 |
# fires in single-T mode too (v4.2's print_pes_tables doesn't go |
| 1182 |
# through this function). The legacy T-interval path still calls |
| 1183 |
# print_pes_results, but main() handles the graph either way. |