Debian Codegraph @

goodvibes/GoodVibes.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 """Quasi-harmonic thermochemical corrections for electronic structure calculations."""
4 import os.path
5 import sys
6 from glob import glob
7 from argparse import ArgumentParser
8
9 from .vib_scale_factors import scaling_data_dict, scaling_refs, canonicalize_level
10 from .io import write_xyz, load_cache, save_cache, qcdata_to_dict, find_spc_file
11 from .thermo import calc_bbe, get_free_space, FREESPACE_SOLVENTS
12 from .media import solvents, compute_media_conc, lookup_solvent
13 from .constants import (
14 SUPPORTED_EXTENSIONS, GAS_CONSTANT, ATMOS,
15 grimme_mRRHO_ref, grimme_msRRHO_ref, truhlar_ref, head_gordon_ref,
16 oniom_scale_ref, gv_banner
17 )
18 import logging
19 from .utils import all_same, setup_logging, fatal, natural_key
20 from .validation import collect_and_validate_files, check_files, print_check_fails
21 from .sort import deduplicate, sort_thermo
22 from .selectivity import (get_boltz, parse_label_args, load_label_yaml,
23 assign_files_to_labels, compute_selectivity,
24 compute_selectivity_scan,
25 compute_selectivity_lowest_only,
26 compute_selectivity_lowest_only_scan)
27 from .output import (print_results, print_temperature_interval,
28 print_pes_results, print_cpu_time, write_json_results,
29 print_selectivity_results)
30
31 log = logging.getLogger('goodvibes')
32
33
34 def parse_arguments():
35 """Parse command-line arguments and return (options, args)."""
36
37 # Get command line inputs. Use -h to list all possible arguments and default values
38 parser = ArgumentParser(
39 prog="goodvibes",
40 description="Compute quasi-harmonic thermochemical corrections from quantum chemistry output files.")
41
42 state = parser.add_argument_group("Temperature & state")
43 state.add_argument("--temp", dest="temperature", default=298.15, type=float, metavar="TEMP",
44 help="Temperature in Kelvin (default: 298.15)")
45 state.add_argument("--ti", dest="temperature_interval", default=None, metavar="TI",
46 help="Temperature interval as START,END,STEP in Kelvin (e.g. '300,1000,100')")
47 state.add_argument("-c", "--conc", dest="conc", default=None, type=float, metavar="CONC",
48 help="Concentration in mol/L for solution-phase entropy; gas phase (1 atm) if not set")
49 state.add_argument("--media", dest="media", default=None, metavar="solvent",
50 help="Apply standard-state concentration correction for the given solvent "
51 "(e.g. H2O corrects to 55.34 M)")
52 state.add_argument("--freespace", dest="freespace", default=None, type=str, metavar="SOLVENT",
53 help="Apply free-space correction for the given solvent (e.g. H2O, toluene, DMF, "
54 "AcOH, chloroform)")
55
56 qh = parser.add_argument_group("Quasi-harmonic corrections")
57 qh.add_argument("-q", dest="Q", action="store_true", default=False,
58 help="Apply both quasi-harmonic entropy (Grimme mRRHO) and enthalpy (Head-Gordon) corrections")
59 qh.add_argument("--qh", dest="QH", action="store_true", default=False,
60 help="Apply Head-Gordon quasi-harmonic enthalpy correction")
61 qh.add_argument("--qs", dest="QS", default="grimme", type=str.lower, metavar="QS",
62 choices=('grimme', 'truhlar'),
63 help="Quasi-harmonic entropy method: 'grimme' for mRRHO free-rotor interpolation, "
64 "'truhlar' for frequency raising (default: grimme)")
65 qh.add_argument("-f", "--tau", dest="freq_cutoff", default=100, type=float, metavar="FREQ_CUTOFF",
66 help="Frequency cut-off for both entropy and enthalpy in cm-1 (default: 100)")
67 qh.add_argument("--fh", dest="H_freq_cutoff", default=100.0, type=float, metavar="H_FREQ_CUTOFF",
68 help="Frequency cut-off for enthalpy only in cm-1; overrides -f for H (default: 100)")
69 qh.add_argument("--fs", dest="S_freq_cutoff", default=100.0, type=float, metavar="S_FREQ_CUTOFF",
70 help="Frequency cut-off for entropy only in cm-1; overrides -f for S (default: 100)")
71 qh.add_argument("--bav", dest='inertia', default="global", type=str, choices=['global', 'conf'],
72 help="Moment of inertia for free-rotor entropy: 'global' uses Bav = 10e-44 kg m^2 "
73 "for all molecules, 'conf' computes from rotational constants per file "
74 "(default: global)")
75
76 freq = parser.add_argument_group("Frequency handling")
77 freq.add_argument("-v", "--vscal", dest="freq_scale_factor", default=None, type=float, metavar="SCALE_FACTOR",
78 help="Vibrational frequency scaling factor for the partition-function frequencies "
79 "(H_vib, S_vib); auto-detected from level of theory via Truhlar's harm_fac if "
80 "not set, falls back to 1.0")
81 freq.add_argument("--zpe-vscal", dest="zpe_scale_factor", default=None, type=float, metavar="ZPE_SCALE_FACTOR",
82 help="Separate scaling factor for the zero-point energy (ZPE); auto-detected from "
83 "level of theory via Truhlar's zpe_fac if not set. If --vscal is set but "
84 "--zpe-vscal is not, ZPE inherits --vscal (back-compat).")
85 freq.add_argument("--vmm", dest="mm_freq_scale_factor", default=None, type=float, metavar="MM_SCALE_FACTOR",
86 help="Frequency scaling factor for the MM region in ONIOM calculations")
87 freq.add_argument("--invert", dest="invert", nargs='?', const=True, default=None, type=float,
88 help="Invert small imaginary frequencies (> -50 cm-1) to positive values; "
89 "optionally provide a custom threshold in cm-1")
90 freq.add_argument("--imag", dest="imag_freq", action="store_true", default=False,
91 help="Print imaginary frequencies for each structure")
92
93 sym = parser.add_argument_group("Symmetry")
94 sym.add_argument("--symm", dest='symm', action="store_true", default=False,
95 help="Apply external symmetry correction to entropy using point-group detection (pymsym)")
96 sym.add_argument("--pg", dest='pg', action="store_true", default=False,
97 help="Display point group from output file (no entropy correction applied)")
98
99 sort_grp = parser.add_argument_group("Sorting & deduplication")
100 sort_grp.add_argument("--sort", dest="sort", default=None, nargs='?', const='gibbs',
101 type=str, choices=['energy', 'gibbs'], metavar="KEY",
102 help="Sort output by energy ('energy' for SCF, 'gibbs' for quasi-harmonic G; default when flag used: gibbs)")
103 sort_grp.add_argument("--boltz", dest="boltz", default=None, nargs='?', const='gibbs',
104 type=str, choices=['energy', 'gibbs'], metavar="KEY",
105 help="Print Boltzmann-weighted populations ('energy' for SCF, 'gibbs' for quasi-harmonic G; "
106 "default when flag used: gibbs)")
107 sort_grp.add_argument("--dedup", dest="duplicate", action="store_true", default=False,
108 help="Remove duplicate structures based on energy, rotational constants, and stoichiometry")
109 sort_grp.add_argument("--e_cutoff", dest="e_cutoff", default=0.05, type=float, metavar="KCAL",
110 help="Energy cutoff for duplicate detection in kcal/mol (default: 0.05)")
111 sort_grp.add_argument("--ro_cutoff", dest="ro_cutoff", default=0.01, type=float, metavar="FRAC",
112 help="Rotational constant cutoff for duplicate detection as a fraction (default: 0.01 = 1%%)")
113 sort_grp.add_argument("--rmsd_cutoff", dest="rmsd_cutoff", default=None, type=float, metavar="ANGS",
114 help="RMSD cutoff for duplicate detection in Angstrom (default: off; 0.125 matches CREST)")
115
116 sel = parser.add_argument_group("Selectivity & PES")
117 sel.add_argument("--label", dest="labels", default=None, action='append', metavar="NAME=PATTERN",
118 help="Repeatable: assign files matching fnmatch PATTERN to species NAME "
119 "for selectivity analysis. Two or more species supported "
120 "(N=2: excess + ΔΔG; N>2: populations only). Example: "
121 "--label R='*P_R_*' --label S='*P_S_*'.")
122 sel.add_argument("--selectivity", dest="selectivity_spec", default=None, metavar="FILE.yaml",
123 help="YAML spec for selectivity analysis. Top-level key 'labels' "
124 "maps species -> fnmatch pattern, or 'files' maps species -> "
125 "explicit list of files. Use instead of --label for many "
126 "species or shareable specs.")
127 sel.add_argument("--ee", dest="ee", default=None, type=str, metavar="patterns",
128 help="DEPRECATED — use --label/--selectivity. Compute 2-species "
129 "selectivity from a colon-delimited glob pair (e.g. '*_R*:*_S*'). "
130 "Will be removed in v5.0.")
131 sel.add_argument("--pes", dest="pes", default=None, metavar="file",
132 help="YAML file defining a reaction pathway for tabulating relative energies")
133 sel.add_argument("--graph", dest='graph', default=None, metavar="file",
134 help="Graph a reaction profile from free energies; provide the PES YAML file")
135 sel.add_argument("--nogconf", dest="gconf", action="store_false", default=True,
136 help="Disable the Gconf correction for multi-conformer ensembles (enabled by default)")
137 sel.add_argument("--lowest-only", dest="lowest_only", action="store_true", default=False,
138 help="PES tables: use only each species' lowest qh-G conformer "
139 "(overrides --nogconf and the default Gconf correction)")
140
141 inp = parser.add_argument_group("Input")
142 inp.add_argument("--custom_ext", type=str, default='', metavar="exts",
143 help="Additional file extensions to accept, comma-separated "
144 "(e.g. '.qfi,.gaussian'); also settable via GOODVIBES_CUSTOM_EXT env var")
145 inp.add_argument("--exclude", dest="exclude", default=None, type=str, metavar="PATTERN",
146 help="Glob pattern to exclude files from the analysis (e.g. '*_TZ.out')")
147 inp.add_argument("--spc", dest="spc", type=str, default=None, metavar="suffix",
148 help="Single-point correction suffix: reads energy from FILE_SPC.ext "
149 "(e.g. --spc TZ reads from FILE_TZ.log)")
150 inp.add_argument("--import", dest="import_path", default=None, type=str, metavar="PATH",
151 help="Read pre-parsed data from a v1.0 JSON file (or a legacy "
152 "--cache-save envelope) instead of re-parsing the input "
153 "QC outputs. Useful for fast re-analysis at a different "
154 "temperature/concentration without re-reading large outputs.")
155 inp.add_argument("--cache-read", dest="cache_read", default=None, type=str, metavar="FILE",
156 help="(deprecated, use --import instead) Read pre-parsed data from a JSON file.")
157
158 out = parser.add_argument_group("Output & reports")
159 out.add_argument("--output", dest="output", default="output", metavar="name",
160 help="Base name for the output file, written as GoodVibes_OUTPUT.dat (default: output)")
161 out.add_argument("--dp", dest="dp", default=6, type=int, metavar="DP",
162 help="Number of decimal places for energy values in output (default: 6)")
163 out.add_argument("--json", dest="json_path", default=None, metavar="PATH",
164 help="Write structured results to PATH as JSON (every parsed and computed "
165 "field per file plus the run options). Schema is preview/v0.1.")
166 out.add_argument("--csv", dest="csv_path", default=None, metavar="PATH",
167 help="Write per-file thermochemistry to PATH as CSV (one row per "
168 "structure; columns mirror ThermoResult). Requires pandas; "
169 "install with `pip install goodvibes[full]`.")
170 out.add_argument("--parquet", dest="parquet_path", default=None, metavar="PATH",
171 help="Write per-file thermochemistry to PATH as Parquet (same "
172 "columns as --csv). Requires pandas + a Parquet engine "
173 "(pyarrow); install with `pip install goodvibes[full]`.")
174 out.add_argument("--xyz", dest="xyz", action="store_true", default=False,
175 help="Write optimized Cartesian coordinates to a .xyz file")
176 out.add_argument("--strip-plot", dest="strip_plot_path", default=None, metavar="PATH",
177 help="Save a per-species ΔG strip plot to PATH (PNG/PDF/SVG by "
178 "extension). Requires --label or --selectivity to define "
179 "buckets; matplotlib via `pip install goodvibes[plot]`.")
180 out.add_argument("--pes-plot", dest="pes_plot_path", default=None, metavar="PATH",
181 help="Save a clean reaction-profile diagram to PATH (PNG/PDF/SVG "
182 "by extension). Requires --pes; uses goodvibes.plot.plot_pes "
183 "(simpler than the legacy --graph FILE.yaml, no styling YAML "
184 "needed). matplotlib via `pip install goodvibes[plot]`.")
185 out.add_argument("--export", dest="export_path", default=None, type=str, metavar="PATH",
186 help="Write the unified v1.0 JSON payload to PATH "
187 "(per-file QCData + thermo + run options + selectivity / pes "
188 "blocks). Identical to --json. The same file can be re-loaded "
189 "via --import to skip parsing on a follow-up run.")
190 out.add_argument("--cache-save", dest="cache_save", default=None, type=str, metavar="FILE",
191 help="(deprecated, use --export instead) Save parsed data to a JSON file.")
192 out.add_argument("--cpu", dest="cputime", action="store_true", default=False,
193 help="Print total CPU time from output files")
194 out.add_argument("--check", dest="check", action="store_true", default=False,
195 help="Verify all files use the same program, level of theory, and solvation model; "
196 "also flag potential duplicates")
197
198 perf = parser.add_argument_group("Performance")
199 perf.add_argument("--jobs", dest="jobs", type=int, default=1, metavar="N",
200 help="Parse and compute thermochemistry in parallel across N "
201 "worker processes (default 1, sequential). 0 = use all "
202 "available CPU cores.")
203 # Parse Arguments
204 (options, args) = parser.parse_known_args()
205
206 # If requested, turn on head-gordon enthalpy correction
207 if options.Q:
208 options.QH = True
209 # If user has specified different file extensions
210 if options.custom_ext or os.environ.get('GOODVIBES_CUSTOM_EXT', ''):
211 custom_extensions = options.custom_ext.split(',') + os.environ.get('GOODVIBES_CUSTOM_EXT', '').split(',')
212 for ext in custom_extensions:
213 SUPPORTED_EXTENSIONS.add(ext.strip())
214
215 # Default value for inverting imaginary frequencies
216 if options.invert is True:
217 options.invert = -50.0
218 elif options.invert is not None and options.invert > 0:
219 options.invert = -1 * options.invert
220
221 # Build the command echo from the original CLI invocation.
222 # File-path positional args (often dozens of .log/.out files) are
223 # collapsed to a "<N files>" placeholder so the line stays readable.
224 file_args, flag_args = [], []
225 for arg in sys.argv[1:]:
226 if os.path.splitext(arg)[1].lower() in SUPPORTED_EXTENSIONS:
227 file_args.append(arg)
228 else:
229 flag_args.append(arg)
230 file_summary = f'<{len(file_args)} file{"" if len(file_args) == 1 else "s"}>' if file_args else ''
231 parts = ['o Requested: goodvibes']
232 if file_summary:
233 parts.append(file_summary)
234 parts.extend(flag_args)
235 command = ' '.join(parts)
236 print(command)
237
238 # Collect filenames from the unrecognized positional arguments
239 files = []
240 for elem in args:
241 if os.path.splitext(elem)[1].lower() not in SUPPORTED_EXTENSIONS:
242 continue
243 for file in glob(elem):
244 if options.spc is not None and options.spc != 'link' and f'_{options.spc}.' in file:
245 continue
246 files.append(file)
247 if options.spc is not None and options.spc != 'link':
248 name, _ = os.path.splitext(file)
249 if find_spc_file(name, options.spc) is None:
250 sys.exit("\nError! No SPC calculation file '{0}_{1}.(log|out)' found! "
251 "The --spc suffix must match the SPC filename exactly "
252 "(e.g. --spc def2_TZVP for filename_def2_TZVP.log), or specify "
253 "link job.\nFor help, use option '-h'\n".format(name, options.spc))
254
255 # Exclude files matching the --exclude glob pattern
256 if options.exclude:
257 from fnmatch import fnmatch
258 files = [f for f in files if not fnmatch(f, options.exclude)]
259 # Natural-sort so file order is deterministic across shells (some glob
260 # implementations don't sort) and conf_10 follows conf_9, not conf_1.
261 files.sort(key=natural_key)
262 return options, files
263
264
265 def resolve_scaling_factor(files, options, level_of_theory):
266 """Look up or validate the vibrational frequency scaling factor.
267
268 If the user provided --freq_scale_factor, log it. Otherwise, attempt automatic
269 lookup from the Truhlar database based on level of theory. Warns if multiple
270 levels of theory are found.
271
272 Parameters:
273 files (list): output file paths.
274 options (Namespace): parsed CLI options. Uses: freq_scale_factor, mm_freq_scale_factor, boltz, ee.
275 level_of_theory (list): level of theory strings, one per file.
276 """
277 if options.freq_scale_factor is not None:
278 if 'ONIOM' not in level_of_theory[0]:
279 log.info(f"\n User-defined vibrational scale factor {options.freq_scale_factor} for {level_of_theory[0]} level of theory")
280 else:
281 log.info(f"\n User-defined vibrational scale factor {options.freq_scale_factor} for QM region of {level_of_theory[0]}")
282 else:
283 # Look for vibrational scaling factor automatically. Truhlar's
284 # database provides separate harm_fac (for partition functions)
285 # and zpe_fac (for ZPE). When auto-detecting, use both; when the
286 # user supplied --vscal explicitly, ZPE inherits it unless they
287 # also passed --zpe-vscal (handled below).
288 if all_same(level_of_theory):
289 level = canonicalize_level(level_of_theory[0])
290 if level in scaling_data_dict:
291 entry = scaling_data_dict[level]
292 options.freq_scale_factor = entry.harm_fac
293 if options.zpe_scale_factor is None:
294 options.zpe_scale_factor = entry.zpe_fac
295 ref = scaling_refs[entry.harm_ref]
296 log.info("\n\no Found vibrational scaling factors of {:.3f} (harmonic, H/S) and "
297 "{:.3f} (ZPE) for {} level of theory\n {}".format(
298 entry.harm_fac, entry.zpe_fac, level_of_theory[0], ref))
299
300 # Warn if different levels of theory are found
301 if not all_same(level_of_theory):
302 print_check_fails(list(level_of_theory), list(files), "levels of theory")
303
304 # Exit program if a comparison of Boltzmann factors is requested and level of theory is not uniform across all files
305 if not all_same(level_of_theory) and (options.boltz or options.ee is not None):
306 sys.exit("\n\n ✗ FATAL ERROR: Boltzmann factors require all species computed at the same level of theory\n")
307
308 # Exit program if molecular mechanics scaling factor is given and all files are not ONIOM calculations
309 if options.mm_freq_scale_factor is not None:
310 if all_same(level_of_theory) and 'ONIOM' in level_of_theory[0]:
311 log.info(f"\n\n User-defined vibrational scale factor {options.mm_freq_scale_factor} for MM region of {level_of_theory[0]}")
312 log.info("\n {}".format(oniom_scale_ref))
313 else:
314 sys.exit("\n Option --vmm is only for use in ONIOM calculation output files.\n "
315 " help use option '-h'\n")
316
317 if options.freq_scale_factor is None:
318 options.freq_scale_factor = 1.0 # If no scaling factor is found use 1.0
319
320
321 def warn_orca_prescaled(files):
322 """Warn about ORCA files where pre-scaled frequencies were un-scaled."""
323 for file in files:
324 if file.endswith('.out'):
325 try:
326 # ORCA can emit non-UTF-8 bytes (paths, internal metadata);
327 # match the io.py parsers and replace bad bytes rather than
328 # crash on UnicodeDecodeError.
329 with open(file, encoding='utf-8', errors='replace') as f:
330 for line in f:
331 if 'Scaling factor for frequencies' in line and 'already applied' in line:
332 try:
333 factor = float(line.split('=')[1].split('(')[0].strip())
334 except (IndexError, ValueError):
335 factor = None
336 if factor is not None and factor != 1.0:
337 log.info("\n Caution! ORCA applied a frequency scaling factor of {:.6f} in {}. "
338 "Frequencies have been un-scaled to avoid double-scaling.".format(
339 factor, os.path.basename(file)))
340 break
341 except (IOError, OSError):
342 pass
343
344
345 def validate_and_configure(options, solvation_model):
346 """Validate solvent, print QH/QS configuration, and return (symm_option, vmm_option)."""
347 # Checks to see whether the available free space of a requested solvent is defined
348 if options.freespace is not None:
349 freespace = get_free_space(options.freespace)
350 if freespace != 1000.0:
351 log.info(f"\n Specified solvent {options.freespace}: free volume {freespace / 10.0:.3f} (mol/l) corrects the translational entropy")
352
353 # Check for implicit solvation
354 if any('smd' in i.lower() or 'cpcm' in i.lower() for i in solvation_model):
355 log.info("\n Caution! Implicit solvation (SMD/CPCM) detected. Enthalpic and entropic terms cannot be "
356 "safely separated. Use them at your own risk!")
357
358 if options.freq_cutoff != 100.0:
359 options.S_freq_cutoff = options.freq_cutoff
360 options.H_freq_cutoff = options.freq_cutoff
361
362 # Summary of the quasi-harmonic treatment; print out the relevant reference
363
364 if options.QS == "grimme":
365 if options.freq_scale_factor == 1.0:
366 log.info(f"\n\n ✔ Using mRRHO entropies with a frequency cut-off value (tau) of {options.S_freq_cutoff} cm-1")
367 qs_ref = grimme_mRRHO_ref
368 else:
369 log.info(f"\n\n ✔ Using msRRHO entropies with a frequency cut-off value (tau) of {options.S_freq_cutoff} cm-1")
370 qs_ref = grimme_msRRHO_ref
371
372 elif options.QS == "truhlar":
373 log.info(f"\n\n Using an RRHO treatment where low frequencies are adjusted to {options.S_freq_cutoff} cm-1")
374 qs_ref = truhlar_ref
375 else:
376 fatal("\n ✗ FATAL ERROR: Unknown quasi-harmonic model " + options.QS + " specified (QS must = grimme or truhlar).")
377 log.info("\n " + qs_ref)
378
379 # Check if qh-H correction should be applied
380 if options.QH:
381 log.info(f"\n\n ✔ Enthalpy quasi-harmonic treatment: frequency cut-off value of {options.H_freq_cutoff} wavenumbers will be applied.")
382 log.info("\n QH = Head-Gordon: Using an RRHO treatement with an approximation term for vibrational energy.")
383 qh_ref = head_gordon_ref
384 log.info("\n " + qh_ref + '\n')
385
386 # Check if entropy symmetry correction should be applied
387 if options.symm:
388 log.info('\n ✔ Point groups and symmetry numbers auto-detected using pymsym: https://github.com/corinwagen/pymsym')
389 else:
390 log.info('\n ✔ Point group symmetry parsed directly from outputs - caution if not provided or incorrect! Use --symm to auto-detect with pymsym')
391
392 # Whether single-point energies are to be used
393 if options.spc:
394 log.info("\n Combining final single point energy with thermal corrections.")
395 # Solvent correction message
396 if options.media:
397 log.info(f"\n ✔ Applying standard concentration correction (based on density at 20C) to {options.media} solvent.")
398
399
400 def _calc_bbe_worker(args):
401 """Top-level worker for ProcessPoolExecutor (must be picklable, hence
402 not a closure). Takes (file, conc, qcdata, opts_dict) and returns
403 a calc_bbe instance via the v5.0 from_options entry point."""
404 from .thermo import ThermoOptions
405 file, conc, cached_qcdata, opts = args
406 options = ThermoOptions(
407 QS=opts['QS'], QH=opts['QH'],
408 s_freq_cutoff=opts['S_freq_cutoff'],
409 h_freq_cutoff=opts['H_freq_cutoff'],
410 temperature=opts['temperature'],
411 concentration=conc,
412 freq_scale_factor=opts['freq_scale_factor'],
413 zpe_scale_factor=opts.get('zpe_scale_factor'),
414 solv=opts['freespace'],
415 spc=opts['spc'], invert=opts['invert'],
416 symm=opts['symm'],
417 mm_freq_scale_factor=opts['mm_freq_scale_factor'],
418 inertia=opts['inertia'],
419 )
420 return calc_bbe.from_options(cached_qcdata if cached_qcdata is not None else file, options)
421
422
423 def compute_thermochem(files, options, qcdata_cache=None):
424 """Run calc_bbe for each file and collect results.
425
426 For files matching the --media solvent name, the neat solvent concentration
427 is used instead of options.conc. Parallelized across `options.jobs`
428 worker processes when `>1`; sequential otherwise.
429
430 Parameters:
431 files (list): output file paths.
432 options (Namespace): parsed CLI options. Uses: QS, QH, S_freq_cutoff,
433 H_freq_cutoff, temperature, conc, freq_scale_factor, freespace,
434 spc, invert, symm, mm_freq_scale_factor, inertia, media, jobs.
435 qcdata_cache (dict, optional): pre-parsed QCData keyed by basename.
436
437 Returns:
438 dict: file path → calc_bbe mapping (thermo_data).
439 """
440 # Build per-file argument tuples sequentially (cheap; only the actual
441 # calc_bbe work is parallelized).
442 opts_dict = {
443 'QS': options.QS, 'QH': options.QH,
444 'S_freq_cutoff': options.S_freq_cutoff,
445 'h_freq_cutoff': options.H_freq_cutoff,
446 'H_freq_cutoff': options.H_freq_cutoff,
447 'temperature': options.temperature,
448 'freq_scale_factor': options.freq_scale_factor,
449 'zpe_scale_factor': getattr(options, 'zpe_scale_factor', None),
450 'freespace': options.freespace,
451 'spc': options.spc, 'invert': options.invert,
452 'symm': options.symm,
453 'mm_freq_scale_factor': options.mm_freq_scale_factor,
454 'inertia': options.inertia,
455 }
456 default_conc = options.conc if options.conc else ATMOS / (GAS_CONSTANT * options.temperature)
457 per_file_args = []
458 for file in files:
459 cached_qcdata = None
460 if qcdata_cache is not None:
461 key = os.path.splitext(os.path.basename(file))[0]
462 cached_qcdata = qcdata_cache.get(key)
463 conc = default_conc
464 if options.media:
465 media_conc = compute_media_conc(options.media, file)
466 if media_conc is not None:
467 conc = media_conc
468 per_file_args.append((file, conc, cached_qcdata, opts_dict))
469
470 jobs = getattr(options, 'jobs', 1) or 1
471 if jobs <= 0:
472 jobs = os.cpu_count() or 1
473
474 if jobs == 1 or len(files) <= 1:
475 bbe_vals = [_calc_bbe_worker(args) for args in per_file_args]
476 else:
477 from concurrent.futures import ProcessPoolExecutor
478 with ProcessPoolExecutor(max_workers=jobs) as ex:
479 bbe_vals = list(ex.map(_calc_bbe_worker, per_file_args))
480
481 return dict(zip(files, bbe_vals))
482
483
484 def main():
485 """CLI entry point: parse arguments, compute thermochemistry, and print results."""
486 options, files = parse_arguments()
487
488 # Start logger
489 setup_logging("GoodVibes", options.output)
490
491 # Print banner
492 log.info(gv_banner)
493
494 # Fail fast on unknown solvent names — let the user fix the typo before we
495 # parse a thousand files.
496 if options.media is not None:
497 try:
498 lookup_solvent(options.media)
499 except ValueError as exc:
500 fatal(f"\n ✗ FATAL ERROR: {exc}")
501 if options.freespace is not None and options.freespace not in FREESPACE_SOLVENTS:
502 fatal(
503 f"\n ✗ FATAL ERROR: Unknown --freespace solvent {options.freespace!r}. "
504 f"Supported (case-sensitive): {', '.join(FREESPACE_SOLVENTS)}."
505 )
506
507 # Selectivity spec: parse --label and --selectivity into a label_patterns
508 # / label_files dict before any heavy work, so typos fail immediately.
509 label_patterns, label_files = None, None
510 if options.labels and options.selectivity_spec:
511 fatal("\n ✗ FATAL ERROR: --label and --selectivity are mutually exclusive.")
512 if options.ee is not None and (options.labels or options.selectivity_spec):
513 fatal("\n ✗ FATAL ERROR: --ee is incompatible with --label / --selectivity. "
514 "Use one selectivity API at a time.")
515 if options.labels:
516 try:
517 label_patterns = parse_label_args(options.labels)
518 except ValueError as exc:
519 fatal(f"\n ✗ FATAL ERROR: {exc}")
520 elif options.selectivity_spec:
521 try:
522 mode, spec = load_label_yaml(options.selectivity_spec)
523 except (ValueError, RuntimeError, FileNotFoundError, OSError) as exc:
524 fatal(f"\n ✗ FATAL ERROR: {exc}")
525 if mode == 'patterns':
526 label_patterns = spec
527 else:
528 label_files = spec
529
530 # --cache-read is deprecated in v5.0 in favor of --import; redirect with a
531 # one-time warning. --cache-save likewise → --export.
532 if options.cache_read is not None:
533 import warnings
534 warnings.warn(
535 "--cache-read is deprecated; use --import instead. Both accept "
536 "v1.0 JSON payloads and legacy cache envelopes.",
537 DeprecationWarning, stacklevel=2,
538 )
539 if options.import_path is None:
540 options.import_path = options.cache_read
541 if options.cache_save is not None:
542 import warnings
543 warnings.warn(
544 "--cache-save is deprecated; use --export instead (or --json, "
545 "which is the same writer).",
546 DeprecationWarning, stacklevel=2,
547 )
548 if options.export_path is None:
549 options.export_path = options.cache_save
550 options.cache_save = None # legacy save_cache block below skipped
551 # --export is just a synonym for --json; if both are set, --json wins so
552 # explicit --json scripts keep working unchanged.
553 if options.export_path is not None and options.json_path is None:
554 options.json_path = options.export_path
555
556 # Load QCData cache early if requested (needed to determine file list in cache-only mode)
557 qcdata_cache = None
558 cache_only = False
559 if options.import_path:
560 qcdata_cache = load_cache(options.import_path)
561 if not files:
562 # Cache-only mode: derive file list from cache entries
563 cache_only = True
564 files = [key + '.cache' for key in qcdata_cache]
565
566 # Check if user has specified any files
567 if not files:
568 sys.exit("\n! Specify at least one output files on the command line ¯\\_(ツ)_/¯ \n")
569
570 # log.info('\n' + command + '\n')
571 if options.temperature_interval is None:
572 log.info(f" Temperature = {options.temperature} Kelvin")
573
574 # Concentration / pressure
575 if options.conc:
576 log.info(f" Concentration = {options.conc} mol/L")
577 else:
578 log.info(" Pressure = 1 atm")
579
580 if cache_only:
581 # Cache-only mode: skip file validation (no output files on disk)
582 level_of_theory, solvation_model = [], []
583 for key, qcdata in qcdata_cache.items():
584 level_of_theory.append('')
585 # solvation_model may be a string or a list [sorted, display] depending on parser
586 sm = qcdata.solvation_model
587 if isinstance(sm, list):
588 sm = sm[0]
589 solvation_model.append(sm)
590 if options.freq_scale_factor is None:
591 options.freq_scale_factor = 1.0
592 log.info("\n Reading from QCData cache: " + options.import_path)
593 else:
594 # Collect file data and validate
595 files, level_of_theory, solvation_model = collect_and_validate_files(files, options)
596 # Resolve frequency scaling factor
597 resolve_scaling_factor(files, options, level_of_theory)
598 if options.import_path:
599 log.info("\n Loaded QCData cache from " + options.import_path)
600
601 # Warn about ORCA files if pre-scaled frequencies were un-scaled
602 warn_orca_prescaled(files)
603
604 # Validate options, configure and print
605 validate_and_configure(options, solvation_model)
606
607 # Compute thermochemistry for all files
608 thermo_data = compute_thermochem(files, options, qcdata_cache=qcdata_cache)
609
610 # Media concentration for display in output (the per-file conc override is handled in compute_thermochem)
611 media_conc = None
612 if options.media and options.media.lower() in solvents:
613 mweight, density = solvents[options.media.lower()]
614 media_conc = (density * 1000) / mweight
615
616 # Save QCData cache if requested
617 if options.cache_save:
618 cache_dict = {}
619 for file, bbe in thermo_data.items():
620 key = os.path.splitext(os.path.basename(file))[0]
621 if hasattr(bbe, 'xyz') and bbe.xyz is not None:
622 cache_dict[key] = qcdata_to_dict(bbe.xyz)
623 save_cache(cache_dict, options.cache_save)
624 log.info("\n Saved QCData cache to " + options.cache_save)
625
626 # Sort output if requested
627 if options.sort:
628 thermo_data = sort_thermo(thermo_data, options.sort)
629
630 # Deduplicate structures if requested (needed for both standard and PES output)
631 dup_list = deduplicate(thermo_data, e_cutoff=options.e_cutoff,
632 ro_cutoff=options.ro_cutoff,
633 rmsd_cutoff=options.rmsd_cutoff) if options.duplicate else []
634
635 # Compute Boltzmann factors once (used by --boltz display and --ee selectivity)
636 boltz_facs = None
637 if options.boltz or options.ee is not None:
638 boltz_key = options.boltz if options.boltz else 'gibbs'
639 boltz_facs = get_boltz(thermo_data, options.temperature, dup_list, key=boltz_key)
640
641 # Selectivity (new --label / --selectivity API). Computed once for
642 # single-T mode; one entry per temperature in --ti scan mode. Two
643 # methods are computed side-by-side: Boltzmann-averaged across all
644 # conformers in each species, and lowest-conformer-only.
645 selectivity_results = None
646 selectivity_lowest_results = None
647 if label_patterns is not None or label_files is not None:
648 if label_patterns is not None:
649 files_per_label = assign_files_to_labels(list(thermo_data), label_patterns)
650 else:
651 files_per_label = label_files
652 sel_key = options.boltz if options.boltz else 'gibbs'
653 try:
654 if options.temperature_interval is None:
655 selectivity_results = [compute_selectivity(
656 thermo_data, files_per_label, options.temperature,
657 dup_list=dup_list, key=sel_key)]
658 selectivity_lowest_results = [compute_selectivity_lowest_only(
659 thermo_data, files_per_label, options.temperature,
660 dup_list=dup_list, key=sel_key)]
661 else:
662 # Mirror print_temperature_interval's parsing of --ti.
663 ti = [float(x) for x in options.temperature_interval.split(',')]
664 if len(ti) == 2:
665 ti.append((ti[1] - ti[0]) / 10.0)
666 temps = list(range(int(ti[0]), int(ti[1]) + 1, int(ti[2])))
667 selectivity_results = compute_selectivity_scan(
668 thermo_data, files_per_label, temps,
669 dup_list=dup_list, key=sel_key)
670 selectivity_lowest_results = compute_selectivity_lowest_only_scan(
671 thermo_data, files_per_label, temps,
672 dup_list=dup_list, key=sel_key)
673 except ValueError as exc:
674 fatal(f"\n ✗ FATAL ERROR: {exc}")
675
676 # Variables populated by temperature-interval mode, used by PES
677 interval_bbe_data, interval, file_list = None, None, None
678
679 # Standard mode: single temperature
680 if options.temperature_interval is None:
681 print_results(thermo_data, options, media_conc=media_conc,
682 dup_list=dup_list, boltz_facs=boltz_facs)
683 if selectivity_results is not None:
684 print_selectivity_results({
685 'Boltzmann-averaged': selectivity_results,
686 'Lowest conformer only': selectivity_lowest_results,
687 })
688
689 # PES: build the v4.2 model once for single-T mode so we can pass it
690 # to both the Rich table renderer and the JSON writer. T-interval mode
691 # still flows through the legacy print_pes_results below.
692 pes_result = None
693 if options.pes and options.temperature_interval is None:
694 from .pes_loader import load_pes
695 pes_result = load_pes(options.pes, thermo_data,
696 temperatures=[options.temperature])
697
698 # Structured (JSON) output — v1.0 stable schema. Additive; runs
699 # alongside the .dat output.
700 if options.json_path:
701 # JSON write fires in both single-T and T-interval modes. In
702 # T-interval mode the per-file thermo numbers reflect the base
703 # temperature only; the temperature_interval value is recorded
704 # in `options` for downstream consumers to scan.
705 media_conc_per_file = {}
706 if options.media:
707 for file in thermo_data:
708 mc = compute_media_conc(options.media, file)
709 if mc is not None:
710 media_conc_per_file[file] = mc
711 write_json_results(thermo_data, options, options.json_path,
712 media_conc_per_file=media_conc_per_file,
713 boltz_facs=boltz_facs,
714 selectivity_results=selectivity_results,
715 selectivity_lowest_results=selectivity_lowest_results,
716 pes_result=pes_result)
717
718 # CSV / Parquet exports (single-T only; one row per structure,
719 # ThermoResult columns). Pandas is in the optional `[full]` extras;
720 # Parquet additionally needs pyarrow. Build the ThermoResult list
721 # once and reuse for both formats.
722 if (options.csv_path or options.parquet_path) and options.temperature_interval is None:
723 from .api import bbe_to_result, to_dataframe, to_parquet
724 try:
725 results = [bbe_to_result(bbe, file) for file, bbe in thermo_data.items()]
726 if options.csv_path:
727 to_dataframe(results).to_csv(options.csv_path, index=False)
728 log.info(f"\n ✔ CSV written to {options.csv_path}")
729 if options.parquet_path:
730 to_parquet(results, options.parquet_path)
731 log.info(f"\n ✔ Parquet written to {options.parquet_path}")
732 except ImportError as exc:
733 fatal(str(exc))
734
735 # Selectivity strip plot — needs a SelectivityResult and a
736 # {file: qh_g} lookup. matplotlib via `goodvibes[plot]`.
737 if options.strip_plot_path:
738 if selectivity_results is None or not selectivity_results:
739 fatal("--strip-plot requires --label or --selectivity to define species buckets.")
740 try:
741 from .plot import plot_selectivity_strip
742 except ImportError as exc:
743 fatal(str(exc))
744 # Use the single-T (or first-T-in-scan) selectivity result.
745 sel = selectivity_results[0]
746 thermo_lookup = {f: bbe.qh_gibbs_free_energy for f, bbe in thermo_data.items()}
747 ax = plot_selectivity_strip(sel, thermo_lookup)
748 ax.figure.savefig(options.strip_plot_path, dpi=200, bbox_inches="tight")
749 log.info(f"\n ✔ Strip plot written to {options.strip_plot_path}\n")
750
751 # PES profile diagram — clean v5.0 plot driven by PESResult.
752 # Reuses the pes_result that was built earlier for the Rich
753 # tables / JSON in single-T mode. matplotlib via `goodvibes[plot]`.
754 if options.pes_plot_path:
755 if pes_result is None:
756 fatal("--pes-plot requires --pes (a reaction pathway YAML) to define the profile.")
757 try:
758 from .plot import plot_pes
759 except ImportError as exc:
760 fatal(str(exc))
761 ax = plot_pes(pes_result)
762 ax.figure.savefig(options.pes_plot_path, dpi=200, bbox_inches="tight")
763 log.info(f"\n ✔ PES plot written to {options.pes_plot_path}\n")
764
765 # Legacy --graph FILE.yaml: the busier matplotlib reaction profile
766 # (bezier connectors, jitter overlays, YAML-driven styling). The
767 # styling YAML can be the same file as --pes — both blocks
768 # (`--- # PES` and `--- # FORMAT`) coexist. Wired here in main()
769 # because v4.2's single-T path doesn't call print_pes_results,
770 # which is where this used to live.
771 if options.graph is not None:
772 try:
773 import matplotlib.pyplot as plt
774 except ImportError:
775 fatal("--graph requires matplotlib. Install with `pip install goodvibes[plot]`.")
776 from .pes import get_pes, graph_reaction_profile
777 graph_data = get_pes(options.graph, thermo_data,
778 options.temperature, options.gconf, options.QH)
779 graph_reaction_profile(graph_data, options, plt)
780
781 # Perform checks for consistent options
782 if options.check:
783 check_files(thermo_data, options, level_of_theory)
784
785 # Variable temperature analysis
786 elif options.temperature_interval:
787 print_temperature_interval(thermo_data, options, media_conc=media_conc, qcdata_cache=qcdata_cache)
788 if selectivity_results is not None:
789 print_selectivity_results({
790 'Boltzmann-averaged': selectivity_results,
791 'Lowest conformer only': selectivity_lowest_results,
792 })
793
794 # Print CPU usage if requested
795 if options.cputime:
796 print_cpu_time(thermo_data, options.exclude)
797
798 # Tabulate relative values (PES). New Rich table renderer for the
799 # single-T case; T-interval still uses the legacy text path.
800 if options.pes:
801 if options.temperature_interval is None:
802 from .output import print_pes_tables
803 print_pes_tables(pes_result, options, temperature=options.temperature)
804 else:
805 print_pes_results(thermo_data, options, dup_list,
806 boltz_facs=boltz_facs,
807 interval_bbe_data=interval_bbe_data,
808 interval=interval, file_list=file_list)
809
810 # Close the log
811 logging.shutdown()
812
813 # Write xyz file if requested
814 if options.xyz:
815 write_xyz("GoodVibes_"+options.output+".xyz", files, thermo_data)
816 log.info(" ✔ Cartesian coordinates written to GoodVibes_"+options.output+".xyz\n")
817
818
819 if __name__ == "__main__":
820 main()