Debian Codegraph @

goodvibes/io.py

raw
1 # -*- coding: utf-8 -*-
2 import json
3 import os.path
4 import re
5 from dataclasses import asdict, dataclass, field
6 from datetime import datetime
7 from typing import List, Optional
8
9 import numpy as np
10
11
12
13 @dataclass
14 class QCData:
15 """Program-agnostic container for parsed quantum chemistry data.
16
17 Populated by parse_qcdata() in io.py. Consumed by calc_bbe in thermo.py.
18 """
19 # Provenance
20 file: str = ''
21 program: str = ''
22 version_program: str = ''
23 job_type: str = ''
24
25 # Electronic structure
26 scf_energy: Optional[float] = None
27 charge: Optional[int] = None
28 multiplicity: int = 1
29
30 # Model chemistry metadata
31 solvation_model: str = ''
32 empirical_dispersion: str = ''
33
34 # Molecular properties
35 molecular_mass: float = 0.0
36 symmno: int = 1
37 linear_mol: bool = False
38 point_group: str = ''
39
40 # Rotational data
41 roconst: List[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])
42 rotemp: List[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])
43 linear_warning: bool = False
44
45 # Frequencies (raw from parser — positive and negative separated)
46 frequency_wn: List[float] = field(default_factory=list)
47 im_frequency_wn: List[float] = field(default_factory=list)
48
49 # Thermal corrections
50 zero_point_corr: Optional[float] = None
51
52 # CPU time [days, hours, mins, secs, msecs]
53 cpu: List[int] = field(default_factory=lambda: [0, 0, 0, 0, 0])
54
55 # Number of MPI processes / cores reported by the QC program. Used by
56 # the ORCA parser to convert TOTAL RUN TIME (wall) into an effective
57 # CPU-time estimate (wall × nprocs); 1 elsewhere.
58 nprocs: int = 1
59
60 # ONIOM MM frequency scaling fractions (per-frequency, empty if not ONIOM)
61 fract_modelsys: List[float] = field(default_factory=list)
62 has_oniom: bool = False
63
64 # Molecular geometry
65 atom_nums: List[int] = field(default_factory=list)
66 atom_types: List[str] = field(default_factory=list)
67 cartesians: List[List[float]] = field(default_factory=list)
68
69 # Frequency scaling factor applied by QC program (ORCA only; 1.0 means unscaled)
70 applied_freq_scale_factor: float = 1.0
71
72 # Single-point-correction (SPC) cache. Populated by calc_bbe when --spc
73 # is used so the SPC file isn't re-parsed on subsequent --import runs.
74 # `sp_suffix` is the --spc value that produced the cached numbers; on
75 # a re-run with the same suffix the cache is reused, on a different
76 # suffix it's bypassed and refreshed. `sp_file` is the resolved
77 # absolute path of the SPC output (diagnostic only).
78 sp_energy: Optional[float] = None
79 sp_version_program: str = ''
80 sp_solvation_model: str = ''
81 sp_charge: Optional[int] = None
82 sp_empirical_dispersion: str = ''
83 sp_multiplicity: Optional[int] = None
84 sp_suffix: str = ''
85 sp_file: str = ''
86
87
88 # Cache version for JSON serialization format
89 CACHE_VERSION = 1
90
91
92 def qcdata_to_dict(qcdata):
93 """Convert a QCData instance to a JSON-serializable dictionary."""
94 d = asdict(qcdata)
95 d['_cache_version'] = CACHE_VERSION
96 return d
97
98
99 def dict_to_qcdata(d):
100 """Reconstruct a QCData instance from a dictionary."""
101 clean = {k: v for k, v in d.items() if not k.startswith('_')}
102 return QCData(**clean)
103
104
105 def save_cache(cache_dict, path):
106 """Write QCData cache to a JSON file.
107
108 Parameters
109 ----------
110 cache_dict : dict
111 Mapping of {basename_key: qcdata_dict} where each value is from qcdata_to_dict().
112 path : str
113 Output JSON file path.
114 """
115 envelope = {
116 '_cache_version': CACHE_VERSION,
117 '_created': datetime.now().isoformat(),
118 'entries': cache_dict,
119 }
120 with open(path, 'w') as f:
121 json.dump(envelope, f, indent=2)
122
123
124 def load_cache(path):
125 """Load a QCData cache from a JSON file.
126
127 Auto-detects the format. v1.0+ payloads (the unified schema written
128 by `--export` / `--json`) are read by extracting each result's
129 `qcdata` block; the legacy cache envelope (`{_cache_version, entries}`,
130 written by pre-v5.0 `--cache-save`) is also accepted for back-compat.
131
132 Parameters
133 ----------
134 path : str
135 Path to JSON file (either v1.0 unified schema or legacy cache).
136
137 Returns
138 -------
139 dict
140 Mapping of {basename_key: QCData}.
141 """
142 with open(path, 'r') as f:
143 data = json.load(f)
144 if 'schema_version' in data:
145 # Unified v1.0+ payload — use each result's qcdata block.
146 from .schema import validate
147 validate(data)
148 cache = {}
149 for entry in data.get('results', []):
150 qc = entry.get('qcdata')
151 if qc is None:
152 continue
153 name = entry.get('name')
154 if name is None:
155 # Fall back to deriving from the file path.
156 fp = entry.get('file', '')
157 name = os.path.splitext(os.path.basename(fp))[0]
158 cache[name] = dict_to_qcdata(qc)
159 return cache
160 # Legacy envelope: {_cache_version, _created, entries}
161 version = data.get('_cache_version', 0)
162 if version != CACHE_VERSION:
163 raise ValueError(
164 "Cache version mismatch: expected {} (legacy) or a v1.0+ "
165 "schema_version, got _cache_version={}".format(CACHE_VERSION, version)
166 )
167 return {key: dict_to_qcdata(val) for key, val in data['entries'].items()}
168
169
170 # PHYSICAL CONSTANTS UNITS
171 KCAL_TO_AU = 627.509541 # UNIT CONVERSION
172
173 # Radii used to determine connectivity in symmetry corrections
174 # Covalent radii taken from Cambridge Structural Database
175 RADII = {'H': 0.32, 'He': 0.93, 'Li': 1.23, 'Be': 0.90, 'B': 0.82, 'C': 0.77, 'N': 0.75, 'O': 0.73, 'F': 0.72,
176 'Ne': 0.71, 'Na': 1.54, 'Mg': 1.36, 'Al': 1.18, 'Si': 1.11, 'P': 1.06, 'S': 1.02, 'Cl': 0.99, 'Ar': 0.98,
177 'K': 2.03, 'Ca': 1.74, 'Sc': 1.44, 'Ti': 1.32, 'V': 1.22, 'Cr': 1.18, 'Mn': 1.17, 'Fe': 1.17, 'Co': 1.16,
178 'Ni': 1.15, 'Cu': 1.17, 'Zn': 1.25, 'Ga': 1.26, 'Ge': 1.22, 'As': 1.20, 'Se': 1.16, 'Br': 1.14, 'Kr': 1.12,
179 'Rb': 2.16, 'Sr': 1.91, 'Y': 1.62, 'Zr': 1.45, 'Nb': 1.34, 'Mo': 1.30, 'Tc': 1.27, 'Ru': 1.25, 'Rh': 1.25,
180 'Pd': 1.28, 'Ag': 1.34, 'Cd': 1.48, 'In': 1.44, 'Sn': 1.41, 'Sb': 1.40, 'Te': 1.36, 'I': 1.33, 'Xe': 1.31,
181 'Cs': 2.35, 'Ba': 1.98, 'La': 1.69, 'Lu': 1.60, 'Hf': 1.44, 'Ta': 1.34, 'W': 1.30, 'Re': 1.28, 'Os': 1.26,
182 'Ir': 1.27, 'Pt': 1.30, 'Au': 1.34, 'Hg': 1.49, 'Tl': 1.48, 'Pb': 1.47, 'Bi': 1.46, 'X': 0}
183 # Bondi van der Waals radii for all atoms from: Bondi, A. J. Phys. Chem. 1964, 68, 441-452,
184 # except hydrogen, which is taken from Rowland, R. S.; Taylor, R. J. Phys. Chem. 1996, 100, 7384-7391.
185 # Radii unavailable in either of these publications are set to 2 Angstrom
186 # (Unfinished)
187 BONDI = {'H': 1.09, 'He': 1.40, 'Li': 1.82, 'Be': 2.00, 'B': 2.00, 'C': 1.70, 'N': 1.55, 'O': 1.52, 'F': 1.47,
188 'Ne': 1.54}
189
190 # Some useful arrays
191 periodictable = ["", "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si",
192 "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn",
193 "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd",
194 "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm",
195 "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt",
196 "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu",
197 "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds",
198 "Rg", "Uub", "Uut", "Uuq", "Uup", "Uuh", "Uus", "Uuo"]
199
200 def element_id(massno, num=False):
201 """
202 Get element symbol from mass number.
203
204 Used in parsing output files to determine elements present in file.
205
206 Parameter:
207 massno (int): mass of element.
208
209 Returns:
210 str: element symbol, or 'XX' if not found in periodic table.
211 """
212 try:
213 if num:
214 return periodictable.index(massno)
215 return periodictable[massno]
216 except IndexError:
217 return "XX"
218
219
220 # Standard atomic weights (IUPAC 2021), most common isotope where applicable.
221 # Used by parse_ase_thermo when an extxyz fixture omits molecular_mass / rotational
222 # constants and they must be computed from the geometry.
223 ATOMIC_MASSES = {
224 'H': 1.00782503207, 'He': 4.002602,
225 'Li': 7.0160034366, 'Be': 9.012183065, 'B': 11.00930536, 'C': 12.0,
226 'N': 14.0030740048, 'O': 15.99491461957, 'F': 18.998403163, 'Ne': 19.9924401762,
227 'Na': 22.9897692820, 'Mg': 23.985041697, 'Al': 26.98153853, 'Si': 27.97692653465,
228 'P': 30.97376199842, 'S': 31.9720711744, 'Cl': 34.968852682, 'Ar': 39.9623831237,
229 'K': 38.96370648, 'Ca': 39.96259098, 'Sc': 44.95590828, 'Ti': 47.94794198,
230 'V': 50.94395704, 'Cr': 51.94050623, 'Mn': 54.93804451, 'Fe': 55.93493633,
231 'Co': 58.93319429, 'Ni': 57.93534241, 'Cu': 62.92959772, 'Zn': 63.92914201,
232 'Ga': 68.9255735, 'Ge': 73.921177761, 'As': 74.92159457, 'Se': 79.9165218,
233 'Br': 78.9183376, 'Kr': 83.9114977282,
234 'Rb': 84.91178974, 'Sr': 87.9056125, 'Y': 88.9058403, 'Zr': 89.9046977,
235 'Nb': 92.906373, 'Mo': 97.90540482, 'Tc': 98.9062508, 'Ru': 101.9043441,
236 'Rh': 102.905498, 'Pd': 105.9034804, 'Ag': 106.9050916, 'Cd': 113.90336509,
237 'In': 114.903878776, 'Sn': 119.90220163, 'Sb': 120.903812, 'Te': 129.906222748,
238 'I': 126.9044719, 'Xe': 131.9041550856,
239 }
240
241
242 def _principal_moments_of_inertia(atom_types, cartesians):
243 """Return (total_mass [amu], [I_a, I_b, I_c] in amu*Angstrom^2).
244
245 Used as a fallback when an extxyz fixture omits molecular_mass / roconst /
246 rotemp; computes them from the geometry using ATOMIC_MASSES.
247 """
248 masses = np.array([ATOMIC_MASSES.get(a, 0.0) for a in atom_types])
249 coords = np.array(cartesians, dtype=float)
250 total = float(masses.sum())
251 if total <= 0.0 or len(coords) == 0:
252 return total, np.array([0.0, 0.0, 0.0])
253 com = (masses[:, None] * coords).sum(axis=0) / total
254 r = coords - com
255 Ixx = float((masses * (r[:, 1] ** 2 + r[:, 2] ** 2)).sum())
256 Iyy = float((masses * (r[:, 0] ** 2 + r[:, 2] ** 2)).sum())
257 Izz = float((masses * (r[:, 0] ** 2 + r[:, 1] ** 2)).sum())
258 Ixy = float(-(masses * r[:, 0] * r[:, 1]).sum())
259 Ixz = float(-(masses * r[:, 0] * r[:, 2]).sum())
260 Iyz = float(-(masses * r[:, 1] * r[:, 2]).sum())
261 inertia = np.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])
262 eigvals = np.linalg.eigvalsh(inertia)
263 eigvals = np.sort(np.maximum(eigvals, 0.0))
264 return total, eigvals
265
266 def compute_connectivity(atom_types, cartesians, tolerance=0.2):
267 """Compute molecular connectivity based on covalent radii."""
268 connectivity = []
269 for i, ai in enumerate(atom_types):
270 row = []
271 for j, aj in enumerate(atom_types):
272 if i == j:
273 continue
274 cutoff = RADII[ai] + RADII[aj] + tolerance
275 distance = np.linalg.norm(np.array(cartesians[i]) - np.array(cartesians[j]))
276 if distance < cutoff:
277 row.append(j)
278 connectivity.append(row)
279 return connectivity
280
281 def write_xyz(filepath, files, thermo_data):
282 """Write optimized Cartesian coordinates to a multi-structure .xyz file.
283
284 Each structure block contains the atom count, a comment line with the
285 filename and SCF energy, and the Cartesian coordinates.
286
287 Parameters:
288 filepath (str): output .xyz file path.
289 files (list): output file paths whose coordinates to write.
290 thermo_data (dict): file path → calc_bbe mapping.
291 """
292 from .utils import display_name
293 with open(filepath, 'w') as f:
294 for file in files:
295 bbe = thermo_data[file]
296 f.write(f'{len(bbe.atom_types)}\n')
297 if bbe.scf_energy is not None:
298 f.write(f'{display_name(file):<39} {"Eopt":>13} {bbe.scf_energy:.6f}\n')
299 else:
300 f.write(f'{display_name(file):<39}\n')
301 if bbe.atom_types and bbe.cartesians:
302 for atom, carts in zip(bbe.atom_types, bbe.cartesians):
303 f.write(f'{atom:>1}{carts[0]:13.6f}{carts[1]:13.6f}{carts[2]:13.6f}\n')
304
305 def find_spc_file(name, spc):
306 """Locate the single-point-correction output paired with ``name``.
307
308 Pattern matched: ``{name}_{spc}.{log,out}`` — exact match. ``--spc TZVP``
309 finds ``filename_TZVP.log`` only; it will NOT match ``filename_def2_TZVP.log``.
310 To pair with a file like ``filename_def2_TZVP.log``, pass the full suffix
311 (``--spc def2_TZVP``).
312
313 Parameters
314 ----------
315 name : str
316 Path stem of the parent output file (no extension).
317 spc : str
318 Suffix passed via ``--spc``.
319
320 Returns
321 -------
322 str or None
323 Path to the matching file, or None if nothing matches.
324 """
325 for ext in ('.log', '.out'):
326 candidate = f'{name}_{spc}{ext}'
327 if os.path.isfile(candidate):
328 return candidate
329 return None
330
331
332 def parse_data(file):
333 """
334 Read computational chemistry output file.
335
336 Attempt to obtain single point energy, program type, program version, solvation_model,
337 charge, empirical_dispersion, and multiplicity from file.
338
339 Parameter:
340 file (str): name of file to be parsed.
341
342 Returns:
343 float: single point energy.
344 str: program used to run calculation.
345 str: version of program used to run calculation.
346 str: solvation model used in chemical calculation (if any).
347 str: original filename parsed.
348 int: overall charge of molecule or chemical system.
349 str: empirical dispersion used in chemical calculation (if any).
350 int: multiplicity of molecule or chemical system.
351 """
352 spe, program, data, version_program, solvation_model, keyword_line, a, charge, multiplicity = 'none', 'none', [], '', '', '', 0, None, None
353
354 data = None
355 stub = os.path.splitext(file)[0]
356 possible_filenames = (stub + ".log", stub + ".out", stub + ".extxyz", file)
357 actual_file = file
358 for possible_filename in possible_filenames:
359 if os.path.exists(possible_filename):
360 actual_file = possible_filename
361 with open(possible_filename, encoding='utf-8', errors='replace') as f:
362 data = f.readlines()
363 break
364
365 if data is None:
366 raise ValueError("File {} does not exist".format(file))
367
368 # ASE extxyz: delegate to parse_ase_thermo and translate to parse_data's
369 # tuple shape; ASE files have no separate single-point semantics.
370 if len(data) >= 2 and 'program=ase' in data[1]:
371 q = parse_ase_thermo(actual_file)
372 return (q.scf_energy if q.scf_energy is not None else 'none',
373 'ase',
374 q.version_program,
375 q.solvation_model or 'gas phase',
376 file,
377 q.charge if q.charge is not None else 0,
378 q.empirical_dispersion or 'No empirical dispersion detected',
379 q.multiplicity)
380
381 # Q-Chem: delegate to parse_qchem_thermo (Q-Chem energy lines, MP2/CCSD
382 # precedence, and $molecule echo are all already handled there).
383 if any('You are running Q-Chem' in ln or 'Welcome to Q-Chem' in ln for ln in data[:80]):
384 q = parse_qchem_thermo(actual_file)
385 return (q.scf_energy if q.scf_energy is not None else 'none',
386 'QChem',
387 q.version_program,
388 q.solvation_model or 'gas phase',
389 file,
390 q.charge if q.charge is not None else 0,
391 q.empirical_dispersion or 'No empirical dispersion detected',
392 q.multiplicity)
393
394 for line in data:
395 if "Gaussian" in line:
396 program = "Gaussian"
397 break
398 if "* O R C A *" in line:
399 program = "Orca"
400 break
401 if "NWChem" in line:
402 program = "NWChem"
403 break
404 if "x T B" in line or "xtb version" in line:
405 program = "xtb"
406 break
407 repeated_link1 = 0
408 freq_started = False # Guard against VPT2 displaced geometry energies
409 zero_point_corr_G4 = 0.0
410
411 for line in data:
412 if program == "Gaussian":
413 # Reset freq_started at each new link (linked jobs have separate links)
414 if 'Normal termination' in line:
415 freq_started = False
416 if line.strip().startswith('Frequencies -- '):
417 freq_started = True
418 if not freq_started and line.strip().startswith('SCF Done:'):
419 spe = float(line.strip().split()[4])
420 elif not freq_started and line.strip().startswith('E2('):
421 spe_value = line.strip().split()[-1]
422 spe = float(spe_value.replace('D','E'))
423 elif not freq_started and 'EUMP2 =' in line.strip():
424 spe = float((line.strip().split()[5]).replace('D', 'E'))
425 elif 'CCSD(T)=' in line.strip():
426 raw = line.strip().split('CCSD(T)=')[1].split('\\')[0].split()[0]
427 spe = float(raw.replace('D', 'E'))
428 elif 'CCSD=' in line.strip() and 'CCSD(T)' not in line.strip():
429 raw = line.strip().split('CCSD=')[1].split('\\')[0].split()[0]
430 spe = float(raw.replace('D', 'E'))
431 elif line.strip().startswith('Counterpoise corrected energy'):
432 spe = float(line.strip().split()[4])
433 # For ONIOM calculations use the extrapolated value rather than SCF value
434 elif "ONIOM: extrapolated energy" in line.strip():
435 spe = (float(line.strip().split()[4]))
436 # For G4 calculations look for G4 energies (Gaussian16a bug prints G4(0 K) as DE(HF)) --Brian modified to work for G16c-where bug is fixed.
437 elif line.strip().startswith('G4(0 K)'):
438 spe = float(line.strip().split()[2])
439 spe -= zero_point_corr_G4 #Remove G4 ZPE
440 elif line.strip().startswith('E(ZPE)='): #Get G4 ZPE
441 zero_point_corr_G4 = float(line.strip().split()[1])
442 # For TD calculations look for SCF energies of the first excited state
443 elif 'E(TD-HF/TD-DFT)' in line.strip():
444 spe = float(line.strip().split()[4])
445 # For Semi-empirical or Molecular Mechanics calculations
446 elif "Energy= " in line.strip() and "Predicted" not in line.strip() and "Thermal" not in line.strip() and "G4" not in line.strip():
447 spe = (float(line.strip().split()[1]))
448 elif "Gaussian" in line and "Revision" in line and repeated_link1 == 0:
449 for i in range(len(line.strip(",").split(",")) - 1):
450 line.strip(",").split(",")[i]
451 version_program += line.strip(",").split(",")[i]
452 repeated_link1 = 1
453 version_program = version_program[1:]
454 # Charge and multiplicity
455 elif 'Charge' in line and 'Multiplicity' in line:
456 try:
457 parts = line.split()
458 charge = int(parts[parts.index('Charge') + 2])
459 multiplicity = int(parts[parts.index('Multiplicity') + 2])
460 except (ValueError, IndexError):
461 pass
462 elif program == "Orca":
463 if 'Program Version' in line.strip():
464 version_program = "ORCA version " + line.split()[2]
465 if line.strip().startswith('FINAL SINGLE POINT ENERGY'):
466 spe = float(line.strip().split()[-1])
467 if "Total Charge" in line.strip() and "...." in line.strip():
468 charge = int(line.strip("=").split()[-1])
469 if "Multiplicity" in line.strip() and "...." in line.strip():
470 multiplicity = int(line.strip("=").split()[-1])
471 elif program == "NWChem":
472 if 'nwchem branch' in line.strip():
473 version_program = "NWChem version " + line.split()[3]
474 if line.strip().startswith('Total DFT energy'):
475 spe = float(line.strip().split()[4])
476 if "charge" in line.strip():
477 charge = int(line.strip().split()[-1])
478 if "mult " in line.strip():
479 multiplicity = int(line.strip().split()[-1])
480 elif program == "xtb":
481 stripped = line.strip()
482 if 'xtb version' in stripped and not version_program:
483 parts = stripped.split()
484 try:
485 version_program = "xtb version " + parts[parts.index('version') + 1]
486 except (ValueError, IndexError):
487 pass
488 if stripped.startswith(':: total energy'):
489 parts = stripped.split()
490 try:
491 spe = float(parts[3])
492 except (ValueError, IndexError):
493 pass
494 if 'net charge' in stripped and stripped.startswith(':'):
495 parts = stripped.split()
496 try:
497 charge = int(parts[parts.index('charge') + 1])
498 except (ValueError, IndexError):
499 pass
500 if 'unpaired electrons' in stripped and stripped.startswith(':'):
501 parts = stripped.split()
502 try:
503 multiplicity = int(parts[parts.index('electrons') + 1]) + 1
504 except (ValueError, IndexError):
505 pass
506
507 # Solvation model and empirical dispersion detection
508 if 'Gaussian' in version_program.strip():
509 for i, line in enumerate(data):
510 if '#' in line.strip() and a == 0:
511 for j, line in enumerate(data[i:i + 10]):
512 if '--' in line.strip():
513 a = a + 1
514 break
515 if a != 0:
516 break
517 else:
518 for k in range(len(line.strip().split("\n"))):
519 line.strip().split("\n")[k]
520 keyword_line += line.strip().split("\n")[k]
521 keyword_line = keyword_line.lower()
522 if 'scrf' not in keyword_line.strip():
523 solvation_model = "gas phase"
524 else:
525 start_scrf = keyword_line.strip().find('scrf') + 4
526 if '(' in keyword_line[start_scrf:start_scrf + 4]:
527 start_scrf += keyword_line[start_scrf:start_scrf + 4].find('(') + 1
528 end_scrf = keyword_line.find(")", start_scrf)
529 display_solvation_model = "scrf=(" + ','.join(
530 keyword_line[start_scrf:end_scrf].lower().split(',')) + ')'
531 sorted_solvation_model = "scrf=(" + ','.join(
532 sorted(keyword_line[start_scrf:end_scrf].lower().split(','))) + ')'
533 else:
534 if ' = ' in keyword_line[start_scrf:start_scrf + 4]:
535 start_scrf += keyword_line[start_scrf:start_scrf + 4].find(' = ') + 3
536 elif ' =' in keyword_line[start_scrf:start_scrf + 4]:
537 start_scrf += keyword_line[start_scrf:start_scrf + 4].find(' =') + 2
538 elif '=' in keyword_line[start_scrf:start_scrf + 4]:
539 start_scrf += keyword_line[start_scrf:start_scrf + 4].find('=') + 1
540 end_scrf = keyword_line.find(" ", start_scrf)
541 if end_scrf == -1:
542 display_solvation_model = "scrf=(" + ','.join(keyword_line[start_scrf:].lower().split(',')) + ')'
543 sorted_solvation_model = "scrf=(" + ','.join(
544 sorted(keyword_line[start_scrf:].lower().split(','))) + ')'
545 else:
546 display_solvation_model = "scrf=(" + ','.join(
547 keyword_line[start_scrf:end_scrf].lower().split(',')) + ')'
548 sorted_solvation_model = "scrf=(" + ','.join(
549 sorted(keyword_line[start_scrf:end_scrf].lower().split(','))) + ')'
550 if solvation_model != "gas phase":
551 solvation_model = [sorted_solvation_model, display_solvation_model]
552 empirical_dispersion = ''
553 if keyword_line.strip().find('empiricaldispersion') == -1 and keyword_line.strip().find(
554 'emp=') == -1 and keyword_line.strip().find('emp =') == -1 and keyword_line.strip().find('emp(') == -1:
555 empirical_dispersion = "No empirical dispersion detected"
556 elif keyword_line.strip().find('empiricaldispersion') > -1:
557 start_emp_disp = keyword_line.strip().find('empiricaldispersion') + 19
558 if '(' in keyword_line[start_emp_disp:start_emp_disp + 4]:
559 start_emp_disp += keyword_line[start_emp_disp:start_emp_disp + 4].find('(') + 1
560 end_emp_disp = keyword_line.find(")", start_emp_disp)
561 empirical_dispersion = 'empiricaldispersion=(' + ','.join(
562 sorted(keyword_line[start_emp_disp:end_emp_disp].lower().split(','))) + ')'
563 else:
564 if ' = ' in keyword_line[start_emp_disp:start_emp_disp + 4]:
565 start_emp_disp += keyword_line[start_emp_disp:start_emp_disp + 4].find(' = ') + 3
566 elif ' =' in keyword_line[start_emp_disp:start_emp_disp + 4]:
567 start_emp_disp += keyword_line[start_emp_disp:start_emp_disp + 4].find(' =') + 2
568 elif '=' in keyword_line[start_emp_disp:start_emp_disp + 4]:
569 start_emp_disp += keyword_line[start_emp_disp:start_emp_disp + 4].find('=') + 1
570 end_emp_disp = keyword_line.find(" ", start_emp_disp)
571 if end_emp_disp == -1:
572 empirical_dispersion = "empiricaldispersion=(" + ','.join(
573 sorted(keyword_line[start_emp_disp:].lower().split(','))) + ')'
574 else:
575 empirical_dispersion = "empiricaldispersion=(" + ','.join(
576 sorted(keyword_line[start_emp_disp:end_emp_disp].lower().split(','))) + ')'
577 elif keyword_line.strip().find('emp=') > -1 or keyword_line.strip().find(
578 'emp =') > -1 or keyword_line.strip().find('emp(') > -1:
579 # Check for temp keyword
580 temp, emp_e, emp_p = False, False, False
581 check_temp = keyword_line.strip().find('emp=')
582 start_emp_disp = keyword_line.strip().find('emp=')
583 if check_temp == -1:
584 check_temp = keyword_line.strip().find('emp =')
585 start_emp_disp = keyword_line.strip().find('emp =')
586 if check_temp == -1:
587 check_temp = keyword_line.strip().find('emp=(')
588 start_emp_disp = keyword_line.strip().find('emp(')
589 check_temp += -1
590 if keyword_line[check_temp].lower() == 't':
591 temp = True # Look for a new one
592 if keyword_line.strip().find('emp=', check_temp + 5) > -1:
593 emp_e = True
594 start_emp_disp = keyword_line.strip().find('emp=', check_temp + 5) + 3
595 elif keyword_line.strip().find('emp =', check_temp + 5) > -1:
596 emp_e = True
597 start_emp_disp = keyword_line.strip().find('emp =', check_temp + 5) + 3
598 elif keyword_line.strip().find('emp(', check_temp + 5) > -1:
599 emp_p = True
600 start_emp_disp = keyword_line.strip().find('emp(', check_temp + 5) + 3
601 else:
602 empirical_dispersion = "No empirical dispersion detected"
603 else:
604 start_emp_disp += 3
605 if (temp and emp_e) or (not temp and keyword_line.strip().find('emp=') > -1) or (
606 not temp and keyword_line.strip().find('emp =')):
607 if '(' in keyword_line[start_emp_disp:start_emp_disp + 4]:
608 start_emp_disp += keyword_line[start_emp_disp:start_emp_disp + 4].find('(') + 1
609 end_emp_disp = keyword_line.find(")", start_emp_disp)
610 empirical_dispersion = 'empiricaldispersion=(' + ','.join(
611 sorted(keyword_line[start_emp_disp:end_emp_disp].lower().split(','))) + ')'
612 else:
613 if ' = ' in keyword_line[start_emp_disp:start_emp_disp + 4]:
614 start_emp_disp += keyword_line[start_emp_disp:start_emp_disp + 4].find(' = ') + 3
615 elif ' =' in keyword_line[start_emp_disp:start_emp_disp + 4]:
616 start_emp_disp += keyword_line[start_emp_disp:start_emp_disp + 4].find(' =') + 2
617 elif '=' in keyword_line[start_emp_disp:start_emp_disp + 4]:
618 start_emp_disp += keyword_line[start_emp_disp:start_emp_disp + 4].find('=') + 1
619 end_emp_disp = keyword_line.find(" ", start_emp_disp)
620 if end_emp_disp == -1:
621 empirical_dispersion = "empiricaldispersion=(" + ','.join(
622 sorted(keyword_line[start_emp_disp:].lower().split(','))) + ')'
623 else:
624 empirical_dispersion = "empiricaldispersion=(" + ','.join(
625 sorted(keyword_line[start_emp_disp:end_emp_disp].lower().split(','))) + ')'
626 elif (temp and emp_p) or (not temp and keyword_line.strip().find('emp(') > -1):
627 start_emp_disp += keyword_line[start_emp_disp:start_emp_disp + 4].find('(') + 1
628 end_emp_disp = keyword_line.find(")", start_emp_disp)
629 empirical_dispersion = 'empiricaldispersion=(' + ','.join(
630 sorted(keyword_line[start_emp_disp:end_emp_disp].lower().split(','))) + ')'
631 if 'ORCA' in version_program.strip():
632 keyword_line_1 = "gas phase"
633 keyword_line_2 = ''
634 keyword_line_3 = ''
635 for i, line in enumerate(data):
636 if 'CPCM SOLVATION MODEL' in line.strip():
637 keyword_line_1 = "CPCM,"
638 if 'SMD CDS free energy correction energy' in line.strip():
639 keyword_line_2 = "SMD,"
640 if "Solvent: " in line.strip():
641 keyword_line_3 = line.strip().split()[-1]
642 solvation_model = keyword_line_1 + keyword_line_2 + keyword_line_3
643 empirical_dispersion1 = 'No empirical dispersion detected'
644 empirical_dispersion2 = ''
645 empirical_dispersion3 = ''
646 for i, line in enumerate(data):
647 if keyword_line.strip().find('DFT DISPERSION CORRECTION') > -1:
648 empirical_dispersion1 = ''
649 if keyword_line.strip().find('DFTD3') > -1:
650 empirical_dispersion2 = "D3"
651 if keyword_line.strip().find('USING zero damping') > -1:
652 empirical_dispersion3 = ' with zero damping'
653 empirical_dispersion = empirical_dispersion1 + empirical_dispersion2 + empirical_dispersion3
654 if 'NWChem' in version_program.strip():
655 empirical_dispersion1 = 'No empirical dispersion detected'
656 empirical_dispersion2 = ''
657 empirical_dispersion3 = ''
658 for i, line in enumerate(data):
659 if keyword_line.strip().find('Dispersion correction') > -1:
660 empirical_dispersion1 = ''
661 if keyword_line.strip().find('disp vdw 3') > -1:
662 empirical_dispersion2 = "D3"
663 if keyword_line.strip().find('disp vdw 4') > -1:
664 empirical_dispersion2 = "D3BJ"
665 empirical_dispersion = empirical_dispersion1 + empirical_dispersion2 + empirical_dispersion3
666 if 'xtb' in version_program.strip():
667 solvation_model = 'gas phase'
668 for line in data:
669 stripped = line.strip()
670 if 'program call' in stripped and ':' in stripped:
671 solvation_model = _xtb_solvation_from_call(stripped.split(':', 1)[1].strip())
672 break
673 empirical_dispersion = 'No empirical dispersion detected'
674
675 return spe, program, version_program, solvation_model, file, charge, empirical_dispersion, multiplicity
676
677 def sp_cpu(file):
678 """Read single-point output for CPU time.
679
680 Delegates to ``parse_qcdata(file).cpu`` so the SPC CPU is identical
681 to what a standalone parse of the same file would report. This
682 guarantees that ``goodvibes <parents> --spc <suffix>`` totals
683 correctly reflect the SPC files' CPU — including program-specific
684 accumulation (Gaussian sums multi-step ``Job cpu time`` lines) and
685 nprocs scaling (ORCA reports wall time only; the parser scales by
686 parallel-MPI process count to estimate effective CPU).
687 """
688 candidates = [
689 os.path.splitext(file)[0] + '.log',
690 os.path.splitext(file)[0] + '.out',
691 ]
692 for cand in candidates:
693 if os.path.exists(cand):
694 return parse_qcdata(cand).cpu
695 raise ValueError("File {} does not exist".format(file))
696
697
698
699 # Tokens on the ORCA ``!`` keyword line that are NOT method or basis set.
700 _ORCA_SKIP_TOKENS = {
701 # Job types
702 'OPT', 'OPTTS', 'FREQ', 'NUMFREQ', 'NUMHESS', 'ANFREQ', 'SP', 'NMR',
703 'VPT2', 'SCANTS', 'NEB-TS', 'FAST-NEB-TS', 'NEB-CI',
704 # Solvation
705 'CPCM', 'SMD',
706 # Dispersion (standalone keywords, not embedded in functional name)
707 'D3BJ', 'D3', 'D4', 'D3ZERO',
708 # SCF convergence
709 'TIGHTSCF', 'NORMALSCF', 'LOOSESCF', 'VERYTIGHTSCF', 'EXTREMESCF',
710 'SLOWCONV', 'NOCONV',
711 # RI approximations
712 'RIJCOSX', 'RI', 'RIJK', 'RIJONX', 'AUTOAUX', 'RIJDX',
713 # Grid
714 'GRID4', 'GRID5', 'GRID6', 'GRID7',
715 'FINALGRID4', 'FINALGRID5', 'FINALGRID6', 'FINALGRID7',
716 # Output verbosity
717 'PRINT', 'MINIPRINT', 'LARGEPRINT', 'PRINTBASIS', 'PRINTMOS', 'NOPRINT',
718 # Reference (DFT)
719 'UKS', 'RKS',
720 # Other
721 'NOFROZENCORE', 'FROZENCORE', 'MOREAD', 'XYZFILE',
722 'SCALFREQ', 'QUASIRRHO',
723 }
724
725 # Reference keywords that map to HF when no other method is present
726 _ORCA_HF_REFS = {'UHF', 'RHF', 'ROHF'}
727
728 # Regex for recognizing basis set tokens (case-insensitive matching)
729 _BASIS_PATTERNS = [
730 re.compile(r'^\d+-\d+\+*G', re.IGNORECASE), # Pople: 6-31G, 6-311+G, etc.
731 re.compile(r'^(AUG-)?CC-PV[DTQR56]Z$', re.IGNORECASE), # Dunning
732 re.compile(r'^DEF2-', re.IGNORECASE), # Karlsruhe def2-
733 re.compile(r'^(SV|TZV|QZV)P?P?$', re.IGNORECASE), # Ahlrichs without def2
734 re.compile(r'^SV\(P\)$', re.IGNORECASE), # SV(P)
735 ]
736
737
738 def _is_basis_set(token):
739 """Return True if *token* looks like a basis set name."""
740 return any(pat.match(token) for pat in _BASIS_PATTERNS)
741
742
743 def _is_auxiliary_basis(token):
744 """Return True if *token* is an auxiliary basis set (e.g. cc-pVTZ/C, def2/J)."""
745 upper = token.upper()
746 if '/' in upper:
747 suffix = upper.rsplit('/', 1)[1]
748 if suffix in ('C', 'J', 'JK', 'JKFIT', 'CFIT'):
749 return True
750 # def2/J, def2/JK style
751 if upper.startswith('DEF2/'):
752 return True
753 return False
754
755
756 def _parse_orca_lot(data):
757 """Extract (method, basis_set) from ORCA output file lines.
758
759 Parses the ``!`` keyword line(s) in the ORCA input section and classifies
760 tokens into method, basis set, or known keywords to skip. Falls back to
761 the ``Your calculation utilizes the basis:`` line when no basis set is
762 found on the ``!`` line.
763 """
764 kw_tokens = []
765 fallback_basis = None
766
767 for line in data:
768 stripped = line.strip()
769
770 # Collect tokens from ORCA input keyword lines: | N> ! ...
771 # The ``!`` must be the first non-whitespace after ``>`` to avoid
772 # matching ``!`` inside comments on other input lines.
773 if '|' in line and '>' in stripped:
774 after_angle = stripped.split('>', 1)[1].lstrip()
775 if after_angle.startswith('!'):
776 after_bang = after_angle.split('!', 1)[1]
777 kw_tokens.extend(after_bang.split())
778
779 # Fallback basis from ORCA output section
780 if 'Your calculation utilizes the basis:' in stripped and fallback_basis is None:
781 fallback_basis = stripped.split(':')[-1].strip()
782
783 # Classify tokens
784 method = None
785 basis = None
786 hf_ref = None # Track UHF/RHF/ROHF in case it's the only method
787
788 for token in kw_tokens:
789 upper = token.upper()
790
791 # Skip parallelization (pal4, pal8, pal16, ...)
792 if re.match(r'^PAL\d+$', upper):
793 continue
794
795 # Skip known ORCA keywords
796 if upper in _ORCA_SKIP_TOKENS:
797 continue
798
799 # Skip auxiliary basis sets
800 if _is_auxiliary_basis(token):
801 continue
802
803 # Skip GCP(...) tokens
804 if upper.startswith('GCP(') or upper == 'GCP':
805 continue
806
807 # Skip QM/QM2 compound job keyword
808 if upper == 'QM/QM2':
809 continue
810
811 # Track HF reference keywords
812 if upper in _ORCA_HF_REFS:
813 hf_ref = 'HF'
814 continue
815
816 # Classify as basis set or method
817 if _is_basis_set(token) and basis is None:
818 basis = token
819 elif method is None:
820 method = token
821
822 # Fall back: if only HF reference found and no other method
823 if method is None and hf_ref is not None:
824 method = hf_ref
825
826 # Fall back to "utilizes the basis" line
827 if basis is None and fallback_basis is not None:
828 basis = fallback_basis
829
830 return method or 'none', basis or 'none'
831
832
833 def level_of_theory(file):
834 """Read output for the level of theory and basis set used."""
835 repeated_theory = 0
836 with open(file, encoding='utf-8', errors='replace') as f:
837 data = f.readlines()
838 level, bs = 'none', 'none'
839
840 # Detect ORCA and use dedicated parser
841 for line in data:
842 if '* O R C A *' in line:
843 level, bs = _parse_orca_lot(data)
844 return '/'.join([level, bs])
845 if 'Gaussian' in line:
846 break
847 if 'NWChem' in line:
848 break
849 if 'x T B' in line or 'xtb version' in line:
850 for ln in data:
851 if 'Hamiltonian' in ln and 'xTB' in ln:
852 parts = ln.split()
853 for tok in parts:
854 if 'xTB' in tok:
855 return tok + '/none'
856 return 'GFN2-xTB/none'
857
858 for line in data:
859 if line.strip().find('External calculation') > -1:
860 level, bs = 'ext', 'ext'
861 break
862 if '\\Freq\\' in line.strip() and repeated_theory == 0:
863 try:
864 level, bs = (line.strip().split("\\")[4:6])
865 repeated_theory = 1
866 except IndexError:
867 pass
868 elif '|Freq|' in line.strip() and repeated_theory == 0:
869 try:
870 level, bs = (line.strip().split("|")[4:6])
871 repeated_theory = 1
872 except IndexError:
873 pass
874 if '\\SP\\' in line.strip() and repeated_theory == 0:
875 try:
876 level, bs = (line.strip().split("\\")[4:6])
877 repeated_theory = 1
878 except IndexError:
879 pass
880 elif '|SP|' in line.strip() and repeated_theory == 0:
881 try:
882 level, bs = (line.strip().split("|")[4:6])
883 repeated_theory = 1
884 except IndexError:
885 pass
886 if 'DLPNO BASED TRIPLES CORRECTION' in line.strip():
887 level = 'DLPNO-CCSD(T)'
888 if 'Estimated CBS total energy' in line.strip():
889 try:
890 bs = ("Extrapol." + line.strip().split()[4])
891 except IndexError:
892 pass
893 # Remove the restricted R or unrestricted U label
894 if level[0] in ('R', 'U'):
895 level = level[1:]
896 level_of_theory = '/'.join([level, bs])
897 return level_of_theory
898
899 def read_initial(file):
900 """At beginning of procedure, read level of theory, solvation model, and check for normal termination"""
901 with open(file, encoding='utf-8', errors='replace') as f:
902 data = f.readlines()
903 level, bs, program, keyword_line = 'none', 'none', 'none', 'none'
904 solvation_model = "gas phase"
905 progress, orientation = 'Incomplete', 'Input'
906 a, repeated_theory = 0, 0
907 no_grid = True
908 dft_used = 'F'
909 grid_lookup = {1: 'sg1', 2: 'coarse', 4: 'fine', 5: 'ultrafine', 7: 'superfine'}
910
911 for line in data:
912 # Determine program
913 if "Gaussian" in line:
914 program = "Gaussian"
915 break
916 if "* O R C A *" in line:
917 program = "Orca"
918 break
919 if "NWChem" in line:
920 program = "NWChem"
921 break
922 if "x T B" in line or "xtb version" in line:
923 program = "xtb"
924 break
925 if "You are running Q-Chem" in line or "Welcome to Q-Chem" in line:
926 program = "QChem"
927 break
928 # ASE extxyz: program=ase appears in line 2 (the comment line)
929 if program == 'none' and len(data) >= 2 and 'program=ase' in data[1]:
930 program = 'ase'
931 for line in data:
932 # Grab pertinent information from file
933 if line.strip().find('External calculation') > -1:
934 level, bs = 'ext', 'ext'
935 if line.strip().find('Standard orientation:') > -1:
936 orientation = 'Standard'
937 if line.strip().find('IExCor=') > -1 and no_grid:
938 try:
939 dft_used = line.split('=')[2].split()[0]
940 _ = grid_lookup[int(dft_used)]
941 no_grid = False
942 except (KeyError, ValueError, IndexError):
943 pass
944 if '\\Freq\\' in line.strip() and repeated_theory == 0:
945 try:
946 level, bs = (line.strip().split("\\")[4:6])
947 repeated_theory = 1
948 except IndexError:
949 pass
950 elif '|Freq|' in line.strip() and repeated_theory == 0:
951 try:
952 level, bs = (line.strip().split("|")[4:6])
953 repeated_theory = 1
954 except IndexError:
955 pass
956 if '\\SP\\' in line.strip() and repeated_theory == 0:
957 try:
958 level, bs = (line.strip().split("\\")[4:6])
959 repeated_theory = 1
960 except IndexError:
961 pass
962 elif '|SP|' in line.strip() and repeated_theory == 0:
963 try:
964 level, bs = (line.strip().split("|")[4:6])
965 repeated_theory = 1
966 except IndexError:
967 pass
968 if 'DLPNO BASED TRIPLES CORRECTION' in line.strip():
969 level = 'DLPNO-CCSD(T)'
970 if 'Estimated CBS total energy' in line.strip():
971 try:
972 bs = ("Extrapol." + line.strip().split()[4])
973 except IndexError:
974 pass
975 # Remove the restricted R or unrestricted U label
976 if level[0] in ('R', 'U'):
977 level = level[1:]
978
979 #NWChem specific parsing
980 if program == 'NWChem':
981 keyword_line_1 = "gas phase"
982 keyword_line_2 = ''
983 keyword_line_3 = ''
984 for i, line in enumerate(data):
985 if line.strip().startswith("xc "):
986 level=line.strip().split()[1]
987 if line.strip().startswith("* library "):
988 bs = line.strip().replace("* library ",'')
989 #need to update these tags for NWChem solvation later
990 if 'CPCM SOLVATION MODEL' in line.strip():
991 keyword_line_1 = "CPCM,"
992 if 'SMD CDS free energy correction energy' in line.strip():
993 keyword_line_2 = "SMD,"
994 if "Solvent: " in line.strip():
995 keyword_line_3 = line.strip().split()[-1]
996 #need to update NWChem keyword for error calculation
997 if 'Total times' in line:
998 progress = 'Normal'
999 elif 'error termination' in line:
1000 progress = 'Error'
1001 solvation_model = keyword_line_1 + keyword_line_2 + keyword_line_3
1002
1003 # Grab solvation models - Gaussian files
1004 if program == 'Gaussian':
1005 for i, line in enumerate(data):
1006 if '#' in line.strip() and a == 0:
1007 for j, line in enumerate(data[i:i + 10]):
1008 if '--' in line.strip():
1009 a = a + 1
1010 break
1011 if a != 0:
1012 break
1013 else:
1014 for k in range(len(line.strip().split("\n"))):
1015 keyword_line += line.strip().split("\n")[k]
1016 if 'Normal termination' in line:
1017 progress = 'Normal'
1018 elif 'Error termination' in line:
1019 progress = 'Error'
1020 keyword_line = keyword_line.lower()
1021 if 'scrf' not in keyword_line.strip():
1022 solvation_model = "gas phase"
1023 else:
1024 start_scrf = keyword_line.strip().find('scrf') + 5
1025 if keyword_line[start_scrf] == "(":
1026 end_scrf = keyword_line.find(")", start_scrf)
1027 solvation_model = "scrf=" + keyword_line[start_scrf:end_scrf]
1028 if solvation_model[-1] != ")":
1029 solvation_model = solvation_model + ")"
1030 else:
1031 start_scrf2 = keyword_line.strip().find('scrf') + 4
1032 if keyword_line.find(" ", start_scrf) > -1:
1033 end_scrf = keyword_line.find(" ", start_scrf)
1034 else:
1035 end_scrf = len(keyword_line)
1036 if keyword_line[start_scrf2] == "(":
1037 solvation_model = "scrf=(" + keyword_line[start_scrf:end_scrf]
1038 if solvation_model[-1] != ")":
1039 solvation_model = solvation_model + ")"
1040 else:
1041 if keyword_line.find(" ", start_scrf) > -1:
1042 end_scrf = keyword_line.find(" ", start_scrf)
1043 else:
1044 end_scrf = len(keyword_line)
1045 solvation_model = "scrf=" + keyword_line[start_scrf:end_scrf]
1046 # xtb parsing for level of theory and solvation model
1047 elif program == 'xtb':
1048 # Hamiltonian (GFN0/1/2-xTB) → "level"; xtb has no basis set in the QC sense
1049 for ln in data:
1050 if 'Hamiltonian' in ln and 'xTB' in ln:
1051 for tok in ln.split():
1052 if 'xTB' in tok:
1053 level = tok
1054 break
1055 if level != 'none':
1056 break
1057 bs = 'none'
1058 # Solvation from program-call line
1059 solvation_model = 'gas phase'
1060 for ln in data:
1061 stripped = ln.strip()
1062 if 'program call' in stripped and ':' in stripped:
1063 solvation_model = _xtb_solvation_from_call(stripped.split(':', 1)[1].strip())
1064 break
1065 # Termination status
1066 for ln in data:
1067 if '[ERROR]' in ln or 'fatal error' in ln.lower():
1068 progress = 'Error'
1069 break
1070 if 'finished run on' in ln:
1071 progress = 'Normal'
1072
1073 # Q-Chem: parse $rem METHOD/BASIS from the input echo, solvation from
1074 # the run banner, and termination from "Thank you very much" footer.
1075 elif program == 'QChem':
1076 in_rem = False
1077 method, basis = 'none', 'none'
1078 cpcm = smd = solvent_name = ''
1079 for line in data:
1080 s = line.strip()
1081 if s.lower() == '$rem':
1082 in_rem = True
1083 continue
1084 if in_rem:
1085 if s == '$end' or s.startswith('$'):
1086 in_rem = False
1087 else:
1088 parts = s.split()
1089 if len(parts) >= 2:
1090 key = parts[0].lower()
1091 if key == 'method' and method == 'none':
1092 method = parts[1]
1093 elif key == 'basis' and basis == 'none':
1094 basis = parts[1]
1095 if 'Using C-PCM' in s or 'C-PCM dielectric factor' in s:
1096 cpcm = 'CPCM'
1097 elif 'Using the SMD solvation model' in s:
1098 smd = 'SMD'
1099 elif s.startswith('Solvent:'):
1100 try:
1101 solvent_name = s.split(':', 1)[1].strip()
1102 except IndexError:
1103 pass
1104 if 'Thank you very much for using Q-Chem' in line:
1105 progress = 'Normal'
1106 elif 'Q-Chem fatal error' in line or 'fatal error occurred' in line:
1107 progress = 'Error'
1108 level, bs = method, basis
1109 if smd:
1110 solvation_model = 'SMD,' + solvent_name if solvent_name else 'SMD'
1111 elif cpcm:
1112 solvation_model = 'CPCM,' + solvent_name if solvent_name else 'CPCM'
1113
1114 # ASE extxyz: pull metadata directly from the comment-line key=values
1115 elif program == 'ase':
1116 info = _parse_extxyz_comment(data[1]) if len(data) >= 2 else {}
1117 lot = info.get('level_of_theory', '')
1118 if '/' in lot:
1119 level, bs = lot.split('/', 1)
1120 elif lot:
1121 level, bs = lot, 'none'
1122 else:
1123 level, bs = 'none', 'none'
1124 solvation_model = info.get('solvation_model', 'gas phase') or 'gas phase'
1125 try:
1126 float(info.get('scf_energy', ''))
1127 progress = 'Normal'
1128 except ValueError:
1129 progress = 'Incomplete'
1130
1131 # ORCA parsing for solvation model and level of theory
1132 elif program == 'Orca':
1133 level, bs = _parse_orca_lot(data)
1134 keyword_line_1 = "gas phase"
1135 keyword_line_2 = ''
1136 keyword_line_3 = ''
1137 orca_abort_line = -1
1138 last_freq_line = -1
1139 for i, line in enumerate(data):
1140 if 'CPCM SOLVATION MODEL' in line.strip():
1141 keyword_line_1 = "CPCM,"
1142 if 'SMD CDS free energy correction energy' in line.strip():
1143 keyword_line_2 = "SMD,"
1144 if "Solvent: " in line.strip():
1145 keyword_line_3 = line.strip().split()[-1]
1146 if 'ORCA TERMINATED NORMALLY' in line:
1147 progress = 'Normal'
1148 elif 'error termination' in line:
1149 progress = 'Error'
1150 if 'ORCA will abort' in line:
1151 orca_abort_line = i
1152 if 'VIBRATIONAL FREQUENCIES' in line and '---' not in line:
1153 last_freq_line = i
1154 # Abort after the last freq section means no valid thermo was produced
1155 if orca_abort_line > last_freq_line:
1156 progress = 'Error'
1157 solvation_model = keyword_line_1 + keyword_line_2 + keyword_line_3
1158 level_of_theory = '/'.join([level, bs])
1159
1160 return level_of_theory, solvation_model, progress, orientation, dft_used
1161
1162 def gaussian_jobtype(filename):
1163 """Read the jobtype from a Gaussian archive string."""
1164 job = ''
1165 with open(filename, encoding='utf-8', errors='replace') as f:
1166 for line in f:
1167 if line.strip().find('\\SP\\') > -1:
1168 job += 'SP'
1169 if line.strip().find('\\FOpt\\') > -1:
1170 job += 'GS'
1171 if line.strip().find('\\FTS\\') > -1:
1172 job += 'TS'
1173 if line.strip().find('\\Freq\\') > -1:
1174 job += 'Freq'
1175 return job
1176
1177
1178 def parse_gaussian_thermo(file):
1179 """Parse Gaussian output for all thermochemistry-relevant data.
1180
1181 Returns QCData with raw frequencies (negative = imaginary, no inversion
1182 applied). Frequency inversion is a user policy decision handled in
1183 thermo.py.
1184
1185 Parameters
1186 ----------
1187 file : str
1188 Path to Gaussian output file.
1189 """
1190 qcdata = QCData(file=file, program='Gaussian')
1191
1192 # Delegate solvation, dispersion, version, charge to parse_data
1193 (_, _, version_program, solvation_model, _, charge,
1194 empirical_dispersion, multiplicity) = parse_data(file)
1195 qcdata.version_program = version_program
1196 qcdata.solvation_model = solvation_model
1197 qcdata.empirical_dispersion = empirical_dispersion
1198 if charge is not None:
1199 qcdata.charge = charge
1200 if multiplicity is not None:
1201 qcdata.multiplicity = multiplicity
1202
1203 # Job type from archive string
1204 qcdata.job_type = gaussian_jobtype(file)
1205
1206 # Read file
1207 with open(file, encoding='utf-8', errors='replace') as f:
1208 g_output = f.readlines()
1209
1210 # Auto-detect G4 composite method
1211 g4 = any('G4(0 K)' in line for line in g_output)
1212
1213 # Detect ONIOM
1214 is_oniom = any('ONIOM: extrapolated energy' in line for line in g_output)
1215 qcdata.has_oniom = is_oniom
1216
1217 # --- First pass: find link structure ---
1218 linkmax = 0
1219 freqloc = 0
1220 for line in g_output:
1221 if 'Normal termination' in line:
1222 linkmax += 1
1223 if 'Frequencies --' in line:
1224 freqloc = linkmax
1225
1226 # --- Second pass: extract data ---
1227 link = 0
1228 frequency_wn = []
1229 im_frequency_wn = []
1230 fract_modelsys = []
1231 freq_started = False # True once we encounter the first "Frequencies --" in this link
1232 freq_done = False # True once VPT2 "Recovering" marker is seen (guards against duplicates)
1233
1234 if freqloc == 0:
1235 freqloc = len(g_output)
1236
1237 for i, line in enumerate(g_output):
1238 # Link counter
1239 if 'Normal termination' in line:
1240 link += 1
1241 if link == freqloc:
1242 frequency_wn = []
1243 im_frequency_wn = []
1244 fract_modelsys = []
1245 freq_started = False
1246 freq_done = False
1247
1248 # Stop after freq link unless G4/composite
1249 if not g4 and link > freqloc:
1250 break
1251
1252 # VPT2/anharmonic: "Recovering previously computed normal modes" means
1253 # the frequencies about to appear are a duplicate of the harmonic set
1254 if 'Recovering previously computed normal modes' in line:
1255 freq_done = True
1256
1257 # Frequencies
1258 if not freq_done and line.strip().startswith('Frequencies -- '):
1259 freq_started = True
1260 if is_oniom:
1261 fract_line = g_output[i + 3]
1262 for j in range(2, 5):
1263 try:
1264 x = float(line.strip().split()[j])
1265 if x > 0.0:
1266 frequency_wn.append(x)
1267 if is_oniom:
1268 try:
1269 y = float(fract_line.strip().split()[j]) / 100.0
1270 y = float('{:.6f}'.format(y))
1271 fract_modelsys.append(y)
1272 except (IndexError, ValueError):
1273 fract_modelsys.append(1.0)
1274 elif x < 0.0:
1275 im_frequency_wn.append(x)
1276 except IndexError:
1277 pass
1278
1279 # --- SCF energy (all variants, last one wins) ---
1280 # Guard against VPT2 displaced geometry energies: once frequencies are
1281 # read, ignore further SCF Done / E2 / EUMP2 lines (but still allow
1282 # archive-line energies like CCSD= which appear after frequencies).
1283 elif not freq_started and line.strip().startswith('SCF Done:'):
1284 qcdata.scf_energy = float(line.strip().split()[4])
1285 elif not freq_started and line.strip().startswith('E2('):
1286 spe_value = line.strip().split()[-1]
1287 qcdata.scf_energy = float(spe_value.replace('D', 'E'))
1288 elif line.strip().startswith('Counterpoise corrected energy'):
1289 qcdata.scf_energy = float(line.strip().split()[4])
1290 elif not freq_started and 'EUMP2 =' in line.strip():
1291 qcdata.scf_energy = float((line.strip().split()[5]).replace('D', 'E'))
1292 elif 'CCSD(T)=' in line.strip():
1293 raw = line.strip().split('CCSD(T)=')[1].split('\\')[0].split()[0]
1294 qcdata.scf_energy = float(raw.replace('D', 'E'))
1295 elif 'CCSD=' in line.strip() and 'CCSD(T)' not in line.strip():
1296 raw = line.strip().split('CCSD=')[1].split('\\')[0].split()[0]
1297 qcdata.scf_energy = float(raw.replace('D', 'E'))
1298 elif 'ONIOM: extrapolated energy' in line.strip():
1299 qcdata.scf_energy = float(line.strip().split()[4])
1300 elif line.strip().startswith('G4(0 K)'):
1301 qcdata.scf_energy = float(line.strip().split()[2])
1302 if qcdata.zero_point_corr is not None:
1303 qcdata.scf_energy -= qcdata.zero_point_corr
1304 elif line.strip().startswith('E(ZPE)='):
1305 qcdata.zero_point_corr = float(line.strip().split()[1])
1306 elif 'E(TD-HF/TD-DFT)' in line.strip():
1307 qcdata.scf_energy = float(line.strip().split()[4])
1308 elif ('Energy= ' in line.strip()
1309 and 'Predicted' not in line.strip()
1310 and 'Thermal' not in line.strip()
1311 and 'G4' not in line.strip()):
1312 qcdata.scf_energy = float(line.strip().split()[1])
1313
1314 # Coordinates: take the LAST "Standard orientation" or "Input orientation" block
1315 elif 'Standard orientation:' in line or 'Input orientation:' in line:
1316 atom_nums_tmp = []
1317 cartesians_tmp = []
1318 for k in range(i + 5, len(g_output)):
1319 if '-----' in g_output[k]:
1320 break
1321 parts = g_output[k].split()
1322 atom_nums_tmp.append(int(parts[1]))
1323 cartesians_tmp.append([float(parts[3]), float(parts[4]), float(parts[5])])
1324 qcdata.atom_nums = atom_nums_tmp
1325 qcdata.cartesians = cartesians_tmp
1326
1327 # Zero-point correction
1328 elif line.strip().startswith('Zero-point correction='):
1329 qcdata.zero_point_corr = float(line.strip().split()[2])
1330
1331 # Multiplicity
1332 elif 'Multiplicity' in line.strip():
1333 try:
1334 qcdata.multiplicity = int(line.split('=')[-1].strip().split()[0])
1335 except (ValueError, IndexError):
1336 qcdata.multiplicity = int(line.split()[-1])
1337
1338 # Molecular mass
1339 elif line.strip().startswith('Molecular mass:'):
1340 qcdata.molecular_mass = float(line.strip().split()[2])
1341
1342 # Rotational symmetry number
1343 elif line.strip().startswith('Rotational symmetry number'):
1344 qcdata.symmno = int((line.strip().split()[3]).split('.')[0])
1345
1346 # Point group / linearity
1347 elif line.strip().startswith('Full point group'):
1348 pg = line.strip().split()[3]
1349 qcdata.point_group = pg
1350 if pg in ('D*H', 'C*V'):
1351 qcdata.linear_mol = True
1352
1353 # Rotational constants (GHz)
1354 elif line.strip().startswith('Rotational constants (GHZ):'):
1355 try:
1356 parts = line.strip().replace(':', ' ').split()
1357 qcdata.roconst = [float(parts[3]), float(parts[4]), float(parts[5])]
1358 except ValueError:
1359 if '********' in line.strip():
1360 qcdata.linear_warning = True
1361 parts = line.strip().replace(':', ' ').split()
1362 qcdata.roconst = [float(parts[4]), float(parts[5])]
1363
1364 # Rotational temperatures
1365 elif line.strip().startswith('Rotational temperature '):
1366 qcdata.rotemp = [float(line.strip().split()[3])]
1367 elif line.strip().startswith('Rotational temperatures'):
1368 try:
1369 qcdata.rotemp = [float(line.strip().split()[3]),
1370 float(line.strip().split()[4]),
1371 float(line.strip().split()[5])]
1372 except ValueError:
1373 if '********' in line.strip():
1374 qcdata.linear_warning = True
1375 qcdata.rotemp = [float(line.strip().split()[4]),
1376 float(line.strip().split()[5])]
1377
1378 # CPU time (not elif — checked independently for every line)
1379 if 'Job cpu time' in line.strip():
1380 qcdata.cpu = [
1381 int(line.split()[3]) + qcdata.cpu[0],
1382 int(line.split()[5]) + qcdata.cpu[1],
1383 int(line.split()[7]) + qcdata.cpu[2],
1384 0 + qcdata.cpu[3],
1385 int(float(line.split()[9]) * 1000.0) + qcdata.cpu[4],
1386 ]
1387
1388 qcdata.frequency_wn = frequency_wn
1389 qcdata.im_frequency_wn = im_frequency_wn
1390 if is_oniom:
1391 qcdata.fract_modelsys = fract_modelsys
1392 if qcdata.atom_nums:
1393 qcdata.atom_types = [periodictable[n] for n in qcdata.atom_nums]
1394
1395 return qcdata
1396
1397
1398 def parse_nwchem_thermo(file):
1399 """Parse NWChem output for all thermochemistry-relevant data.
1400
1401 Returns QCData with raw frequencies (negative = imaginary, no inversion
1402 applied).
1403
1404 Parameters
1405 ----------
1406 file : str
1407 Path to NWChem output file.
1408 """
1409 qcdata = QCData(file=file, program='NWChem')
1410
1411 # Delegate version, charge, multiplicity to parse_data
1412 try:
1413 (_, _, version_program, solvation_model, _, charge,
1414 empirical_dispersion, multiplicity) = parse_data(file)
1415 qcdata.version_program = version_program
1416 qcdata.solvation_model = solvation_model
1417 qcdata.empirical_dispersion = empirical_dispersion
1418 if charge is not None:
1419 qcdata.charge = charge
1420 if multiplicity is not None:
1421 qcdata.multiplicity = multiplicity
1422 except (ValueError, IndexError):
1423 pass
1424
1425 # NWChem has no archive string for job type; detect from content
1426 with open(file, encoding='utf-8', errors='replace') as f:
1427 g_output = f.readlines()
1428
1429 frequency_wn = []
1430 im_frequency_wn = []
1431
1432 for i, line in enumerate(g_output):
1433 # Frequencies (up to 6 per line)
1434 if line.strip().startswith('P.Frequency'):
1435 for j in range(1, 7):
1436 try:
1437 x = float(line.strip().split()[j])
1438 if x > 0.0:
1439 frequency_wn.append(x)
1440 elif x < 0.0:
1441 im_frequency_wn.append(x)
1442 except IndexError:
1443 pass
1444
1445 # SCF energy
1446 elif line.strip().startswith('Total DFT energy ='):
1447 qcdata.scf_energy = float(line.strip().split()[4])
1448
1449 # Zero-point correction
1450 elif line.strip().startswith('Zero-Point'):
1451 qcdata.zero_point_corr = float(line.strip().split()[8])
1452
1453 # Multiplicity
1454 elif 'mult ' in line.strip():
1455 try:
1456 qcdata.multiplicity = int(line.split()[1])
1457 except (ValueError, IndexError):
1458 qcdata.multiplicity = 1
1459
1460 # Coordinates: take the LAST "Output coordinates in angstroms" block
1461 elif 'Output coordinates in angstroms' in line:
1462 atom_nums_tmp = []
1463 cartesians_tmp = []
1464 for k in range(i + 4, len(g_output)):
1465 cline = g_output[k].strip()
1466 if cline == '':
1467 break
1468 parts = cline.split()
1469 atom_nums_tmp.append(int(float(parts[2])))
1470 cartesians_tmp.append([float(parts[3]), float(parts[4]), float(parts[5])])
1471 qcdata.atom_nums = atom_nums_tmp
1472 qcdata.cartesians = cartesians_tmp
1473
1474 # Molecular mass
1475 elif line.strip().find('mol. weight') != -1:
1476 qcdata.molecular_mass = float(line.strip().split()[-1][0:-1])
1477
1478 # Rotational symmetry number
1479 elif line.strip().find('symmetry #') != -1:
1480 qcdata.symmno = int(line.strip().split()[-1][0:-1])
1481
1482 # Point group / linearity
1483 elif line.strip().find('symmetry detected') != -1:
1484 pg = line.strip().split()[0]
1485 qcdata.point_group = pg
1486 if pg in ('D*H', 'C*V'):
1487 qcdata.linear_mol = True
1488
1489 # Version (fallback if parse_data failed)
1490 elif 'nwchem branch' in line.strip() and not qcdata.version_program:
1491 qcdata.version_program = 'NWChem version ' + line.split()[3]
1492
1493 # Rotational constants (convert cm⁻¹ to GHz) and temperatures
1494 elif line.strip().startswith('A=') or line.strip().startswith('B=') or line.strip().startswith('C='):
1495 letter = line.strip()[0]
1496 h = {'A': 0, 'B': 1, 'C': 2}[letter]
1497 qcdata.roconst[h] = float(line.strip().split()[1]) * 29.9792458
1498 qcdata.rotemp[h] = float(line.strip().split()[4])
1499
1500 # CPU time
1501 if 'Total times' in line.strip():
1502 secs = float(line.strip().split()[3][0:-1])
1503 qcdata.cpu = [0, 0, 0, secs, 0.0]
1504
1505 # Determine job type from content
1506 if len(frequency_wn) > 0 or len(im_frequency_wn) > 0:
1507 qcdata.job_type = 'Freq'
1508 else:
1509 qcdata.job_type = 'SP'
1510
1511 qcdata.frequency_wn = frequency_wn
1512 qcdata.im_frequency_wn = im_frequency_wn
1513 if qcdata.atom_nums:
1514 qcdata.atom_types = [periodictable[n] for n in qcdata.atom_nums]
1515
1516 return qcdata
1517
1518
1519 def _scale_cpu(cpu, factor):
1520 """Multiply a [days, hours, mins, secs, msecs] tuple by an integer factor.
1521
1522 Used by the ORCA parser to convert wall time × nprocs → effective CPU.
1523 """
1524 total_ms = (
1525 cpu[0] * 86_400_000
1526 + cpu[1] * 3_600_000
1527 + cpu[2] * 60_000
1528 + cpu[3] * 1_000
1529 + cpu[4]
1530 ) * factor
1531 days, total_ms = divmod(total_ms, 86_400_000)
1532 hours, total_ms = divmod(total_ms, 3_600_000)
1533 mins, total_ms = divmod(total_ms, 60_000)
1534 secs, msecs = divmod(total_ms, 1_000)
1535 return [days, hours, mins, secs, msecs]
1536
1537
1538 def parse_orca_thermo(file):
1539 """Parse ORCA output for all thermochemistry-relevant data.
1540
1541 Uses native line-by-line parsing.
1542
1543 Parameters
1544 ----------
1545 file : str
1546 Path to ORCA output file.
1547 """
1548 qcdata = QCData(file=file, program='Orca')
1549
1550 with open(file, encoding='utf-8', errors='replace') as f:
1551 output = f.readlines()
1552
1553 frequency_wn = []
1554 im_frequency_wn = []
1555 in_freq_section = False
1556 solvation_type = ''
1557 solvent_name = ''
1558 applied_freq_scale_factor = 1.0
1559 _has_opt = False
1560 _has_ts = False
1561 _has_freq_kw = False
1562 _orca_abort_line = -1
1563 _last_freq_line = -1
1564
1565 for i, line in enumerate(output):
1566 stripped = line.strip()
1567
1568 # --- Frequency section state machine ---
1569 if 'VIBRATIONAL FREQUENCIES' in stripped and '---' not in stripped:
1570 in_freq_section = True
1571 frequency_wn = []
1572 im_frequency_wn = []
1573 _last_freq_line = i
1574 elif in_freq_section and 'cm**-1' in stripped:
1575 parts = stripped.split()
1576 try:
1577 freq_val = float(parts[1])
1578 if freq_val > 0.0:
1579 frequency_wn.append(freq_val)
1580 elif freq_val < 0.0:
1581 im_frequency_wn.append(freq_val)
1582 # freq_val == 0.0 → skip (translational/rotational modes)
1583 except (IndexError, ValueError):
1584 pass
1585 elif in_freq_section:
1586 if stripped == '' and (frequency_wn or im_frequency_wn):
1587 in_freq_section = False
1588
1589 # --- Main field parsing ---
1590 # Coordinates: take the LAST "CARTESIAN COORDINATES (ANGSTROEM)" block
1591 if 'CARTESIAN COORDINATES (ANGSTROEM)' in stripped:
1592 atom_nums_tmp = []
1593 atom_types_tmp = []
1594 cartesians_tmp = []
1595 for k in range(i + 2, len(output)):
1596 cline = output[k].strip()
1597 if cline == '' or '---' in cline:
1598 break
1599 parts = cline.split()
1600 elem = parts[0]
1601 atom_types_tmp.append(elem)
1602 atom_nums_tmp.append(element_id(elem, num=True))
1603 cartesians_tmp.append([float(parts[1]), float(parts[2]), float(parts[3])])
1604 qcdata.atom_nums = atom_nums_tmp
1605 qcdata.atom_types = atom_types_tmp
1606 qcdata.cartesians = cartesians_tmp
1607
1608 # SCF energy (last occurrence wins for linked jobs)
1609 elif stripped.startswith('FINAL SINGLE POINT ENERGY'):
1610 qcdata.scf_energy = float(stripped.split()[-1])
1611
1612 # Collect input keywords for job type detection (handled after loop)
1613 elif '|' in line and '>' in stripped and '!' in stripped:
1614 kw = stripped.split('!', 1)[1].upper()
1615 if 'OPTTS' in kw:
1616 _has_ts = True
1617 elif 'OPT' in kw:
1618 _has_opt = True
1619 if 'FREQ' in kw:
1620 _has_freq_kw = True
1621
1622 # Charge
1623 elif 'Total Charge' in stripped and '....' in stripped:
1624 qcdata.charge = int(stripped.split()[-1])
1625
1626 # Multiplicity
1627 elif 'Multiplicity' in stripped and 'Mult' in stripped and '....' in stripped:
1628 qcdata.multiplicity = int(stripped.split()[-1])
1629
1630 # Program version
1631 elif 'Program Version' in stripped:
1632 qcdata.version_program = 'ORCA version ' + line.split()[2]
1633
1634 # Zero-point energy (Eh)
1635 elif stripped.startswith('Zero point energy') and '...' in stripped:
1636 parts = stripped.split()
1637 try:
1638 dot_idx = parts.index('...')
1639 qcdata.zero_point_corr = float(parts[dot_idx + 1])
1640 except (ValueError, IndexError):
1641 pass
1642
1643 # Molecular mass (AMU)
1644 elif 'Total Mass' in stripped and '...' in stripped:
1645 parts = stripped.split()
1646 try:
1647 dot_idx = parts.index('...')
1648 qcdata.molecular_mass = float(parts[dot_idx + 1])
1649 except (ValueError, IndexError):
1650 pass
1651
1652 # Rotational constants in cm⁻¹ → convert to GHz and rotational temps
1653 elif stripped.startswith('Rotational constants in cm-1:'):
1654 rparts = stripped.split(':')[1].split()
1655 try:
1656 roconst_cm = [float(rparts[0]), float(rparts[1]), float(rparts[2])]
1657 qcdata.roconst = [b * 29.9792458 for b in roconst_cm]
1658 # Rotational temperature: T_rot = h*c*B/k_B where B in cm⁻¹
1659 HC_OVER_KB = 1.4387768775 # K per cm⁻¹
1660 qcdata.rotemp = [HC_OVER_KB * b for b in roconst_cm]
1661 except (IndexError, ValueError):
1662 pass
1663
1664 # Point group and symmetry number (same line)
1665 elif 'Point Group:' in stripped and 'Symmetry Number:' in stripped:
1666 pg_part = stripped.split('Point Group:')[1].split(',')[0].strip()
1667 qcdata.point_group = pg_part
1668 # Linear point groups: ORCA 6 prints "C(inf)v"/"D(inf)h",
1669 # ORCA 5 prints "Cinfv"/"Dinfh" — match both via the "inf" stem.
1670 if 'inf' in pg_part.lower():
1671 qcdata.linear_mol = True
1672 try:
1673 symm_part = stripped.split('Symmetry Number:')[1].strip()
1674 qcdata.symmno = int(symm_part)
1675 except (ValueError, IndexError):
1676 pass
1677
1678 # Solvation model detection
1679 elif 'CPCM SOLVATION MODEL' in stripped:
1680 solvation_type = 'CPCM'
1681 elif 'SMD CDS free energy correction energy' in stripped:
1682 solvation_type = 'SMD'
1683 elif stripped.startswith('Solvent:') and '...' in stripped:
1684 solvent_name = stripped.split()[-1]
1685
1686 # Frequency scaling factor (ORCA pre-applies this to reported frequencies)
1687 elif stripped.startswith('Scaling factor for frequencies'):
1688 try:
1689 applied_freq_scale_factor = float(stripped.split('=')[1].split('(')[0].strip())
1690 except (IndexError, ValueError):
1691 pass
1692
1693 # CPU time. ORCA prints wall time only ("TOTAL RUN TIME:"); we scale
1694 # by the number of MPI processes (parsed from "Program running with
1695 # N parallel MPI-processes") to get an effective CPU time, matching
1696 # how Gaussian/NWChem/xTB report theirs.
1697 elif stripped.startswith('TOTAL RUN TIME:'):
1698 parts = stripped.split()
1699 try:
1700 cpu_list = [
1701 int(parts[3]), # days
1702 int(parts[5]), # hours
1703 int(parts[7]), # minutes
1704 int(parts[9]), # seconds
1705 int(parts[11]), # msec
1706 ]
1707 if qcdata.nprocs > 1:
1708 cpu_list = _scale_cpu(cpu_list, qcdata.nprocs)
1709 qcdata.cpu = cpu_list
1710 except (IndexError, ValueError):
1711 pass
1712
1713 # MPI process count (printed once per task; we keep the first hit).
1714 elif 'parallel MPI-processes' in stripped and qcdata.nprocs == 1:
1715 try:
1716 qcdata.nprocs = int(stripped.split('with')[1].split('parallel')[0].strip())
1717 except (IndexError, ValueError):
1718 pass
1719
1720 # ORCA abort: optimization failed before freq calculation could run.
1721 if 'ORCA will abort' in stripped:
1722 _orca_abort_line = i
1723
1724 # If the last abort comes after the last freq section (or there are no freqs),
1725 # any frequencies/ZPE present are from calc_hess, not the actual freq job — discard.
1726 if _orca_abort_line > _last_freq_line:
1727 frequency_wn = []
1728 im_frequency_wn = []
1729 qcdata.zero_point_corr = None
1730
1731 # Assemble solvation model
1732 if solvation_type:
1733 if solvent_name:
1734 qcdata.solvation_model = solvation_type + ',' + solvent_name
1735 else:
1736 qcdata.solvation_model = solvation_type
1737
1738 # Un-scale frequencies if ORCA applied a scaling factor, so that
1739 # frequency_wn always contains unscaled values (matching Gaussian convention)
1740 qcdata.applied_freq_scale_factor = applied_freq_scale_factor
1741 if applied_freq_scale_factor != 1.0 and applied_freq_scale_factor > 0.0:
1742 frequency_wn = [f / applied_freq_scale_factor for f in frequency_wn]
1743 im_frequency_wn = [f / applied_freq_scale_factor for f in im_frequency_wn]
1744 qcdata.frequency_wn = frequency_wn
1745 qcdata.im_frequency_wn = im_frequency_wn
1746
1747 # Fallback: parse coordinates from "* xyz charge mult" input block
1748 # when CARTESIAN COORDINATES (ANGSTROEM) block is absent (e.g., thermo-only re-analysis)
1749 if not qcdata.atom_nums:
1750 for i, line in enumerate(output):
1751 stripped = line.strip()
1752 if stripped.startswith('|') and '* xyz' in stripped:
1753 atom_nums_tmp = []
1754 atom_types_tmp = []
1755 cartesians_tmp = []
1756 for k in range(i + 1, len(output)):
1757 cline = output[k].strip()
1758 # Input lines start with "| N>" prefix
1759 if '|' in cline:
1760 content = cline.split('>', 1)[-1].strip() if '>' in cline else cline.strip('| ').strip()
1761 else:
1762 break
1763 if content == '*' or content == '' or 'END OF INPUT' in content:
1764 break
1765 parts = content.split()
1766 if len(parts) >= 4:
1767 elem = parts[0]
1768 atom_types_tmp.append(elem)
1769 atom_nums_tmp.append(element_id(elem, num=True))
1770 cartesians_tmp.append([float(parts[1]), float(parts[2]), float(parts[3])])
1771 if atom_nums_tmp:
1772 qcdata.atom_nums = atom_nums_tmp
1773 qcdata.atom_types = atom_types_tmp
1774 qcdata.cartesians = cartesians_tmp
1775 break
1776
1777 # For linear molecules, filter rotemp to non-zero values only
1778 # (linear molecules have one near-zero rotational constant along the axis)
1779 if qcdata.linear_mol:
1780 nonzero_rotemp = [t for t in qcdata.rotemp if t > 1e-10]
1781 if nonzero_rotemp:
1782 qcdata.rotemp = nonzero_rotemp
1783
1784 # Determine job type from combined input keywords and output content
1785 has_freq = _has_freq_kw or len(frequency_wn) > 0 or len(im_frequency_wn) > 0
1786 if _has_ts:
1787 qcdata.job_type = 'TSFreq' if has_freq else 'TS'
1788 elif _has_opt:
1789 qcdata.job_type = 'GSFreq' if has_freq else 'GS'
1790 elif has_freq:
1791 qcdata.job_type = 'Freq'
1792 else:
1793 qcdata.job_type = 'SP'
1794
1795 return qcdata
1796
1797
1798 def _xtb_solvation_from_call(call_line):
1799 """Parse the xtb ``program call`` line for an implicit-solvation flag.
1800
1801 Returns a string like 'GBSA,water', 'CPCM-X,dimethylsulfoxide',
1802 'ALPB,toluene', or 'gas phase'.
1803 """
1804 tokens = call_line.split()
1805 for i, tok in enumerate(tokens):
1806 if tok in ('-g', '--gbsa') and i + 1 < len(tokens):
1807 return 'GBSA,' + tokens[i + 1]
1808 if tok == '--cpcmx' and i + 1 < len(tokens):
1809 return 'CPCM-X,' + tokens[i + 1]
1810 if tok == '--alpb' and i + 1 < len(tokens):
1811 return 'ALPB,' + tokens[i + 1]
1812 return 'gas phase'
1813
1814
1815 def _xtb_read_xyz_fallback(file):
1816 """Read the paired .xyz file when the .out has no final-geometry block.
1817
1818 Returns (atom_nums, atom_types, cartesians) — empty lists if not readable.
1819 """
1820 xyz = os.path.splitext(file)[0] + '.xyz'
1821 if not os.path.exists(xyz):
1822 return [], [], []
1823 try:
1824 with open(xyz, encoding='utf-8', errors='replace') as f:
1825 lines = f.readlines()
1826 except OSError:
1827 return [], [], []
1828 if len(lines) < 2:
1829 return [], [], []
1830 try:
1831 natoms = int(lines[0].strip())
1832 except (ValueError, IndexError):
1833 return [], [], []
1834 atom_nums, atom_types, cartesians = [], [], []
1835 for line in lines[2:2 + natoms]:
1836 parts = line.split()
1837 if len(parts) < 4:
1838 continue
1839 elem = parts[0]
1840 try:
1841 atom_types.append(elem)
1842 atom_nums.append(element_id(elem, num=True))
1843 cartesians.append([float(parts[1]), float(parts[2]), float(parts[3])])
1844 except ValueError:
1845 continue
1846 return atom_nums, atom_types, cartesians
1847
1848
1849 def parse_xtb_thermo(file):
1850 """Parse xtb output for all thermochemistry-relevant data.
1851
1852 xtb takes a ``.xyz`` coordinate file plus CLI flags rather than an input
1853 deck. The parser handles single-point (``xtb file.xyz``), Hessian-only
1854 (``--hess``), and optimization+Hessian (``--ohess``) jobs, plus implicit
1855 solvation (GBSA via ``-g``, ALPB via ``--alpb``, CPCM-X via ``--cpcmx``).
1856
1857 For runs without ``--opt``/``--ohess`` (no optimized-geometry block in the
1858 output), Cartesians fall back to the paired ``.xyz`` input file.
1859
1860 Parameters
1861 ----------
1862 file : str
1863 Path to xtb output file.
1864 """
1865 qcdata = QCData(file=file, program='xtb')
1866
1867 with open(file, encoding='utf-8', errors='replace') as f:
1868 output = f.readlines()
1869
1870 # Empty / aborted runs: bail out early but record the program.
1871 if not output or any('[ERROR]' in line for line in output):
1872 if any('xtb version' in line for line in output):
1873 for line in output:
1874 if 'xtb version' in line:
1875 parts = line.split()
1876 try:
1877 qcdata.version_program = 'xtb version ' + parts[parts.index('version') + 1]
1878 except (ValueError, IndexError):
1879 pass
1880 break
1881 return qcdata
1882
1883 HC_OVER_KB = 1.4387768775 # K per cm⁻¹
1884
1885 frequency_wn = []
1886 im_frequency_wn = []
1887 last_freq_idx = -1
1888 program_call = ''
1889
1890 # First pass: locate the LAST vibrational-frequencies header. Linear
1891 # molecules and atoms use the ``vibrational frequencies (cm⁻¹)`` form;
1892 # everything else uses ``projected vibrational frequencies (cm⁻¹)``.
1893 for i, line in enumerate(output):
1894 if 'vibrational frequencies' in line and '(cm' in line:
1895 last_freq_idx = i
1896
1897 # Second pass: extract scalar fields and geometry; freq parsing happens once
1898 for i, line in enumerate(output):
1899 stripped = line.strip()
1900
1901 # --- Version
1902 if 'xtb version' in stripped and not qcdata.version_program:
1903 parts = stripped.split()
1904 try:
1905 qcdata.version_program = 'xtb version ' + parts[parts.index('version') + 1]
1906 except (ValueError, IndexError):
1907 pass
1908
1909 # --- Program call line (for solvation flag parsing)
1910 elif 'program call' in stripped and ':' in stripped and not program_call:
1911 program_call = stripped.split(':', 1)[1].strip()
1912
1913 # --- Charge: ": net charge <n> :"
1914 elif 'net charge' in stripped and stripped.startswith(':'):
1915 parts = stripped.split()
1916 try:
1917 qcdata.charge = int(parts[parts.index('charge') + 1])
1918 except (ValueError, IndexError):
1919 pass
1920
1921 # --- Multiplicity from "unpaired electrons" (mult = unpaired + 1)
1922 elif 'unpaired electrons' in stripped and stripped.startswith(':'):
1923 parts = stripped.split()
1924 try:
1925 unpaired = int(parts[parts.index('electrons') + 1])
1926 qcdata.multiplicity = unpaired + 1
1927 except (ValueError, IndexError):
1928 pass
1929
1930 # --- Electronic SCF energy ":: total energy <E> Eh ::"
1931 # Last occurrence wins (final SCC after opt, or sole SCC for SP)
1932 elif stripped.startswith(':: total energy'):
1933 parts = stripped.split()
1934 try:
1935 qcdata.scf_energy = float(parts[3])
1936 except (ValueError, IndexError):
1937 pass
1938
1939 # --- Zero-point energy
1940 elif stripped.startswith(':: zero point energy'):
1941 parts = stripped.split()
1942 try:
1943 qcdata.zero_point_corr = float(parts[4])
1944 except (ValueError, IndexError):
1945 pass
1946
1947 # --- Molecular mass: "molecular mass/u : <m>"
1948 elif stripped.startswith('molecular mass/u'):
1949 parts = stripped.split()
1950 try:
1951 qcdata.molecular_mass = float(parts[-1])
1952 except (ValueError, IndexError):
1953 pass
1954
1955 # --- Rotational constants in cm⁻¹: "rotational constants/cm⁻¹ : B1 B2 B3"
1956 # xtb prints "Infinity" for atoms (no rotation); skip in that case.
1957 elif stripped.startswith('rotational constants/cm'):
1958 parts = stripped.split(':', 1)[1].split() if ':' in stripped else stripped.split()
1959 if 'Infinity' in parts[:3]:
1960 pass # atom: leave roconst/rotemp at defaults
1961 else:
1962 try:
1963 roconst_cm = [float(parts[0]), float(parts[1]), float(parts[2])]
1964 qcdata.roconst = [b * 29.9792458 for b in roconst_cm]
1965 qcdata.rotemp = [HC_OVER_KB * b for b in roconst_cm]
1966 except (IndexError, ValueError):
1967 pass
1968
1969 # --- Linear marker (thermo SETUP block)
1970 elif 'linear?' in stripped and stripped.startswith(':'):
1971 if 'true' in stripped:
1972 qcdata.linear_mol = True
1973
1974 # --- Point group from "symmetry <pg>"
1975 elif stripped.startswith(':') and 'symmetry' in stripped and 'rotational' not in stripped:
1976 parts = stripped.split()
1977 try:
1978 idx = parts.index('symmetry')
1979 if idx + 1 < len(parts) and parts[idx + 1] != ':':
1980 pg = parts[idx + 1]
1981 if pg not in ('GBSA', 'found', 'elements:'):
1982 qcdata.point_group = pg
1983 except ValueError:
1984 pass
1985
1986 # --- Symmetry number ": rotational number <n> :"
1987 elif 'rotational number' in stripped and stripped.startswith(':'):
1988 parts = stripped.split()
1989 try:
1990 qcdata.symmno = int(parts[parts.index('number') + 1])
1991 except (ValueError, IndexError):
1992 pass
1993
1994 # --- Final optimized geometry block (only present for --opt/--ohess)
1995 elif stripped == 'final structure:':
1996 # Skip the "===" line; line i+1 is "===", i+2 is atom count, i+3 is comment
1997 try:
1998 natoms = int(output[i + 2].strip())
1999 except (ValueError, IndexError):
2000 continue
2001 atom_nums_tmp = []
2002 atom_types_tmp = []
2003 cartesians_tmp = []
2004 for k in range(i + 4, i + 4 + natoms):
2005 if k >= len(output):
2006 break
2007 parts = output[k].split()
2008 if len(parts) < 4:
2009 break
2010 try:
2011 atom_types_tmp.append(parts[0])
2012 atom_nums_tmp.append(element_id(parts[0], num=True))
2013 cartesians_tmp.append([float(parts[1]), float(parts[2]), float(parts[3])])
2014 except ValueError:
2015 break
2016 qcdata.atom_nums = atom_nums_tmp
2017 qcdata.atom_types = atom_types_tmp
2018 qcdata.cartesians = cartesians_tmp
2019
2020 # --- CPU time from "total:" block: "* cpu-time: <D> d, <H> h, <M> min, <S> sec"
2021 # xtb prints two spaces ("* cpu-time:") so match the substring.
2022 elif 'cpu-time:' in stripped and stripped.startswith('*') and qcdata.cpu == [0, 0, 0, 0, 0]:
2023 # First (= "total:") cpu-time line; subsequent are SCF/ANC/hess subtimers
2024 parts = stripped.replace(',', ' ').split()
2025 try:
2026 d_idx = parts.index('d')
2027 h_idx = parts.index('h')
2028 m_idx = parts.index('min')
2029 s_idx = parts.index('sec')
2030 days = int(parts[d_idx - 1])
2031 hours = int(parts[h_idx - 1])
2032 mins = int(parts[m_idx - 1])
2033 secs_float = float(parts[s_idx - 1])
2034 secs = int(secs_float)
2035 msecs = int((secs_float - secs) * 1000)
2036 qcdata.cpu = [days, hours, mins, secs, msecs]
2037 except (ValueError, IndexError):
2038 pass
2039
2040 # Frequencies from the LAST projected-vibrational-frequencies block.
2041 # xtb prints all 3N modes; the first 5 (linear) or 6 (non-linear) are the
2042 # zero translational/rotational eigenvalues from projection — skip them by
2043 # filtering |v| < 1.0 cm⁻¹. Negatives below that are imaginary modes.
2044 if last_freq_idx >= 0:
2045 for k in range(last_freq_idx + 1, len(output)):
2046 parts = output[k].split()
2047 if not parts or parts[0] != 'eigval':
2048 break
2049 for tok in parts[2:]:
2050 try:
2051 v = float(tok)
2052 except ValueError:
2053 continue
2054 if abs(v) < 1.0:
2055 continue
2056 if v > 0:
2057 frequency_wn.append(v)
2058 else:
2059 im_frequency_wn.append(v)
2060 qcdata.frequency_wn = frequency_wn
2061 qcdata.im_frequency_wn = im_frequency_wn
2062
2063 # Multiplicity: if `unpaired electrons` was missing from output, leave at default 1.
2064
2065 # Solvation: parse from program call line
2066 if program_call:
2067 qcdata.solvation_model = _xtb_solvation_from_call(program_call)
2068 else:
2069 qcdata.solvation_model = 'gas phase'
2070
2071 # xtb has no DFT dispersion; GFN includes its own D3/D4 implicitly.
2072 qcdata.empirical_dispersion = 'No empirical dispersion detected'
2073
2074 # Geometry fallback: SP-only and --hess runs lack a 'final structure:' block.
2075 if not qcdata.atom_nums:
2076 atom_nums, atom_types, cartesians = _xtb_read_xyz_fallback(file)
2077 if atom_nums:
2078 qcdata.atom_nums = atom_nums
2079 qcdata.atom_types = atom_types
2080 qcdata.cartesians = cartesians
2081
2082 # Mass / rotational fallback: --hess-only runs print frequencies but skip
2083 # the THERMODYNAMIC block, so 'molecular mass / u' and 'rotational
2084 # constants / cm⁻¹' are absent. Recompute from the geometry we just
2085 # loaded (B [cm⁻¹] = h/(8π²cI) ≈ 16.857629 / I[amu·Å²]).
2086 if (qcdata.molecular_mass == 0.0 or qcdata.rotemp == [0.0, 0.0, 0.0]) \
2087 and qcdata.atom_types and qcdata.cartesians:
2088 total_mass, eigvals = _principal_moments_of_inertia(
2089 qcdata.atom_types, qcdata.cartesians)
2090 if qcdata.molecular_mass == 0.0:
2091 qcdata.molecular_mass = total_mass
2092 if qcdata.rotemp == [0.0, 0.0, 0.0]:
2093 roconst_cm = [16.857629 / I if I > 1e-3 else 0.0 for I in eigvals] # noqa: E741
2094 qcdata.roconst = [b * 29.9792458 for b in roconst_cm]
2095 qcdata.rotemp = [HC_OVER_KB * b for b in roconst_cm]
2096
2097 # Linear molecules: keep only physical rotational temperatures. xtb
2098 # inverts a near-zero moment of inertia for the linear axis, producing
2099 # either a huge positive number (e.g. 1e27 K) or a huge negative one;
2100 # restrict to 0 < T_rot < 1e10 K to drop both pathological cases.
2101 if qcdata.linear_mol and qcdata.rotemp:
2102 physical = [t for t in qcdata.rotemp if 0.0 < t < 1.0e10]
2103 if physical:
2104 qcdata.rotemp = physical
2105 qcdata.roconst = [t / HC_OVER_KB * 29.9792458 for t in physical]
2106
2107 # Job type from observed content
2108 has_opt_geom = any('final structure:' in line for line in output)
2109 has_freq = bool(frequency_wn) or bool(im_frequency_wn)
2110 if has_opt_geom and has_freq:
2111 qcdata.job_type = 'GSFreq'
2112 elif has_opt_geom:
2113 qcdata.job_type = 'GS'
2114 elif has_freq:
2115 qcdata.job_type = 'Freq'
2116 else:
2117 qcdata.job_type = 'SP'
2118
2119 return qcdata
2120
2121
2122 # Bohr → Ångström conversion (squared, for amu*Bohr² → amu*Ų)
2123 _BOHR2_TO_ANGSTROM2 = 0.5291772109 ** 2
2124
2125
2126 def parse_qchem_thermo(file):
2127 """Parse a Q-Chem 6 output file for all thermochemistry-relevant data.
2128
2129 Handles single-job and multi-job (`@@@`-separated opt + freq + sp) inputs:
2130 the LAST occurrence wins for SCF energy, geometry, and frequencies, so
2131 the converged opt geometry and post-correlation energies are picked up
2132 correctly. Recognises native HF/DFT total energy, MP2 total energy, CCSD
2133 total energy, and CCSD(T) total energy via the precedence
2134 CCSD(T) > CCSD > MP2 > Total energy.
2135
2136 Parameters
2137 ----------
2138 file : str
2139 Path to a Q-Chem 6 output file.
2140 """
2141 qcdata = QCData(file=file, program='QChem')
2142
2143 with open(file, encoding='utf-8', errors='replace') as f:
2144 output = f.readlines()
2145
2146 if not output:
2147 return qcdata
2148
2149 HC_OVER_KB = 1.4387768775 # K per cm⁻¹
2150
2151 # First pass: locate the last freq block, last geometry block, last
2152 # thermo header, and the input $molecule + $rem echoes (for charge,
2153 # multiplicity, and the requested correlation method).
2154 last_geom_header = -1
2155 last_thermo_header = -1
2156 last_freq_header = -1
2157 molecule_block_lines = []
2158 rem_methods = []
2159 in_molecule_block = False
2160 in_rem_block = False
2161 user_input_seen = False
2162
2163 for i, line in enumerate(output):
2164 stripped = line.strip()
2165 if 'You are running Q-Chem version' in stripped:
2166 try:
2167 qcdata.version_program = 'Q-Chem version ' + stripped.split('version:')[1].strip()
2168 except IndexError:
2169 pass
2170 elif 'User input:' in stripped:
2171 user_input_seen = True
2172 elif user_input_seen and stripped == '$molecule' and not molecule_block_lines:
2173 in_molecule_block = True
2174 continue
2175 elif in_molecule_block:
2176 if stripped == '$end' or stripped.startswith('$'):
2177 in_molecule_block = False
2178 elif stripped:
2179 molecule_block_lines.append(stripped)
2180 elif user_input_seen and stripped.lower() == '$rem':
2181 in_rem_block = True
2182 continue
2183 elif in_rem_block:
2184 if stripped == '$end' or stripped.startswith('$'):
2185 in_rem_block = False
2186 elif stripped and not stripped.startswith('!'):
2187 parts = stripped.split()
2188 if len(parts) >= 2 and parts[0].lower() == 'method':
2189 rem_methods.append(parts[1].lower())
2190 if 'Standard Nuclear Orientation (Angstroms)' in line:
2191 last_geom_header = i
2192 # Anchor on the harmonic block ("AT 298.15 K AND ..."); skip the
2193 # anharmonic VPT2/TOSH summaries that print only ZPE.
2194 if 'STANDARD THERMODYNAMIC QUANTITIES AT' in line:
2195 last_thermo_header = i
2196 if stripped.startswith('Frequency:'):
2197 last_freq_header = i
2198
2199 # Method of the FINAL job step decides which energy line to trust.
2200 final_method = rem_methods[-1] if rem_methods else ''
2201
2202 # Charge / multiplicity from the input $molecule block.
2203 # First non-`READ` line is "<charge> <mult>".
2204 for line in molecule_block_lines:
2205 s = line.strip()
2206 if s.upper() == 'READ':
2207 continue
2208 parts = s.split()
2209 if len(parts) >= 2:
2210 try:
2211 qcdata.charge = int(parts[0])
2212 qcdata.multiplicity = int(parts[1])
2213 except ValueError:
2214 pass
2215 break
2216
2217 # Multiplicity fallback from "There are N alpha and M beta electrons".
2218 if qcdata.multiplicity == 1:
2219 for line in output:
2220 if 'alpha and' in line and 'beta electrons' in line:
2221 parts = line.split()
2222 try:
2223 nalpha = int(parts[parts.index('alpha') - 1])
2224 nbeta = int(parts[parts.index('beta') - 1])
2225 qcdata.multiplicity = abs(nalpha - nbeta) + 1
2226 except (ValueError, IndexError):
2227 pass
2228
2229 # Energies — collect candidates; pick by FINAL method, not by precedence.
2230 # Q-Chem prints "MP2 total energy" as an extra analysis even when the
2231 # method is e.g. B2PLYP (a double hybrid that's properly captured by the
2232 # SCF "Total energy" line), so we can't blindly prefer correlated lines.
2233 scf_total = None
2234 mp2_total = None
2235 ccsd_total = None
2236 ccsdt_total = None
2237 for line in output:
2238 stripped = line.strip()
2239 if stripped.startswith('Total energy ='):
2240 try:
2241 scf_total = float(stripped.split('=')[1].split()[0])
2242 except (IndexError, ValueError):
2243 pass
2244 elif 'MP2' in stripped and 'total energy =' in stripped:
2245 try:
2246 mp2_total = float(stripped.split('=')[1].split()[0])
2247 except (IndexError, ValueError):
2248 pass
2249 elif stripped.startswith('CCSD total energy') or stripped.startswith('CCSD total energy'):
2250 try:
2251 ccsd_total = float(stripped.split('=')[1].split()[0])
2252 except (IndexError, ValueError):
2253 pass
2254 elif stripped.startswith('CCSD(T) total energy'):
2255 try:
2256 ccsdt_total = float(stripped.split('=')[1].split()[0])
2257 except (IndexError, ValueError):
2258 pass
2259 if 'ccsd(t)' in final_method and ccsdt_total is not None:
2260 qcdata.scf_energy = ccsdt_total
2261 elif final_method == 'ccsd' and ccsd_total is not None:
2262 qcdata.scf_energy = ccsd_total
2263 elif final_method in ('mp2', 'rimp2', 'ump2') and mp2_total is not None:
2264 qcdata.scf_energy = mp2_total
2265 else:
2266 qcdata.scf_energy = scf_total
2267
2268 # Solvation
2269 solvation_type = ''
2270 solvent_name = ''
2271 for line in output:
2272 stripped = line.strip()
2273 if 'Using C-PCM' in stripped or 'C-PCM dielectric factor' in stripped:
2274 solvation_type = solvation_type or 'CPCM'
2275 elif 'Using the SMD solvation model' in stripped:
2276 solvation_type = 'SMD'
2277 elif stripped.startswith('Solvent:'):
2278 try:
2279 solvent_name = stripped.split(':', 1)[1].strip()
2280 except IndexError:
2281 pass
2282 if solvation_type:
2283 qcdata.solvation_model = (solvation_type + ',' + solvent_name) if solvent_name else solvation_type
2284
2285 # Final geometry — read from the LAST Standard Nuclear Orientation block.
2286 if last_geom_header >= 0:
2287 atom_nums, atom_types, cartesians = [], [], []
2288 # Skip 2 header lines + the dashes line before atoms.
2289 i = last_geom_header + 3
2290 while i < len(output):
2291 parts = output[i].split()
2292 if len(parts) >= 5:
2293 try:
2294 int(parts[0]) # row index
2295 elem = parts[1]
2296 xyz = [float(parts[2]), float(parts[3]), float(parts[4])]
2297 atom_types.append(elem)
2298 atom_nums.append(element_id(elem, num=True))
2299 cartesians.append(xyz)
2300 i += 1
2301 continue
2302 except ValueError:
2303 pass
2304 break
2305 qcdata.atom_types = atom_types
2306 qcdata.atom_nums = atom_nums
2307 qcdata.cartesians = cartesians
2308
2309 # Frequencies — collect from contiguous Frequency: lines starting at the last header.
2310 if last_freq_header >= 0:
2311 # Walk forward from the last_freq_header but we want all preceding
2312 # contiguous Frequency: lines that belong to the same final block.
2313 # Strategy: scan the file once more and collect freqs from the LAST
2314 # contiguous run of Frequency: lines (separated only by columns of
2315 # mode data, never by another major section header).
2316 freq_blocks = []
2317 current = []
2318 for line in output:
2319 stripped = line.strip()
2320 if stripped.startswith('Frequency:'):
2321 try:
2322 nums = [float(x) for x in stripped.split(':', 1)[1].split()]
2323 current.extend(nums)
2324 except ValueError:
2325 pass
2326 elif current and ('STANDARD THERMODYNAMIC' in line or
2327 'Standard Nuclear Orientation' in line):
2328 # End of a freq block; new section ahead.
2329 freq_blocks.append(current)
2330 current = []
2331 if current:
2332 freq_blocks.append(current)
2333 if freq_blocks:
2334 freqs = freq_blocks[-1]
2335 qcdata.frequency_wn = [f for f in freqs if f >= 0]
2336 qcdata.im_frequency_wn = [f for f in freqs if f < 0]
2337
2338 # Point group: printed once per SCF (before the thermo block); take LAST.
2339 for line in output:
2340 if 'Molecular Point Group' in line:
2341 try:
2342 after = line.split('Molecular Point Group', 1)[1].strip()
2343 qcdata.point_group = after.split()[0]
2344 except (IndexError, ValueError):
2345 pass
2346
2347 # Thermo block: ZPE, mass, symmno, principal moments (last block wins).
2348 if last_thermo_header >= 0:
2349 for line in output[last_thermo_header:]:
2350 stripped = line.strip()
2351 if stripped.startswith('Zero point vibrational energy:'):
2352 # "Zero point vibrational energy: 14.050 kcal/mol"
2353 try:
2354 zpe_kcal = float(stripped.split(':')[1].split()[0])
2355 qcdata.zero_point_corr = zpe_kcal / 627.509541
2356 except (IndexError, ValueError):
2357 pass
2358 elif stripped.startswith('Molecular Mass:'):
2359 try:
2360 qcdata.molecular_mass = float(stripped.split(':')[1].split()[0])
2361 except (IndexError, ValueError):
2362 pass
2363 elif stripped.startswith('Eigenvalues --'):
2364 try:
2365 eigs_bohr2 = [float(x) for x in stripped.split('--', 1)[1].split()][:3]
2366 eigs_a2 = [e * _BOHR2_TO_ANGSTROM2 for e in eigs_bohr2]
2367 nonzero = [e for e in eigs_a2 if e > 1e-6]
2368 if len(nonzero) == 2: # linear
2369 qcdata.linear_mol = True
2370 B_cm = 16.857629 / nonzero[-1]
2371 qcdata.roconst = [B_cm * 29.9792458] * 3
2372 qcdata.rotemp = [HC_OVER_KB * B_cm] * 3
2373 elif len(nonzero) == 3:
2374 roconst_cm = [16.857629 / I for I in nonzero] # noqa: E741
2375 qcdata.roconst = [b * 29.9792458 for b in roconst_cm]
2376 qcdata.rotemp = [HC_OVER_KB * b for b in roconst_cm]
2377 except (IndexError, ValueError):
2378 pass
2379 elif 'Rotational Symmetry Number is' in stripped:
2380 try:
2381 qcdata.symmno = int(stripped.split('is')[1].split()[0])
2382 except (IndexError, ValueError):
2383 pass
2384
2385 # CPU time: "Total job time: 1.70s(wall), 21.27s(cpu)" — take the (cpu)
2386 # value (the wall × ncores estimate Q-Chem prints) so the sum matches
2387 # the Gaussian/NWChem/xTB convention of true summed CPU.
2388 for line in reversed(output):
2389 if 'Total job time:' in line:
2390 try:
2391 cpu_s = float(line.split(',')[1].split('s(cpu)')[0].strip())
2392 days = int(cpu_s // 86400)
2393 rem = cpu_s - days * 86400
2394 hours = int(rem // 3600)
2395 rem -= hours * 3600
2396 mins = int(rem // 60)
2397 rem -= mins * 60
2398 secs = int(rem)
2399 ms = int(round((rem - secs) * 1000))
2400 qcdata.cpu = [days, hours, mins, secs, ms]
2401 except (IndexError, ValueError):
2402 pass
2403 break
2404
2405 # Job type from observed content.
2406 has_freq = bool(qcdata.frequency_wn) or bool(qcdata.im_frequency_wn)
2407 has_geom_block = last_geom_header >= 0
2408 if qcdata.im_frequency_wn:
2409 qcdata.job_type = 'TS'
2410 elif has_geom_block and has_freq:
2411 qcdata.job_type = 'GSFreq'
2412 elif has_freq:
2413 qcdata.job_type = 'Freq'
2414 else:
2415 qcdata.job_type = 'SP'
2416
2417 return qcdata
2418
2419
2420 # Regex matching extxyz comment-line tokens: bare key=value or key="value with spaces"
2421 _EXTXYZ_TOKEN = re.compile(r'(\w+)=("(?:[^"\\]|\\.)*"|\S+)')
2422
2423
2424 def _parse_extxyz_comment(line):
2425 """Parse an extxyz comment line into a {key: str} dict.
2426
2427 Strips surrounding double quotes from quoted values; leaves unquoted values
2428 untouched. Caller is responsible for type coercion.
2429 """
2430 out = {}
2431 for key, val in _EXTXYZ_TOKEN.findall(line):
2432 if len(val) >= 2 and val[0] == '"' and val[-1] == '"':
2433 val = val[1:-1]
2434 out[key] = val
2435 return out
2436
2437
2438 def _extxyz_bool(s):
2439 """Decode an extxyz boolean (T/F/True/False) to a Python bool."""
2440 return str(s).strip().lower() in ('t', 'true', '1', 'yes')
2441
2442
2443 def parse_ase_thermo(file):
2444 """Parse a GoodVibes ASE thermo extxyz file.
2445
2446 The format is standard extended XYZ with thermochemistry metadata in the
2447 second line (key=value, ASE Atoms.info convention). Required keys:
2448 ``program=ase``, ``scf_energy``. Frequencies are space-separated in cm-1
2449 (negatives are imaginary). See tests/ase/README.md for the full spec.
2450 """
2451 qcdata = QCData(file=file, program='ase')
2452
2453 with open(file, encoding='utf-8', errors='replace') as f:
2454 lines = f.readlines()
2455 if len(lines) < 2:
2456 return qcdata
2457 try:
2458 natoms = int(lines[0].strip())
2459 except ValueError:
2460 return qcdata
2461
2462 info = _parse_extxyz_comment(lines[1])
2463
2464 # Provenance
2465 qcdata.version_program = info.get('ase_version', 'ase')
2466
2467 # Charge / multiplicity (defaults: 0 / 1)
2468 try:
2469 qcdata.charge = int(float(info.get('charge', '0')))
2470 except ValueError:
2471 qcdata.charge = 0
2472 try:
2473 qcdata.multiplicity = int(float(info.get('multiplicity', '1')))
2474 except ValueError:
2475 qcdata.multiplicity = 1
2476
2477 # Electronic energy (Hartree by default; eV converted)
2478 if 'scf_energy' in info:
2479 try:
2480 e = float(info['scf_energy'])
2481 units = info.get('scf_energy_units', 'Hartree').lower()
2482 if units in ('ev',):
2483 e = e / 27.211386245988
2484 elif units in ('kcal/mol', 'kcalmol'):
2485 e = e / 627.509541
2486 elif units in ('kj/mol', 'kjmol'):
2487 e = e / 2625.4996394799
2488 qcdata.scf_energy = e
2489 except ValueError:
2490 pass
2491
2492 # Zero-point energy (Hartree)
2493 if 'zpe' in info:
2494 try:
2495 qcdata.zero_point_corr = float(info['zpe'])
2496 except ValueError:
2497 pass
2498
2499 # Frequencies (cm-1; negatives are imaginary)
2500 if 'frequencies' in info:
2501 for tok in info['frequencies'].split():
2502 try:
2503 v = float(tok)
2504 except ValueError:
2505 continue
2506 if v < 0:
2507 qcdata.im_frequency_wn.append(v)
2508 else:
2509 qcdata.frequency_wn.append(v)
2510
2511 # Optional model-chemistry metadata
2512 qcdata.solvation_model = info.get('solvation_model', '')
2513 qcdata.empirical_dispersion = info.get('empirical_dispersion', '')
2514 qcdata.point_group = info.get('point_group', '')
2515 if 'symmno' in info:
2516 try:
2517 qcdata.symmno = int(float(info['symmno']))
2518 except ValueError:
2519 pass
2520 if 'linear_mol' in info:
2521 qcdata.linear_mol = _extxyz_bool(info['linear_mol'])
2522 if 'applied_freq_scale_factor' in info:
2523 try:
2524 qcdata.applied_freq_scale_factor = float(info['applied_freq_scale_factor'])
2525 except ValueError:
2526 pass
2527
2528 # Atom block: species, x, y, z (additional columns ignored)
2529 atom_nums, atom_types, cartesians = [], [], []
2530 for line in lines[2:2 + natoms]:
2531 parts = line.split()
2532 if len(parts) < 4:
2533 continue
2534 elem = parts[0]
2535 try:
2536 xyz = [float(parts[1]), float(parts[2]), float(parts[3])]
2537 except ValueError:
2538 continue
2539 atom_types.append(elem)
2540 atom_nums.append(element_id(elem, num=True))
2541 cartesians.append(xyz)
2542 qcdata.atom_types = atom_types
2543 qcdata.atom_nums = atom_nums
2544 qcdata.cartesians = cartesians
2545
2546 # Molecular mass: explicit override, else compute from atomic masses
2547 if 'molecular_mass' in info:
2548 try:
2549 qcdata.molecular_mass = float(info['molecular_mass'])
2550 except ValueError:
2551 pass
2552 if not qcdata.molecular_mass and atom_types:
2553 qcdata.molecular_mass = sum(ATOMIC_MASSES.get(a, 0.0) for a in atom_types)
2554
2555 # Rotational constants: explicit override (cm-1), else derived from inertia
2556 HC_OVER_KB = 1.4387768775 # K per cm⁻¹
2557 if 'roconst_cm' in info:
2558 try:
2559 roconst_cm = [float(t) for t in info['roconst_cm'].split()][:3]
2560 qcdata.roconst = [b * 29.9792458 for b in roconst_cm]
2561 qcdata.rotemp = [HC_OVER_KB * b for b in roconst_cm]
2562 except ValueError:
2563 pass
2564 elif 'rotemp' in info:
2565 try:
2566 qcdata.rotemp = [float(t) for t in info['rotemp'].split()][:3]
2567 qcdata.roconst = [t / HC_OVER_KB * 29.9792458 for t in qcdata.rotemp]
2568 except ValueError:
2569 pass
2570 if not any(qcdata.rotemp) and len(atom_types) >= 2:
2571 _mass, eigvals = _principal_moments_of_inertia(atom_types, cartesians)
2572 # Linear molecules: smallest principal moment is ~0.
2573 nonzero = [e for e in eigvals if e > 1e-3]
2574 if not qcdata.linear_mol and len(nonzero) == 2:
2575 qcdata.linear_mol = True
2576 if qcdata.linear_mol:
2577 # Use the largest two equal moments; physics needs a single B.
2578 B_cm = 16.857629 / nonzero[-1] # cm⁻¹
2579 qcdata.roconst = [B_cm * 29.9792458] * 3
2580 qcdata.rotemp = [HC_OVER_KB * B_cm] * 3
2581 elif len(nonzero) == 3:
2582 roconst_cm = [16.857629 / I for I in nonzero] # noqa: E741
2583 qcdata.roconst = [b * 29.9792458 for b in roconst_cm]
2584 qcdata.rotemp = [HC_OVER_KB * b for b in roconst_cm]
2585
2586 # Job type: explicit override, else infer from frequency presence/sign
2587 if 'job_type' in info:
2588 qcdata.job_type = info['job_type']
2589 else:
2590 if qcdata.im_frequency_wn:
2591 qcdata.job_type = 'TS'
2592 elif qcdata.frequency_wn:
2593 qcdata.job_type = 'Freq'
2594 else:
2595 qcdata.job_type = 'SP'
2596
2597 return qcdata
2598
2599
2600 def parse_qcdata(file):
2601 """Parse any supported output file into a QCData object.
2602
2603 Detects program from file content and delegates to the correct parser.
2604
2605 Parameters
2606 ----------
2607 file : str
2608 Path to quantum chemistry output file.
2609 """
2610 stub = os.path.splitext(file)[0]
2611 possible_filenames = (stub + '.log', stub + '.out', stub + '.extxyz', file)
2612 data = None
2613 actual_file = file
2614 for possible_filename in possible_filenames:
2615 if os.path.exists(possible_filename):
2616 actual_file = possible_filename
2617 with open(possible_filename, encoding='utf-8', errors='replace') as f:
2618 data = f.readlines()
2619 break
2620
2621 if data is None:
2622 return QCData(file=file, program='unknown')
2623
2624 # Detect program from first ~80 lines (Q-Chem banner is past the SLURM preamble)
2625 program = 'unknown'
2626 for line in data[:80]:
2627 if 'Gaussian' in line:
2628 program = 'Gaussian'
2629 break
2630 if '* O R C A *' in line:
2631 program = 'Orca'
2632 break
2633 if 'NWChem' in line:
2634 program = 'NWChem'
2635 break
2636 if 'x T B' in line or 'xtb version' in line:
2637 program = 'xtb'
2638 break
2639 if 'You are running Q-Chem' in line or 'Welcome to Q-Chem' in line:
2640 program = 'QChem'
2641 break
2642 # ASE extxyz: program=ase appears in the comment line (2nd line).
2643 if program == 'unknown' and len(data) >= 2 and 'program=ase' in data[1]:
2644 program = 'ase'
2645
2646 if program == 'Gaussian':
2647 return parse_gaussian_thermo(actual_file)
2648 elif program == 'Orca':
2649 return parse_orca_thermo(actual_file)
2650 elif program == 'NWChem':
2651 return parse_nwchem_thermo(actual_file)
2652 elif program == 'xtb':
2653 return parse_xtb_thermo(actual_file)
2654 elif program == 'QChem':
2655 return parse_qchem_thermo(actual_file)
2656 elif program == 'ase':
2657 return parse_ase_thermo(actual_file)
2658 else:
2659 return QCData(file=file, program='unknown')