File size: 23,448 Bytes
39ea985 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 | """Pass A parser: one ORCA 6.0 calculation (orca.out + orca.engrad) -> a plain-python record.
Design notes
------------
* Single forward scan over orca.out. The file can be 600 MB, so nothing is loaded whole: the FOCK
block is consumed straight from the line iterator into its final numpy array.
* The scanner is a pushback iterator, so a sub-parser that reads one line too far can hand it back;
otherwise a section's terminating line (often the *next* section's header) would be swallowed.
* Every section is optional. Datasets differ (NBO on/off, RHF/UHF, ECPs, linear dependencies), so a
missing section leaves its fields as None rather than raising.
* The Fock matrix is returned as an int32 upper triangle in micro-Hartree, which is the storage
encoding and is lossless with respect to ORCA's 6-decimal print.
* Reduced orbital populations are aggregated to shell totals (s, p, d, f, g) per atom; the
individual components (pz, dxy, ...) are voluminous and low value, so they are skipped.
Returns a dict with keys grouped as: meta / system / atoms / pairs / orbitals / fock.
"""
from __future__ import annotations
import io, os, re, subprocess, tarfile
import numpy as np
SHELLS = ("s", "p", "d", "f", "g")
EH_TO_UEH = 1e6
_COLHDR = re.compile(r"^\s+0(\s+\d+)+\s*$")
_BOND = re.compile(r"B\(\s*(\d+)-\s*(\w+)\s*,\s*(\d+)-\s*(\w+)\s*\)\s*:\s*(-?\d+\.\d+)")
class _PB:
"""Line iterator with one-line pushback."""
def __init__(self, it):
self._it = iter(it)
self._buf = []
def __iter__(self):
return self
def __next__(self):
if self._buf:
return self._buf.pop()
return next(self._it)
def next(self, default=""):
try:
return self.__next__()
except StopIteration:
return default
def push(self, line):
self._buf.append(line)
def _f(tok):
try:
return float(tok)
except (TypeError, ValueError):
return None
def _after(line, sep):
_, _, rest = line.partition(sep)
return rest.strip()
def _num_after_colon(line):
return _f(line.split(":")[-1].split()[0]) if ":" in line else None
def _is_rule(t):
return bool(t) and set(t) <= set("-=*")
# ----------------------------------------------------------------------------- Fock block
def _read_matrix(pb, nbas, hdr):
"""Read one nbas x nbas matrix printed in column blocks, given its first header line."""
F = np.zeros((nbas, nbas), dtype=np.float64)
done = 0
while done < nbas:
while hdr.strip() == "":
hdr = next(pb)
ncol = len(hdr.split())
rows = [next(pb) for _ in range(nbas)]
blk = np.fromstring(" ".join(rows), sep=" ", dtype=np.float64)
blk = blk.reshape(nbas, ncol + 1)[:, 1:]
F[:, done:done + ncol] = blk
done += ncol
if done < nbas:
hdr = next(pb)
return F
def _tri_u_eh(F):
iu = np.triu_indices(F.shape[0])
return np.rint(F[iu] * EH_TO_UEH).astype(np.int32)
def _next_matrix_header(pb, max_skip=6):
"""Look for a column header, skipping blank and rule lines ('----', '****').
Anything else is pushed back and None is returned."""
for _ in range(max_skip + 1):
line = pb.next(None)
if line is None:
return None
t = line.strip()
if t == "" or _is_rule(t):
continue
if _COLHDR.match(line):
return line
pb.push(line)
return None
return None
# ----------------------------------------------------------------------------- sub-parsers
def _atom_charges(pb):
"""' 0 Xe: 1.277884 [spin]' rows. Returns (charge, spin|None)."""
q, sp = [], []
for l2 in pb:
t = l2.strip()
if _is_rule(t):
continue
if not t:
if q:
break
continue
if ":" not in t:
pb.push(l2)
break
head, _, rest = l2.partition(":")
hp = head.split()
if not hp or not hp[0].isdigit():
pb.push(l2)
break
vals = rest.split()
if not vals:
break
q.append(float(vals[0]))
if len(vals) > 1:
sp.append(float(vals[1]))
return (np.array(q) if q else None, np.array(sp) if sp else None)
def _reduced_shells(pb, natm):
"""Per-atom shell totals from a REDUCED ORBITAL CHARGES block. Returns (charge, spin|None),
each (natm, len(SHELLS)) or None."""
if not natm:
return None, None
charge = np.zeros((natm, len(SHELLS)))
spin = None
target = charge
atom = -1
for l2 in pb:
t = l2.strip()
if not t or _is_rule(t):
continue
if t == "CHARGE":
target = charge
continue
if t == "SPIN":
spin = np.zeros((natm, len(SHELLS)))
target = spin
continue
if ":" not in t: # next section banner
pb.push(l2)
break
parts = l2.split(":")
head = parts[0].split()
if head and head[0].isdigit():
atom = int(head[0])
if len(parts) >= 3 and 0 <= atom < natm:
tail = parts[1].split()
if tail and tail[-1] in SHELLS:
v = _f(parts[2].split()[0])
if v is not None:
target[atom, SHELLS.index(tail[-1])] = v
return charge, spin
def _bond_list(pb):
"""'B( 0-Xe, 1-Cl) : 0.1834' three per line, ending at a blank line."""
out = []
for l2 in pb:
t = l2.strip()
if _is_rule(t):
continue
if not t:
if out:
break
continue
found = _BOND.findall(l2)
if not found:
pb.push(l2)
break
for i, _, j, _, v in found:
out.append((int(i), int(j), float(v)))
return out
def _mayer_table(pb):
cols = {k: [] for k in ("NA", "ZA", "QA", "VA", "BVA", "FA")}
for l2 in pb:
p = l2.split()
if len(p) != 8 or not p[0].isdigit():
pb.push(l2)
break
for k, v in zip(("NA", "ZA", "QA", "VA", "BVA", "FA"), p[2:]):
cols[k].append(float(v))
return {k: (np.array(v) if v else None) for k, v in cols.items()}
def _npa_summary(pb, r, natm):
"""RHF rows have 7 fields (El, No, Charge, Core, Valence, Rydberg, Total); UHF rows have an
eighth, the natural spin density."""
if not natm:
return
q = np.full(natm, np.nan)
core = np.full(natm, np.nan)
val = np.full(natm, np.nan)
ryd = np.full(natm, np.nan)
spin = np.full(natm, np.nan)
for l2 in pb:
t = l2.strip()
if not t or _is_rule(t):
continue
p = t.split()
if t.startswith("* Total *"):
if len(p) >= 7:
r["npa_core"], r["npa_valence"], r["npa_rydberg"] = (
float(p[4]), float(p[5]), float(p[6]))
break
if len(p) in (7, 8) and p[1].isdigit() and _f(p[2]) is not None:
i = int(p[1]) - 1
if 0 <= i < natm:
q[i], core[i], val[i], ryd[i] = (float(p[2]), float(p[3]),
float(p[4]), float(p[5]))
if len(p) == 8:
spin[i] = float(p[7])
continue
if not np.isnan(q).all():
pb.push(l2)
break
if not np.isnan(q).all():
r["npa_q"], r["npa_atom_core"] = q, core
r["npa_atom_val"], r["npa_atom_ryd"] = val, ryd
if not np.isnan(spin).all():
r["npa_spin"] = spin
_CONFIG_SHELL = re.compile(r"(\d)([spdfg])\(\s*([\d.]+)\)")
def _natural_config(pb, natm):
"""'Xe 1 [core]5s( 2.00)5p( 4.39)4f( 0.02)5d( 0.15)' -> per-atom occupancy by l."""
if not natm:
return None
out = np.zeros((natm, len(SHELLS)))
seen = False
for l2 in pb:
t = l2.strip()
if not t or _is_rule(t):
continue
p = t.split()
if len(p) >= 3 and p[1].isdigit() and ("[core]" in t or _CONFIG_SHELL.search(t)):
i = int(p[1]) - 1
if 0 <= i < natm:
for _, l, v in _CONFIG_SHELL.findall(t):
out[i, SHELLS.index(l)] += float(v)
seen = True
continue
if seen:
pb.push(l2)
break
return out if seen else None
def _orbital_energies(pb):
"""Returns (eps_a, occ_a, eps_b, occ_b); the beta pair is None for RHF."""
eps_a = occ_a = eps_b = occ_b = None
eps, occ = [], []
spin = 0
for l2 in pb:
t = l2.strip()
if not t or _is_rule(t):
continue
if "SPIN UP" in t:
spin = 0
continue
if "SPIN DOWN" in t:
eps_a, occ_a = np.array(eps), np.array(occ)
eps, occ = [], []
spin = 1
continue
if t.startswith("NO") and "OCC" in t:
continue
p = t.split()
if len(p) == 4:
o, e = _f(p[1]), _f(p[2])
if o is not None and e is not None:
occ.append(o)
eps.append(e)
continue
pb.push(l2)
break
if spin == 0:
eps_a, occ_a = np.array(eps), np.array(occ)
else:
eps_b, occ_b = np.array(eps), np.array(occ)
return eps_a, occ_a, eps_b, occ_b
def _dipole(pb, r):
for l2 in pb:
t = l2.strip()
if t.startswith("Electronic contribution"):
r["dipole_elec"] = [float(x) for x in t.split(":")[1].split()]
elif t.startswith("Nuclear contribution"):
r["dipole_nuc"] = [float(x) for x in t.split(":")[1].split()]
elif t.startswith("Total Dipole Moment"):
r["dipole_total"] = [float(x) for x in t.split(":")[1].split()]
elif t.startswith("Magnitude (a.u.)"):
r["dipole_au"] = _num_after_colon(t)
elif t.startswith("Magnitude (Debye)"):
r["dipole_debye"] = _num_after_colon(t)
return
def _quadrupole(pb, r):
for l2 in pb:
t = l2.strip()
p = t.split()
if t.startswith("NUC") and len(p) >= 7:
r["quad_nuc"] = [float(x) for x in p[1:7]]
elif t.startswith("EL") and len(p) >= 7:
r["quad_elec"] = [float(x) for x in p[1:7]]
elif t.startswith("TOT") and len(p) >= 7:
r["quad_total"] = [float(x) for x in p[1:7]]
elif t.startswith("diagonalized tensor"):
nxt = next(pb).split()
if len(nxt) >= 3:
r["quad_diag"] = [float(x) for x in nxt[:3]]
elif t.startswith("Isotropic quadrupole"):
r["quad_iso"] = _num_after_colon(t)
return
# ----------------------------------------------------------------------------- main parser
def _blank_record():
return {
"version": None, "hftyp": None, "charge": None, "mult": None, "nelec": None,
"nbas": None, "naux": None, "smallest_ovlp_eig": None, "n_lindep": None,
"e_total": None, "e_nuc_rep": None, "e_one_elec": None, "e_two_elec": None,
"e_kinetic": None, "virial_ratio": None, "e_xc": None, "e_nl": None, "e_exchange": None,
"n_alpha_int": None, "n_beta_int": None,
"s2": None, "s2_ideal": None, "s2_dev": None,
"scf_converged": False, "scf_cycles": None,
"conv_denergy": None, "conv_maxdp": None, "conv_rmsdp": None, "conv_diiserr": None,
"dipole_elec": None, "dipole_nuc": None, "dipole_total": None,
"dipole_au": None, "dipole_debye": None,
"quad_nuc": None, "quad_elec": None, "quad_total": None, "quad_diag": None,
"quad_iso": None, "rot_const_cm": None, "rot_const_mhz": None,
"grad_norm": None, "grad_rms": None, "grad_max": None,
"run_time_s": None, "terminated_normally": False,
"nbo_available": False, "npa_available": False,
"npa_core": None, "npa_valence": None, "npa_rydberg": None,
"nbo_lewis": None, "nbo_nonlewis": None,
"elements": [], "coords": None, "ecp_ncore": {},
"mulliken_q": None, "mulliken_s": None, "loewdin_q": None, "loewdin_s": None,
"mayer_NA": None, "mayer_ZA": None, "mayer_QA": None,
"mayer_VA": None, "mayer_BVA": None, "mayer_FA": None,
"npa_q": None, "npa_atom_core": None, "npa_atom_val": None, "npa_atom_ryd": None,
"npa_spin": None, "natural_config": None,
"mulliken_shell_q": None, "loewdin_shell_q": None,
"mulliken_shell_s": None, "loewdin_shell_s": None,
"mayer_bo": [], "loewdin_bo": [], "mulliken_ovlp": [],
"eps_a": None, "occ_a": None, "eps_b": None, "occ_b": None,
"fock_a": None, "fock_b": None,
}
def parse_orca_out(fh):
r = _blank_record()
pb = _PB(fh)
coords = []
for line in pb:
s = line.strip()
# ---------------- header / settings
if r["version"] is None and "Program Version" in line:
r["version"] = line.split("Program Version")[1].split()[0]
elif "Hartree-Fock type" in line:
r["hftyp"] = _after(line, "....")
elif "Total Charge" in line and "...." in line:
r["charge"] = int(float(_after(line, "....")))
elif s.startswith("Multiplicity") and "Mult " in line:
r["mult"] = int(float(_after(line, "....")))
elif "Number of Electrons" in line and "...." in line:
r["nelec"] = int(float(_after(line, "....")))
elif line.startswith("Number of basis functions") and r["nbas"] is None:
r["nbas"] = int(_after(line, "..."))
elif "# of basis functions in Aux-J" in line:
r["naux"] = int(_after(line, "..."))
elif "Smallest eigenvalue" in line and r["smallest_ovlp_eig"] is None:
r["smallest_ovlp_eig"] = _f(_after(line, "..."))
elif "Number of eigenvalues below threshold" in line:
r["n_lindep"] = int(_after(line, "..."))
elif "ECP" in line and "replacing" in line and "core electrons" in line:
m = re.search(r"Type\s+(\S+)\s+ECP.*replacing\s+(\d+)\s+core electrons", line)
if m:
r["ecp_ncore"][m.group(1)] = int(m.group(2))
# ---------------- geometry
elif s == "CARTESIAN COORDINATES (ANGSTROEM)" and not r["elements"]:
next(pb)
for l2 in pb:
p = l2.split()
if len(p) != 4:
pb.push(l2)
break
r["elements"].append(p[0])
coords.append([float(p[1]), float(p[2]), float(p[3])])
# ---------------- energies
elif s.startswith("Total Energy") and ":" in line and r["e_total"] is None:
r["e_total"] = _num_after_colon(line)
elif s.startswith("Nuclear Repulsion") and ":" in line:
r["e_nuc_rep"] = _num_after_colon(line)
elif s.startswith("One Electron Energy"):
r["e_one_elec"] = _num_after_colon(line)
elif s.startswith("Two Electron Energy"):
r["e_two_elec"] = _num_after_colon(line)
elif s.startswith("Kinetic Energy"):
r["e_kinetic"] = _num_after_colon(line)
elif s.startswith("Virial Ratio"):
r["virial_ratio"] = _num_after_colon(line)
elif s.startswith("E(XC)"):
r["e_xc"] = _num_after_colon(line)
elif s.startswith("NL Energy, E(C,NL)"):
r["e_nl"] = _num_after_colon(line)
elif s.startswith("New exchange energy"):
r["e_exchange"] = _num_after_colon(line)
elif s.startswith("N(Alpha)"):
r["n_alpha_int"] = _num_after_colon(line)
elif s.startswith("N(Beta)"):
r["n_beta_int"] = _num_after_colon(line)
elif s.startswith("FINAL SINGLE POINT ENERGY") and r["e_total"] is None:
r["e_total"] = _f(s.split()[-1])
# ---------------- SCF convergence
elif "SCF CONVERGED AFTER" in line:
r["scf_converged"] = True
m = re.search(r"AFTER\s+(\d+)\s+CYCLES", line)
if m:
r["scf_cycles"] = int(m.group(1))
elif s.startswith("Last Energy change"):
r["conv_denergy"] = _f(_after(line, "...").split()[0])
elif s.startswith("Last MAX-Density change"):
r["conv_maxdp"] = _f(_after(line, "...").split()[0])
elif s.startswith("Last RMS-Density change"):
r["conv_rmsdp"] = _f(_after(line, "...").split()[0])
elif s.startswith("Last DIIS Error"):
r["conv_diiserr"] = _f(_after(line, "...").split()[0])
elif s.startswith("Expectation value of <S**2>"):
r["s2"] = _num_after_colon(line)
elif s.startswith("Ideal value S*(S+1)"):
r["s2_ideal"] = _num_after_colon(line)
elif s.startswith("Deviation") and r["s2"] is not None and r["s2_dev"] is None:
r["s2_dev"] = _num_after_colon(line)
# ---------------- orbitals and Fock
elif s == "ORBITAL ENERGIES":
ea, oa, eb, ob = _orbital_energies(pb)
r["eps_a"], r["occ_a"] = ea, oa
if eb is not None:
r["eps_b"], r["occ_b"] = eb, ob
elif s == "FOCK" and r["nbas"]:
hdr = _next_matrix_header(pb, max_skip=6)
if hdr is not None:
F = _read_matrix(pb, r["nbas"], hdr)
r["fock_a"] = _tri_u_eh(F)
del F
hdr_b = _next_matrix_header(pb, max_skip=6)
if hdr_b is not None:
Fb = _read_matrix(pb, r["nbas"], hdr_b)
r["fock_b"] = _tri_u_eh(Fb)
del Fb
# ---------------- population analyses
elif s.startswith("MULLIKEN ATOMIC CHARGES"):
r["mulliken_q"], r["mulliken_s"] = _atom_charges(pb)
elif s.startswith("LOEWDIN ATOMIC CHARGES"):
r["loewdin_q"], r["loewdin_s"] = _atom_charges(pb)
elif s.startswith("MULLIKEN REDUCED ORBITAL CHARGES"):
r["mulliken_shell_q"], r["mulliken_shell_s"] = _reduced_shells(pb, len(r["elements"]))
elif s.startswith("LOEWDIN REDUCED ORBITAL CHARGES"):
r["loewdin_shell_q"], r["loewdin_shell_s"] = _reduced_shells(pb, len(r["elements"]))
elif s.startswith("MULLIKEN OVERLAP CHARGES"):
r["mulliken_ovlp"] = _bond_list(pb)
elif s.startswith("LOEWDIN BOND ORDERS"):
r["loewdin_bo"] = _bond_list(pb)
elif s.startswith("ATOM") and "BVA" in s and "ZA" in s:
for k, v in _mayer_table(pb).items():
r[f"mayer_{k}"] = v
elif s.startswith("Mayer bond orders larger than"):
r["mayer_bo"] = _bond_list(pb)
# ---------------- NBO / NPA
elif "Now starting NBO" in line:
r["nbo_available"] = True
elif s.startswith("Summary of Natural Population Analysis") and r["npa_q"] is None:
r["npa_available"] = True
_npa_summary(pb, r, len(r["elements"]))
elif s.startswith("Atom No") and "Natural Electron Configuration" in s and r["natural_config"] is None:
r["natural_config"] = _natural_config(pb, len(r["elements"]))
elif s.startswith("Total Lewis") and r["nbo_lewis"] is None:
p = s.split()
if len(p) > 2:
r["nbo_lewis"] = _f(p[2])
elif s.startswith("Total non-Lewis") and r["nbo_nonlewis"] is None:
p = s.split()
if len(p) > 2:
r["nbo_nonlewis"] = _f(p[2])
# ---------------- properties
elif s == "DIPOLE MOMENT" and r["dipole_total"] is None:
_dipole(pb, r)
elif s == "QUADRUPOLE MOMENT" and r["quad_total"] is None:
_quadrupole(pb, r)
elif s.startswith("Rotational constants in cm-1"):
r["rot_const_cm"] = [float(x) for x in s.split(":")[1].split()]
elif s.startswith("Rotational constants in MHz"):
r["rot_const_mhz"] = [float(x) for x in s.split(":")[1].split()]
elif s.startswith("Norm of the Cartesian gradient"):
r["grad_norm"] = _f(_after(line, "..."))
elif s.startswith("RMS gradient"):
r["grad_rms"] = _f(_after(line, "..."))
elif s.startswith("MAX gradient"):
r["grad_max"] = _f(_after(line, "..."))
elif "ORCA TERMINATED NORMALLY" in line:
r["terminated_normally"] = True
elif s.startswith("TOTAL RUN TIME"):
m = re.search(r"(\d+) days (\d+) hours (\d+) minutes (\d+) seconds (\d+) msec", s)
if m:
d, h, mi, sec, ms = (int(x) for x in m.groups())
r["run_time_s"] = d * 86400 + h * 3600 + mi * 60 + sec + ms / 1000
r["coords"] = np.array(coords, dtype=np.float64) if coords else None
return r
# ----------------------------------------------------------------------------- engrad
def parse_engrad(fh):
"""Returns (n_atoms, energy, gradient (n,3) Eh/bohr, Z (n,), coords_bohr (n,3))."""
lines = [l for l in fh if not l.lstrip().startswith("#") and l.strip()]
it = iter(lines)
n = int(next(it).split()[0])
energy = float(next(it).split()[0])
vals = [float(next(it).split()[0]) for _ in range(3 * n)]
zs, xyz = [], []
for _ in range(n):
p = next(it).split()
zs.append(int(p[0]))
xyz.append([float(x) for x in p[1:4]])
return n, energy, np.array(vals).reshape(n, 3), np.array(zs), np.array(xyz)
def iter_lines(fb, encoding="utf-8", chunk=1 << 20):
"""Yield decoded lines from a binary stream. tarfile's stream mode ('r|') hands back objects
that TextIOWrapper rejects (no seekable()), so decoding is done here."""
buf = b""
while True:
data = fb.read(chunk)
if not data:
break
buf += data
parts = buf.split(b"\n")
buf = parts.pop()
for part in parts:
yield part.decode(encoding, "replace")
if buf:
yield buf.decode(encoding, "replace")
# ----------------------------------------------------------------------------- archive entry
def parse_archive(tar_path):
"""Stream an orca.tar.zst and parse the members we need. Never writes to disk."""
proc = subprocess.Popen(["zstd", "-dc", tar_path], stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL)
rec, grad = None, None
try:
with tarfile.open(fileobj=proc.stdout, mode="r|") as tf:
for member in tf:
name = os.path.basename(member.name)
if name == "orca.out":
rec = parse_orca_out(iter_lines(tf.extractfile(member)))
elif name == "orca.engrad":
grad = parse_engrad(iter_lines(tf.extractfile(member)))
finally:
if proc.stdout:
proc.stdout.close()
proc.wait()
if rec is None:
raise ValueError(f"no orca.out in {tar_path}")
if grad is not None:
n, e_grad, g, z, xyz_bohr = grad
rec["forces"] = -g
rec["atomic_numbers"] = z
rec["coords_bohr"] = xyz_bohr
rec["e_total_engrad"] = e_grad
else:
rec["forces"] = rec["atomic_numbers"] = None
rec["coords_bohr"] = rec["e_total_engrad"] = None
return rec
|