ericqu commited on
Commit
39ea985
·
verified ·
1 Parent(s): e02f5c7

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. fullC/b1_failures.tsv +2 -0
  2. fullC/b1_summary.json +25 -0
  3. fullC/basis_def2-TZVPD_orca6.json +0 -0
  4. fullC/code/build_index.py +54 -0
  5. fullC/code/check_overlap.py +103 -0
  6. fullC/code/copy_100k_share.sh +15 -0
  7. fullC/code/derive_occ_store.py +151 -0
  8. fullC/code/export_basis.py +193 -0
  9. fullC/code/gbw_reader.py +69 -0
  10. fullC/code/hf_upload.py +31 -0
  11. fullC/code/make_subset.py +87 -0
  12. fullC/code/merge_store.py +265 -0
  13. fullC/code/omol_parse.py +612 -0
  14. fullC/code/omol_store.py +374 -0
  15. fullC/code/pass_a.py +150 -0
  16. fullC/code/pass_b1.py +361 -0
  17. fullC/code/pyproject.toml +18 -0
  18. fullC/code/repack_store.py +130 -0
  19. fullC/code/uv.lock +0 -0
  20. fullC/code/verify_store.py +196 -0
  21. fullC/failures_task3.tsv +2 -0
  22. fullC/p2/ml_elytes/group_000.zarr/atom_shell/zarr.json +68 -0
  23. fullC/p2/ml_elytes/group_000.zarr/atom_z/zarr.json +65 -0
  24. fullC/p2/ml_elytes/group_000.zarr/cmo_a_offsets/zarr.json +65 -0
  25. fullC/p2/ml_elytes/group_000.zarr/cmo_b/zarr.json +55 -0
  26. fullC/p2/ml_elytes/group_000.zarr/eps_b_offsets/zarr.json +65 -0
  27. fullC/p2/ml_elytes/group_000.zarr/fock_a_offsets/zarr.json +65 -0
  28. fullC/p2/ml_elytes/group_000.zarr/gbw_eps_a/zarr.json +65 -0
  29. fullC/p2/ml_elytes/group_000.zarr/gbw_eps_b/zarr.json +65 -0
  30. fullC/p2/ml_elytes/group_000.zarr/gbw_occ_a/zarr.json +65 -0
  31. fullC/p2/ml_elytes/group_000.zarr/gbw_occ_b/zarr.json +65 -0
  32. fullC/p2/ml_elytes/group_000.zarr/mo_f8/zarr.json +68 -0
  33. fullC/p2/ml_elytes/group_000.zarr/occ_a/zarr.json +65 -0
  34. fullC/p2/ml_elytes/group_000.zarr/pair_loewdin_bo_value/zarr.json +65 -0
  35. fullC/p2/ml_elytes/group_000.zarr/pair_mayer_bo_value/zarr.json +65 -0
  36. fullC/p2/ml_elytes/group_000.zarr/pair_mulliken_ovlp_index/zarr.json +68 -0
  37. fullC/p2/ml_elytes/group_000.zarr/scalar_f8/zarr.json +68 -0
  38. fullC/p2/ml_elytes/group_000.zarr/zarr.json +0 -0
  39. fullC/p2/ml_elytes/group_001.zarr/zarr.json +0 -0
  40. fullC/p2/ml_elytes/group_002.zarr/zarr.json +0 -0
  41. fullC/subset_100k.txt +0 -0
  42. fullC/subset_100k_counts.tsv +45 -0
  43. fullC/subset_100k_missing.txt +0 -0
  44. occC/b1_failures.tsv +2 -0
  45. occC/b1_summary.json +25 -0
  46. occC/basis_def2-TZVPD_orca6.json +0 -0
  47. occC/failures_task3.tsv +2 -0
  48. occC/subset_100k.txt +0 -0
  49. occC/subset_100k_counts.tsv +45 -0
  50. occC/subset_100k_missing.txt +0 -0
fullC/b1_failures.tsv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ shard calc_id reason
2
+ p2/ani1xbb/shard_t03_0005_00.zarr ani1xbb__aniBB_022_377503_0_3 failed: fock_match
fullC/b1_summary.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "totals": {
3
+ "n": 99999,
4
+ "found": 99999,
5
+ "ok": 99998,
6
+ "fock_checked": 99954,
7
+ "bytes_cmo": 1521762062968,
8
+ "fail_gbw_found": 0,
9
+ "fail_nbas_match": 0,
10
+ "fail_nspin_match": 0,
11
+ "fail_nelec_match": 0,
12
+ "fail_spin_match": 0,
13
+ "fail_eps_checked": 0,
14
+ "fail_eps_match": 0,
15
+ "fail_occ_contiguous": 0,
16
+ "fail_fock_checked": 45,
17
+ "fail_fock_match": 1,
18
+ "fail_mo_ok": 1
19
+ },
20
+ "dtype": "f4",
21
+ "eps_err_max": 4.999999996257998e-07,
22
+ "fc_offdiag_max": 0.002244156607543126,
23
+ "wall_s": 1131.7759289741516,
24
+ "shard_failures": []
25
+ }
fullC/basis_def2-TZVPD_orca6.json ADDED
The diff for this file is too large to render. See raw diff
 
fullC/code/build_index.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write a flat per-calculation index for a store: one row per calculation with its shard, row
2
+ number and the handful of columns most queries filter on. Lets a consumer find a calculation
3
+ without opening every shard.
4
+
5
+ python build_index.py --store $PSCRATCH/omol_100k
6
+ writes <store>/index.tsv
7
+ """
8
+ from __future__ import annotations
9
+ import argparse, glob, os
10
+ import numpy as np
11
+ import zarr
12
+
13
+
14
+ def p2_shards(store):
15
+ out = []
16
+ for depth in ("*", "*/*/*"):
17
+ out += glob.glob(os.path.join(store, "p2", depth, "*.zarr"))
18
+ return sorted(set(out))
19
+
20
+
21
+ def main():
22
+ ap = argparse.ArgumentParser()
23
+ ap.add_argument("--store", required=True)
24
+ args = ap.parse_args()
25
+ shards = p2_shards(args.store)
26
+ out = os.path.join(args.store, "index.tsv")
27
+ n = 0
28
+ cols = ["calc_id", "dataset", "shard", "row", "n_atoms", "nbas", "nelec", "charge", "mult",
29
+ "is_uhf", "has_fock", "scf_converged", "mo_ok", "e_total", "conv_diiserr", "rel_path"]
30
+ with open(out, "w") as fh:
31
+ fh.write("\t".join(cols) + "\n")
32
+ for sp in shards:
33
+ g = zarr.open_group(sp, mode="r")
34
+ rel = os.path.relpath(sp, os.path.join(args.store, "p2"))
35
+ ids, rels, ds = g.attrs["calc_id"], g.attrs["rel_path"], g.attrs["dataset"]
36
+ si = np.asarray(g["scalar_i"]); ic = {k: j for j, k in enumerate(g.attrs["scalar_i_cols"])}
37
+ sf = np.asarray(g["scalar_f8"]); fc_ = {k: j for j, k in enumerate(g.attrs["scalar_f8_cols"])}
38
+ fl = np.asarray(g["flags"]); fc = {k: j for j, k in enumerate(g.attrs["flag_cols"])}
39
+ if g.attrs.get("has_mo"):
40
+ cf = np.asarray(g["mo_flags"])[:, g.attrs["mo_flag_cols"].index("mo_ok")]
41
+ else:
42
+ cf = np.full(len(ids), -1)
43
+ for i in range(len(ids)):
44
+ fh.write("\t".join(map(str, [
45
+ ids[i], ds, rel, i, si[i, ic["n_atoms"]], si[i, ic["nbas"]], si[i, ic["nelec"]],
46
+ si[i, ic["charge"]], si[i, ic["mult"]], int(fl[i, fc["is_uhf"]]),
47
+ int(fl[i, fc["has_fock"]]), int(fl[i, fc["scf_converged"]]), int(cf[i]),
48
+ f"{sf[i, fc_['e_total']]:.10f}", f"{sf[i, fc_['conv_diiserr']]:.3e}", rels[i]])) + "\n")
49
+ n += 1
50
+ print(f"wrote {out}: {n:,} rows from {len(shards)} shards")
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
fullC/code/check_overlap.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify ORCA's printed AO Fock matrix + pyscf overlap reproduces ORCA orbital energies.
2
+
3
+ Established convention (ORCA 6.0, def2-TZVPD):
4
+ * AO order per atom = def2-TZVP shells grouped by l (s,p,d,f,g; basis order within l),
5
+ then the def2-TZVPD augmentation (diffuse) shells appended in l order.
6
+ * m order: p = (z, x, y); d = (z2, xz, yz, x2-y2, xy); f = (0,+1,-1,+2,-2,+3,-3); g = (0,+1,-1,...,+4,-4)
7
+ * relative to pyscf real solid harmonics, f(+3) and f(-3) have opposite sign (g signs searched if present).
8
+ """
9
+ import re, sys, time, itertools
10
+ import numpy as np
11
+ from scipy.linalg import eigh
12
+ from pyscf import gto
13
+
14
+ def parse(path):
15
+ lines = open(path, errors="replace").read().split("\n")
16
+ i = lines.index("CARTESIAN COORDINATES (ANGSTROEM)")
17
+ atoms = []
18
+ for l in lines[i+2:]:
19
+ p = l.split()
20
+ if len(p) != 4: break
21
+ atoms.append((p[0], (float(p[1]), float(p[2]), float(p[3]))))
22
+ charge = int([l for l in lines if "Total Charge" in l][0].split("....")[1])
23
+ mult = int([l for l in lines if l.strip().startswith("Multiplicity") and "Mult " in l][0].split("....")[1])
24
+ hftyp = [l for l in lines if "Hartree-Fock type" in l][0].split("....")[1].strip()
25
+ nbas = int([l for l in lines if l.startswith("Number of basis functions")][0].split("...")[1])
26
+ k = lines.index("ORBITAL ENERGIES")
27
+ start = k + 4
28
+ eps = []
29
+ for l in lines[start:]:
30
+ p = l.split()
31
+ if len(p) != 4: break
32
+ eps.append(float(p[2]))
33
+ fi = lines.index("FOCK"); i = fi + 2
34
+ F = np.zeros((nbas, nbas)); done = 0
35
+ while done < nbas:
36
+ ncol = len(lines[i].split())
37
+ F[:, done:done+ncol] = np.fromstring("\n".join(lines[i+1:i+1+nbas]), sep=" ").reshape(nbas, ncol+1)[:, 1:]
38
+ done += ncol; i += 1 + nbas
39
+ return atoms, charge, mult, hftyp, nbas, np.array(eps), F
40
+
41
+ ORCA_M = {l: [0] + [m for k in range(1, l+1) for m in (k, -k)] for l in range(6)}
42
+ FLIP = {(3, 3), (3, -3)} # sign flips relative to pyscf
43
+
44
+ def orca_perm_and_sign(mol, extra_flips=()):
45
+ tzvp = {}
46
+ for ia in range(mol.natm):
47
+ el = mol.atom_symbol(ia)
48
+ if el not in tzvp:
49
+ tzvp[el] = {(sh[0], tuple(round(p[0], 6) for p in sh[1:])) for sh in gto.basis.load("def2-tzvp", el)}
50
+ perm = []; sgn = []; labels = []
51
+ ao = 0; table = {}
52
+ for ish in range(mol.nbas):
53
+ ia = mol.bas_atom(ish); l = mol.bas_angular(ish)
54
+ for c in range(mol.bas_nctr(ish)):
55
+ for m in ([1, -1, 0] if l == 1 else list(range(-l, l+1))):
56
+ table[(ish, c, m)] = ao; ao += 1
57
+ for ia in range(mol.natm):
58
+ el = mol.atom_symbol(ia)
59
+ shells = []
60
+ for ish in [i for i in range(mol.nbas) if mol.bas_atom(i) == ia]:
61
+ l = mol.bas_angular(ish); ex = tuple(round(float(e), 6) for e in mol.bas_exp(ish))
62
+ for c in range(mol.bas_nctr(ish)):
63
+ shells.append((l, ish, c, (l, ex) not in tzvp[el]))
64
+ shells = sorted([s for s in shells if not s[3]], key=lambda s: (s[0], s[1], s[2])) + \
65
+ sorted([s for s in shells if s[3]], key=lambda s: (s[0], s[1], s[2]))
66
+ for l, ish, c, aug in shells:
67
+ for m in ORCA_M[l]:
68
+ perm.append(table[(ish, c, m)])
69
+ sgn.append(-1.0 if ((l, m) in FLIP) ^ ((l, m) in extra_flips) else 1.0)
70
+ labels.append((ia, el, l, m, aug))
71
+ return np.array(perm), np.array(sgn), labels
72
+
73
+ def orca_overlap(mol, extra_flips=()):
74
+ perm, sgn, labels = orca_perm_and_sign(mol, extra_flips)
75
+ S = mol.intor("int1e_ovlp")[np.ix_(perm, perm)] * np.outer(sgn, sgn)
76
+ return S, labels
77
+
78
+ if __name__ == "__main__":
79
+ for path in sys.argv[1:]:
80
+ t0 = time.time(); name = path.split("/samples/")[1].split("/")[0]
81
+ try:
82
+ atoms, charge, mult, hftyp, nbas, eps, F = parse(path)
83
+ mol = gto.M(atom=atoms, basis="def2-tzvpd", ecp="def2-tzvpd", unit="Angstrom", charge=charge, spin=mult-1, verbose=0)
84
+ except Exception as e:
85
+ print(f"{name:24s} SKIP: {type(e).__name__}: {str(e)[:120]}"); continue
86
+ if mol.nao != nbas:
87
+ print(f"{name:24s} SKIP: pyscf nao {mol.nao} != ORCA nbas {nbas}"); continue
88
+ nmo = int((eps != 0).sum()); nocc = (mol.nelectron + (mult-1)) // 2
89
+ S, labels = orca_overlap(mol)
90
+ w = eigh(F, S, eigvals_only=True); d = np.abs(w[:nmo] - eps[:nmo])
91
+ note = ""
92
+ has_g = any(l == 4 for _, _, l, _, _ in labels)
93
+ if d[:nocc].max() > 1e-4 and has_g:
94
+ gl = [(4, m) for m in ORCA_M[4] if m != 0]
95
+ for flips in itertools.product([0, 1], repeat=len(gl)):
96
+ ef = tuple(x for x, f in zip(gl, flips) if f)
97
+ S2, _ = orca_overlap(mol, ef)
98
+ w2 = eigh(F, S2, eigvals_only=True); d2 = np.abs(w2[:nmo] - eps[:nmo])
99
+ if d2[:nocc].max() < d[:nocc].max():
100
+ d = d2; note = f" g-flips={ef}"
101
+ if d[:nocc].max() < 1e-4: break
102
+ sS = np.linalg.eigvalsh(S)
103
+ print(f"{name:24s} {hftyp} nbas={nbas} nmo={nmo} Smin={sS.min():.1e} | occ max|de|={d[:nocc].max():.1e} all max={d.max():.1e} mean={d.mean():.1e}{note} | {time.time()-t0:.0f}s", flush=True)
fullC/code/copy_100k_share.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH --account=m5293
3
+ #SBATCH --qos=xfer
4
+ #SBATCH --time=12:00:00
5
+ #SBATCH --job-name=omol_copy_100k_share
6
+ #SBATCH --output=/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/logs/copy_100k_share_%j.log
7
+ # Copy the finished, verified 100k share (repacked Pass A + Pass B1 C_occ) from scratch to CFS.
8
+ set -euo pipefail
9
+ SRC="$PSCRATCH/omol_100k"
10
+ DST="/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/omol_elec_100k"
11
+ mkdir -p "$DST"
12
+ echo "copying $SRC -> $DST $(date)"
13
+ rsync -a --no-inc-recursive "$SRC/" "$DST/"
14
+ echo "rsync finished $(date)"
15
+ echo "files: $(find "$DST" -type f | wc -l) bytes: $(du -sb "$DST" | cut -f1)"
fullC/code/derive_occ_store.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Derive the occupied-only variant of a full-C store.
2
+
3
+ For every p2 shard the group directory is copied file for file (no decode or re-encode of the
4
+ Fock and table arrays), except the `cmo_*` arrays, which are rewritten with only the occupied
5
+ rows of each calculation's C^T block. Both variants share one schema: `mo_content` in the group
6
+ attributes is "full" or "occupied", and `cmo_x[o[i]:o[i+1]].reshape(-1, nbas)` is C^T restricted to
7
+ the stored orbitals either way. p1 and the root files are copied as they are.
8
+
9
+ python derive_occ_store.py --src $PSCRATCH/omol_100k --dst $PSCRATCH/omol_100k_occ --workers 64
10
+ """
11
+ from __future__ import annotations
12
+ import argparse, glob, os, shutil, sys, time, traceback
13
+ import multiprocessing as mp
14
+ import numpy as np
15
+ import zarr
16
+
17
+ zarr.config.set({"threading.max_workers": 1, "async.concurrency": 2})
18
+ try:
19
+ import numcodecs.blosc
20
+ numcodecs.blosc.set_nthreads(1)
21
+ numcodecs.blosc.use_threads = False
22
+ except Exception:
23
+ pass
24
+
25
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
26
+ from omol_store import put_array
27
+
28
+ CMO_CHUNK = 1 << 22
29
+
30
+
31
+ def p2_shards(store):
32
+ out = []
33
+ for depth in ("*", "*/*/*"):
34
+ out += glob.glob(os.path.join(store, "p2", depth, "*.zarr"))
35
+ return sorted(set(out))
36
+
37
+
38
+ def derive(args):
39
+ src, dst = args
40
+ t0 = time.time()
41
+ try:
42
+ if os.path.isdir(dst):
43
+ if zarr.open_group(dst, mode="r").attrs.get("occ_derived_verified"):
44
+ return dst, "skip", 0, 0.0, ""
45
+ shutil.rmtree(dst)
46
+ gs = zarr.open_group(src, mode="r")
47
+ if gs.attrs.get("mo_content", "full") != "full":
48
+ raise RuntimeError("source is not a full-C store")
49
+ skip = {n for n in gs.array_keys() if n.startswith("cmo_")}
50
+ shutil.copytree(src, dst, ignore=lambda d, names: [n for n in names if d == src and n in skip])
51
+ # the copied root zarr.json may carry consolidated metadata that still lists the excluded
52
+ # arrays; drop it and re-consolidate once the new arrays are in place
53
+ import json
54
+ meta_path = os.path.join(dst, "zarr.json")
55
+ meta = json.load(open(meta_path))
56
+ if "consolidated_metadata" in meta:
57
+ meta["consolidated_metadata"] = None
58
+ json.dump(meta, open(meta_path, "w"))
59
+ gd = zarr.open_group(dst, mode="r+", use_consolidated=False)
60
+ n = int(gs.attrs["n_calc"])
61
+ nbas = np.asarray(gs["scalar_i"])[:, list(gs.attrs["scalar_i_cols"]).index("nbas")].astype("i8")
62
+ mi = np.asarray(gs["mo_i"])
63
+ nocc = {s: mi[:, list(gs.attrs["mo_i_cols"]).index(f"nocc_{s}")].astype("i8") for s in "ab"}
64
+ written = 0
65
+ for s in "ab":
66
+ zsrc = gs[f"cmo_{s}"]
67
+ off_src = np.asarray(gs[f"cmo_{s}_offsets"])
68
+ lens = np.where(np.diff(off_src) > 0, nocc[s] * nbas, 0)
69
+ offs = np.zeros(n + 1, dtype="i8")
70
+ offs[1:] = np.cumsum(lens)
71
+ buf = np.empty(int(offs[-1]), dtype=zsrc.dtype)
72
+ for i in range(n):
73
+ if lens[i]:
74
+ a = int(off_src[i])
75
+ buf[offs[i]:offs[i + 1]] = zsrc[a:a + int(lens[i])]
76
+ put_array(gd, f"cmo_{s}", buf, codec=None,
77
+ chunks=(max(1, min(len(buf), CMO_CHUNK)),), overwrite=True)
78
+ put_array(gd, f"cmo_{s}_offsets", offs, overwrite=True)
79
+ # verify: every stored block equals the source prefix
80
+ back = np.asarray(gd[f"cmo_{s}"][...])
81
+ if not np.array_equal(back, buf):
82
+ raise RuntimeError(f"read-back mismatch cmo_{s}")
83
+ written += buf.nbytes
84
+ # verify the copied arrays too (cheap ones fully, Fock by a spot check of the first calc)
85
+ for name in gs.array_keys():
86
+ if name in skip:
87
+ continue
88
+ if name.startswith("fock_") and not name.endswith("_offsets"):
89
+ k = min(int(gs[name].shape[0]), 200_000)
90
+ if not np.array_equal(np.asarray(gs[name][:k]), np.asarray(gd[name][:k])):
91
+ raise RuntimeError(f"copy mismatch {name}")
92
+ else:
93
+ a, b = np.asarray(gs[name][...]), np.asarray(gd[name][...])
94
+ ok = np.array_equal(a, b, equal_nan=True) if a.dtype.kind == "f" else np.array_equal(a, b)
95
+ if not ok:
96
+ raise RuntimeError(f"copy mismatch {name}")
97
+ gd.attrs.update({
98
+ "mo_content": "occupied",
99
+ "mo_layout": "cmo_x[o[i]:o[i+1]].reshape(nocc_x, nbas) = C_occ^T (row k = occupied MO k "
100
+ "over AOs, ORCA AO order); derived from the full-C store",
101
+ "occ_derived_verified": True,
102
+ })
103
+ if gs.metadata.consolidated_metadata is not None:
104
+ zarr.consolidate_metadata(gd.store)
105
+ return dst, "ok", written, time.time() - t0, ""
106
+ except Exception:
107
+ return dst, "fail", 0, time.time() - t0, traceback.format_exc(limit=4)
108
+
109
+
110
+ def main():
111
+ ap = argparse.ArgumentParser()
112
+ ap.add_argument("--src", required=True)
113
+ ap.add_argument("--dst", required=True)
114
+ ap.add_argument("--workers", type=int, default=64)
115
+ args = ap.parse_args()
116
+ src, dst = os.path.abspath(args.src), os.path.abspath(args.dst)
117
+ os.makedirs(dst, exist_ok=True)
118
+ # p1 and root files verbatim
119
+ if not os.path.isdir(os.path.join(dst, "p1")):
120
+ shutil.copytree(os.path.join(src, "p1"), os.path.join(dst, "p1"))
121
+ for name in os.listdir(src):
122
+ p = os.path.join(src, name)
123
+ if os.path.isfile(p):
124
+ shutil.copy2(p, dst)
125
+ elif name == "code":
126
+ shutil.copytree(p, os.path.join(dst, "code"), dirs_exist_ok=True)
127
+ shards = p2_shards(src)
128
+ jobs = [(s, os.path.join(dst, os.path.relpath(s, src))) for s in shards]
129
+ print(f"derive occupied-only store: {len(jobs)} p2 shards {src} -> {dst}", flush=True)
130
+ t0 = time.time()
131
+ n_ok = n_skip = n_fail = 0
132
+ written = 0
133
+ with mp.Pool(min(args.workers, len(jobs))) as pool:
134
+ for k, (path, status, w, dt, err) in enumerate(pool.imap_unordered(derive, jobs), 1):
135
+ if status == "ok":
136
+ n_ok += 1; written += w
137
+ elif status == "skip":
138
+ n_skip += 1
139
+ else:
140
+ n_fail += 1
141
+ print(f"FAIL {path}\n{err}", flush=True)
142
+ if k % 100 == 0 or k == len(jobs):
143
+ print(f" {k}/{len(jobs)} ok={n_ok} skip={n_skip} fail={n_fail} "
144
+ f"cocc {written/1e9:.1f} GB {(time.time()-t0)/60:.1f} min", flush=True)
145
+ print(f"\ndone: ok {n_ok}, skipped {n_skip}, failed {n_fail}, occupied C {written/1e9:.1f} GB, "
146
+ f"wall {(time.time()-t0)/60:.1f} min")
147
+
148
+
149
+ if __name__ == "__main__":
150
+ mp.set_start_method("fork", force=True)
151
+ main()
fullC/code/export_basis.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-element basis set, ECP and effective nuclear charge, exported from the gbw with orca_2json.
2
+
3
+ Why from the gbw and not a library: the orbital basis is def2-TZVPD as ORCA 6 stores it, and
4
+ neither pyscf nor Basis Set Exchange carry the lanthanide entries. The export is exact for every
5
+ element and it is what makes S and H reconstructible from geometry alone.
6
+
7
+ Shell order: orca_2json lists an atom's shells in the order ORCA uses for its AO basis (verified on
8
+ XeCl4 against the exported orbital labels: def2-TZVP shells grouped by l, then the TZVPD
9
+ augmentation shells), so the per-element shell list here IS the AO layout of that element in
10
+ every matrix of the store. Spherical functions; m order p=(z,x,y), d=(z2,xz,yz,x2-y2,xy),
11
+ f=(0,+1,-1,+2,-2,+3,-3).
12
+
13
+ ECP-leak bug in orca_2json 6.0.0: an atom's ECP block is repeated onto the following atoms, so a
14
+ block is trusted only if ElementNumber - NuclearCharge > 0 and the block's N_core equals that
15
+ difference, and each ECP element is taken preferably from a molecule where it is the first
16
+ ECP-bearing atom. Blocks are cross-checked between two source molecules whenever possible.
17
+
18
+ python export_basis.py --store $PSCRATCH/omol_100k --gbw-root $PSCRATCH/gbw_100k \
19
+ --out $PSCRATCH/omol_100k/basis_def2-TZVPD_orca6.json
20
+ """
21
+ from __future__ import annotations
22
+ import argparse, glob, json, os, shutil, struct, subprocess, sys, tempfile
23
+ import numpy as np
24
+ import zarr
25
+ import zstandard as zstd
26
+
27
+ ORCA = "/global/common/software/m5293/orca_6_0_0"
28
+ SYMBOLS = ("X H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn "
29
+ "Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr "
30
+ "Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn").split()
31
+ ECP_Z_MIN = 37 # def2 ECPs start at Rb
32
+
33
+
34
+ def p1_shards(store):
35
+ out = []
36
+ for depth in ("*", "*/*/*"):
37
+ out += glob.glob(os.path.join(store, "p1", depth, "*.zarr"))
38
+ return sorted(set(out))
39
+
40
+
41
+ def candidates(store, gbw_root, per_element=3):
42
+ """For each element, the smallest calculations containing it whose gbw is staged.
43
+ For ECP elements prefer calculations where the element is the first ECP-bearing atom."""
44
+ best = {} # Z -> list of (rank, nbas, dataset, calc_id)
45
+ for sp in p1_shards(store):
46
+ g = zarr.open_group(sp, mode="r")
47
+ ds = g.attrs["dataset"]
48
+ ids = g.attrs["calc_id"]
49
+ nbas = np.asarray(g["scalar_i"])[:, list(g.attrs["scalar_i_cols"]).index("nbas")]
50
+ off = np.asarray(g["atom_offsets"])
51
+ az = np.asarray(g["atom_z"])
52
+ for i in range(len(ids)):
53
+ zs = az[off[i]:off[i + 1]]
54
+ heavy = zs >= ECP_Z_MIN
55
+ first_heavy = int(zs[heavy][0]) if heavy.any() else None
56
+ for Z in np.unique(zs):
57
+ Z = int(Z)
58
+ rank = 0 if (Z < ECP_Z_MIN or first_heavy == Z) else 1
59
+ best.setdefault(Z, []).append((rank, int(nbas[i]), ds, ids[i]))
60
+ out = {}
61
+ for Z, lst in best.items():
62
+ lst.sort()
63
+ picked = []
64
+ for rank, nb, ds, cid in lst:
65
+ path = os.path.join(gbw_root, ds, cid + ".gbw.zstd0")
66
+ if os.path.exists(path):
67
+ picked.append((ds, cid, nb, rank, path))
68
+ if len(picked) >= per_element:
69
+ break
70
+ out[Z] = picked
71
+ return out
72
+
73
+
74
+ def gbw_base_path(raw):
75
+ return raw[40:40 + 512].split(b"\x00", 1)[0].decode()
76
+
77
+
78
+ def run_orca_2json(gbw_zstd, workdir):
79
+ raw = zstd.ZstdDecompressor().decompressobj().decompress(open(gbw_zstd, "rb").read())
80
+ base = gbw_base_path(raw)
81
+ if base:
82
+ os.makedirs(os.path.dirname(base) or ".", exist_ok=True)
83
+ name = os.path.join(workdir, "x")
84
+ with open(name + ".gbw", "wb") as fh:
85
+ fh.write(raw)
86
+ with open(name + ".json.conf", "w") as fh:
87
+ json.dump({"Basisset": True}, fh)
88
+ env = dict(os.environ, LD_LIBRARY_PATH=ORCA + ":" + os.environ.get("LD_LIBRARY_PATH", ""))
89
+ r = subprocess.run([os.path.join(ORCA, "orca_2json"), name + ".gbw", "-json"],
90
+ capture_output=True, text=True, env=env, cwd=workdir, timeout=600)
91
+ if not os.path.exists(name + ".json"):
92
+ raise RuntimeError(f"orca_2json failed: {r.stdout[-500:]} {r.stderr[-500:]}")
93
+ d = json.load(open(name + ".json"))
94
+ for f in glob.glob(name + "*"):
95
+ os.remove(f)
96
+ return d["Molecule"]["Atoms"]
97
+
98
+
99
+ def shell_key(basis):
100
+ return json.dumps(basis, sort_keys=True)
101
+
102
+
103
+ def main():
104
+ ap = argparse.ArgumentParser()
105
+ ap.add_argument("--store", required=True)
106
+ ap.add_argument("--gbw-root", required=True)
107
+ ap.add_argument("--out", required=True)
108
+ ap.add_argument("--per-element", type=int, default=2)
109
+ args = ap.parse_args()
110
+
111
+ cands = candidates(args.store, args.gbw_root, args.per_element)
112
+ print(f"{len(cands)} elements present; "
113
+ f"{sum(1 for v in cands.values() if not v)} without a staged gbw", flush=True)
114
+ workdir = tempfile.mkdtemp(prefix="orca2json_", dir=os.environ.get("PSCRATCH", "/tmp"))
115
+ cache = {}
116
+ elements = {}
117
+ problems = []
118
+ for Z in sorted(cands):
119
+ seen_basis, seen_ecp, zeff_seen, sources = [], [], set(), []
120
+ for ds, cid, nb, rank, path in cands[Z]:
121
+ if path not in cache:
122
+ try:
123
+ cache[path] = run_orca_2json(path, workdir)
124
+ except Exception as e:
125
+ problems.append(f"Z={Z} {cid}: {e}")
126
+ continue
127
+ atoms = cache[path]
128
+ prev_ecp_elem = None
129
+ for a in atoms:
130
+ zi = int(a["ElementNumber"])
131
+ zeff = float(a["NuclearCharge"])
132
+ has_ecp = zi - zeff > 0
133
+ if zi == Z:
134
+ seen_basis.append(shell_key(a["Basis"]))
135
+ zeff_seen.add(zeff)
136
+ if has_ecp:
137
+ blk = a.get("ECPs")
138
+ ncore = int(round(zi - zeff))
139
+ # trust the block only when it cannot be a leak: consistent N_core and
140
+ # no different ECP element printed before this atom
141
+ if blk and int(blk.get("N_core", -1)) == ncore and prev_ecp_elem in (None, Z):
142
+ seen_ecp.append(shell_key(blk))
143
+ sources.append(cid)
144
+ if has_ecp:
145
+ prev_ecp_elem = zi
146
+ if not seen_basis:
147
+ problems.append(f"Z={Z}: no basis exported")
148
+ continue
149
+ if len(set(seen_basis)) != 1:
150
+ problems.append(f"Z={Z}: basis differs between occurrences ({len(set(seen_basis))} variants)")
151
+ if len(zeff_seen) != 1:
152
+ problems.append(f"Z={Z}: NuclearCharge differs between occurrences {sorted(zeff_seen)}")
153
+ zeff = sorted(zeff_seen)[0]
154
+ ecp = None
155
+ if Z - zeff > 0:
156
+ if not seen_ecp:
157
+ problems.append(f"Z={Z}: ECP expected (Z_eff={zeff}) but no trustworthy block found")
158
+ else:
159
+ if len(set(seen_ecp)) != 1:
160
+ problems.append(f"Z={Z}: ECP block differs between sources")
161
+ ecp = json.loads(seen_ecp[0])
162
+ basis = json.loads(seen_basis[0])
163
+ nao = sum({"s": 1, "p": 3, "d": 5, "f": 7, "g": 9, "h": 11}[s["Shell"]] for s in basis)
164
+ elements[str(Z)] = {
165
+ "symbol": SYMBOLS[Z], "Z": Z, "Z_eff": zeff, "n_core": int(round(Z - zeff)),
166
+ "n_ao": nao, "shells": [s["Shell"] for s in basis], "basis": basis, "ecp": ecp,
167
+ "n_sources": len(set(sources)), "n_ecp_blocks_checked": len(seen_ecp),
168
+ }
169
+ print(f" Z={Z:3d} {SYMBOLS[Z]:2s} Z_eff={zeff:5.1f} shells={''.join(s['Shell'] for s in basis)} "
170
+ f"nao={nao} ecp={'yes' if ecp else 'no'} sources={len(set(sources))}", flush=True)
171
+ shutil.rmtree(workdir, ignore_errors=True)
172
+ out = {
173
+ "basis_name": "def2-TZVPD as stored by ORCA 6.0.0 (exported with orca_2json, Basisset only)",
174
+ "conventions": {
175
+ "functions": "spherical harmonics",
176
+ "ao_order": "per atom, shells in the listed order; within a shell m order "
177
+ "p=(z,x,y) d=(z2,xz,yz,x2-y2,xy) f=(0,+1,-1,+2,-2,+3,-3)",
178
+ "sign_vs_pyscf": "f(+3) and f(-3) carry the opposite sign to pyscf's real solid harmonics",
179
+ "normalisation": "contraction coefficients exactly as orca_2json prints them",
180
+ "ecp": "ECPs.potential: per l, ecp = [exponents, coefficients, powers]; N_core electrons replaced",
181
+ },
182
+ "elements": elements,
183
+ "problems": problems,
184
+ }
185
+ with open(args.out, "w") as fh:
186
+ json.dump(out, fh, indent=1)
187
+ print(f"\nwrote {args.out}: {len(elements)} elements, {len(problems)} problems")
188
+ for p in problems:
189
+ print(" PROBLEM:", p)
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()
fullC/code/gbw_reader.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal reader for ORCA 6 .gbw files (reverse-engineered, validated against orca.out on OMol25 data).
2
+
3
+ Layout: 64-byte header of little-endian int64 words; word 3 (byte 24) points to the MO block:
4
+ int32 n_operators (1 = RHF/RKS, 2 = UHF/UKS), int32 dim, then for each operator
5
+ dim*dim float64 coefficients stored so that reshape(dim, dim) gives C[ao, mo], dim float64 occupations,
6
+ dim float64 orbital energies (Eh), dim int32 irreps, dim int32 core flags.
7
+ Returns C[ao, mo] (columns = MOs) in ORCA AO ordering; C^T S C = I verified to 1e-7 against pyscf S.
8
+ """
9
+ import struct, numpy as np, zstandard as zstd
10
+
11
+ def read_gbw(path):
12
+ b = open(path, "rb").read()
13
+ if path.endswith(".zstd0") or b[:4] == b"\x28\xb5\x2f\xfd":
14
+ b = zstd.ZstdDecompressor().decompressobj().decompress(b)
15
+ hdr = struct.unpack_from("<8q", b, 0)
16
+ ptr = hdr[3]
17
+ nop, dim = struct.unpack_from("<ii", b, ptr); off = ptr + 8
18
+ ops = []
19
+ for _ in range(nop):
20
+ C = np.frombuffer(b, dtype="<f8", count=dim*dim, offset=off).reshape(dim, dim).copy(); off += dim*dim*8
21
+ occ = np.frombuffer(b, dtype="<f8", count=dim, offset=off).copy(); off += dim*8
22
+ en = np.frombuffer(b, dtype="<f8", count=dim, offset=off).copy(); off += dim*8
23
+ irrep = np.frombuffer(b, dtype="<i4", count=dim, offset=off).copy(); off += dim*4
24
+ core = np.frombuffer(b, dtype="<i4", count=dim, offset=off).copy(); off += dim*4
25
+ ops.append(dict(C=C, occ=occ, energies=en, irrep=irrep, core=core))
26
+ return dict(nbas=dim, nop=nop, ops=ops, header=hdr)
27
+
28
+ if __name__ == "__main__":
29
+ import sys
30
+ sys.path.insert(0, "/global/u1/e/ericqu/omol_elec_process")
31
+ from check_overlap import parse, orca_overlap
32
+ from pyscf import gto
33
+ G = "/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/gbw_pilot"; S_ = "/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/samples"
34
+ def inflate(v):
35
+ n = int((np.sqrt(8*len(v)+1)-1)//2); M = np.zeros((n,n)); M[np.triu_indices(n)] = v; return M + M.T - np.diag(M.diagonal())
36
+ for rel in sys.argv[1:]:
37
+ name = rel.split("/")[0]
38
+ g = read_gbw(f"{G}/{rel}/orca.gbw.zstd0"); z = np.load(f"{G}/{rel}/density_mat.npz")
39
+ atoms, charge, mult, hftyp, nbas, eps, F = parse(f"{S_}/{rel}/orca.out")
40
+ a = g["ops"][0]; C, occ, en = a["C"], a["occ"], a["energies"]
41
+ nmo = int((eps != 0).sum())
42
+ line = f"== {name:22s} {hftyp} nbas={g['nbas']} nop={g['nop']} | eps(gbw)-eps(printed) max {np.abs(en[:nmo]-eps[:nmo]).max():.1e} Eh | occ sum {occ.sum():.2f}"
43
+ # density from gbw vs npz
44
+ P_npz = inflate(z["orca.scfp"])
45
+ if g["nop"] == 2:
46
+ b_ = g["ops"][1]; Pg = C @ np.diag(occ) @ C.T + b_["C"] @ np.diag(b_["occ"]) @ b_["C"].T
47
+ else:
48
+ Pg = C @ np.diag(occ) @ C.T
49
+ line += f" | P(gbw)-P(npz) max {np.abs(Pg-P_npz).max():.1e}"
50
+ # S from C when no linear dependence: S = C^-T C^-1 ; F = C^-T diag(eps) C^-1
51
+ if nmo == nbas:
52
+ Ci = np.linalg.inv(C); F_rec = Ci.T @ np.diag(en) @ Ci; S_rec = Ci.T @ Ci
53
+ line += f" | F(gbw)-F(printed): max {np.abs(F_rec-F).max():.1e}, rms {np.sqrt(((F_rec-F)**2).mean()):.1e}"
54
+ try:
55
+ mol = gto.M(atom=atoms, basis="def2-tzvpd", ecp="def2-tzvpd", unit="Angstrom", charge=charge, spin=mult-1, verbose=0)
56
+ S, _ = orca_overlap(mol); line += f" | S(gbw)-S(pyscf) max {np.abs(S_rec-S).max():.1e}"
57
+ except Exception as e:
58
+ line += f" | pyscf basis unavailable ({type(e).__name__})"
59
+ else:
60
+ line += f" | {nbas-nmo} lin.dep. removed: C is {nbas}x{nmo}, F/S not invertible from C alone"
61
+ try:
62
+ mol = gto.M(atom=atoms, basis="def2-tzvpd", ecp="def2-tzvpd", unit="Angstrom", charge=charge, spin=mult-1, verbose=0)
63
+ S, _ = orca_overlap(mol); Ck = C[:, :nmo]
64
+ line += f" | C^T S C - I max {np.abs(Ck.T @ S @ Ck - np.eye(nmo)).max():.1e}"
65
+ F_rec = S @ Ck @ np.diag(en[:nmo]) @ Ck.T @ S
66
+ line += f" | F(S C e C^T S)-F(printed) max {np.abs(F_rec-F).max():.1e}"
67
+ except Exception as e:
68
+ line += f" | pyscf basis unavailable ({type(e).__name__})"
69
+ print(line, flush=True)
fullC/code/hf_upload.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Upload the merged 100k stores to the Hub dataset repo ericqu/OME.
2
+
3
+ Layout in the repo: fullC/{p1,p2,index.tsv,basis json,...} and occC/{...}. No README (by request).
4
+ upload_large_folder is resumable: re-running picks up where it stopped (state in .cache/ under the
5
+ folder). Run from an xfer-queue job (network access, no node-hour charge).
6
+
7
+ python hf_upload.py --folder $PSCRATCH/hf_OME --repo ericqu/OME
8
+ """
9
+ import argparse, time
10
+ from huggingface_hub import HfApi
11
+
12
+
13
+ def main():
14
+ ap = argparse.ArgumentParser()
15
+ ap.add_argument("--folder", required=True)
16
+ ap.add_argument("--repo", default="ericqu/OME")
17
+ ap.add_argument("--workers", type=int, default=16)
18
+ args = ap.parse_args()
19
+ api = HfApi()
20
+ print("user:", api.whoami()["name"], flush=True)
21
+ info = api.repo_info(args.repo, repo_type="dataset")
22
+ print(f"repo {args.repo}: private={info.private} gated={info.gated}", flush=True)
23
+ t0 = time.time()
24
+ api.upload_large_folder(repo_id=args.repo, repo_type="dataset", folder_path=args.folder,
25
+ num_workers=args.workers, print_report=True, print_report_every=120,
26
+ ignore_patterns=["README.md", "*/README.md", ".cache/*", "*/.cache/*"])
27
+ print(f"upload finished in {(time.time()-t0)/3600:.2f} h", flush=True)
28
+
29
+
30
+ if __name__ == "__main__":
31
+ main()
fullC/code/make_subset.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Draw a uniform random subset of OMol25 calculations and check they exist on m5250.
2
+
3
+ The population is the 4M-split path list shipped with the release (`4m_paths.txt`, 3,986,753 rows).
4
+ Sampling is uniform over that list with a fixed seed, so the subset keeps the collection's natural
5
+ dataset proportions and is exactly reproducible.
6
+
7
+ Writes:
8
+ subset_<n>.txt one relative path per line, present on m5250, shuffled
9
+ subset_<n>_missing.txt paths sampled but not found locally
10
+ subset_<n>_counts.tsv per-dataset counts, sampled vs population
11
+ """
12
+ import argparse, os, random, sys
13
+ from collections import Counter
14
+
15
+ M5250 = "/global/cfs/projectdirs/m5250/OMol_elec"
16
+ PATHS = ("/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/gbw_pilot/"
17
+ "source_root/4m_paths.txt")
18
+ OUTDIR = "/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/subsets"
19
+
20
+
21
+ def dataset_of(rel):
22
+ """Top-level dataset name; the omol/ tree is grouped by its second and third component."""
23
+ parts = rel.split("/")
24
+ if parts[0] == "omol" and len(parts) > 2:
25
+ return "/".join(parts[:3])
26
+ return parts[0]
27
+
28
+
29
+ def main():
30
+ ap = argparse.ArgumentParser()
31
+ ap.add_argument("-n", type=int, default=100_000)
32
+ ap.add_argument("--seed", type=int, default=20260903)
33
+ ap.add_argument("--paths", default=PATHS)
34
+ ap.add_argument("--outdir", default=OUTDIR)
35
+ ap.add_argument("--check", type=int, default=5000,
36
+ help="how many sampled paths to stat for a miss-rate estimate (0 = none)")
37
+ args = ap.parse_args()
38
+
39
+ with open(args.paths) as fh:
40
+ pop = [l.strip() for l in fh if l.strip()]
41
+ print(f"population: {len(pop):,} paths", flush=True)
42
+
43
+ rng = random.Random(args.seed)
44
+ n = min(args.n, len(pop))
45
+ sample = rng.sample(pop, n)
46
+ print(f"sampled uniformly: {n:,} (seed {args.seed})", flush=True)
47
+
48
+ os.makedirs(args.outdir, exist_ok=True)
49
+ # Stat-ing every path is slow on CFS (huge directories), and Pass A detects a missing archive
50
+ # for free, so only a subsample is checked here to estimate the miss rate.
51
+ missing = []
52
+ ncheck = min(args.check, n)
53
+ for i, rel in enumerate(sample[:ncheck]):
54
+ if not os.path.exists(os.path.join(M5250, rel, "orca.tar.zst")):
55
+ missing.append(rel)
56
+ if (i + 1) % 1000 == 0:
57
+ print(f" checked {i+1:,}/{ncheck:,}: {len(missing):,} missing", flush=True)
58
+ present = sample
59
+ rng.shuffle(present)
60
+ base = os.path.join(args.outdir, f"subset_{n//1000}k")
61
+ with open(base + ".txt", "w") as fh:
62
+ fh.write("\n".join(present) + "\n")
63
+ with open(base + "_missing.txt", "w") as fh:
64
+ fh.write("\n".join(missing) + ("\n" if missing else ""))
65
+
66
+ pop_counts = Counter(dataset_of(p) for p in pop)
67
+ got_counts = Counter(dataset_of(p) for p in present)
68
+ with open(base + "_counts.tsv", "w") as fh:
69
+ fh.write("dataset\tpopulation\tsampled\tpct_of_dataset\n")
70
+ for ds in sorted(pop_counts, key=lambda d: -pop_counts[d]):
71
+ fh.write(f"{ds}\t{pop_counts[ds]}\t{got_counts.get(ds,0)}\t"
72
+ f"{100*got_counts.get(ds,0)/pop_counts[ds]:.3f}\n")
73
+
74
+ rate = (100 * len(missing) / ncheck) if ncheck else float("nan")
75
+ print(f"\nsubset {len(present):,} paths; miss rate on {ncheck:,} checked: "
76
+ f"{len(missing):,} ({rate:.2f}%)")
77
+ print(f"datasets covered: {len(got_counts)}/{len(pop_counts)}")
78
+ zero = [d for d in pop_counts if d not in got_counts]
79
+ if zero:
80
+ print("datasets with no sampled member:")
81
+ for d in zero:
82
+ print(f" {d} (population {pop_counts[d]:,})")
83
+ print(f"\nwrote {base}.txt / _missing.txt / _counts.tsv")
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
fullC/code/merge_store.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Merge the many small Pass A/B1 shard groups of a store into a few large ones.
2
+
3
+ Pass A flushed a shard group whenever a worker had buffered ~1.2 GB of Fock data, which bounds
4
+ parser memory but leaves hundreds of groups per 100k calculations and tens of thousands of
5
+ metadata files for a loader to touch. This rewrites a store as, per dataset, the smallest number
6
+ of groups whose on-disk size stays under --group-bytes (measured on the p2 side, so p1 and p2 get
7
+ the same row layout), and writes consolidated metadata so opening a group is one JSON read.
8
+
9
+ Row order inside a merged group is the concatenation of the source groups in name order; every
10
+ ragged array is concatenated and its offsets rebased; the per-calculation attrs lists are
11
+ concatenated. Chunk shapes and codecs come from the source arrays; shard files hold
12
+ --chunks-per-shard chunks. Writing is done in whole-shard blocks by a pool of workers (one task
13
+ per destination array per block), so memory per worker stays around one shard.
14
+
15
+ python merge_store.py --src $PSCRATCH/omol_100k --dst $PSCRATCH/omol_100k_m --group-bytes 32e9
16
+ """
17
+ from __future__ import annotations
18
+ import argparse, glob, json, os, shutil, sys, time, traceback
19
+ import multiprocessing as mp
20
+ import numpy as np
21
+ import zarr
22
+
23
+ zarr.config.set({"threading.max_workers": 1, "async.concurrency": 2})
24
+ try:
25
+ import numcodecs.blosc
26
+ numcodecs.blosc.set_nthreads(1)
27
+ numcodecs.blosc.use_threads = False
28
+ except Exception:
29
+ pass
30
+
31
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
32
+
33
+ DROP_ATTRS = {"repack_verified", "occ_derived_verified", "mo_gbw_root", "n_calc", "calc_id",
34
+ "rel_path", "hftyp"}
35
+ LIST_ATTRS = ("calc_id", "rel_path", "hftyp")
36
+
37
+
38
+ def groups_by_dataset(root, side):
39
+ out = {}
40
+ for depth in ("*", "*/*/*"):
41
+ for gp in glob.glob(os.path.join(root, side, depth, "*.zarr")):
42
+ ds = os.path.relpath(os.path.dirname(gp), os.path.join(root, side))
43
+ out.setdefault(ds, []).append(gp)
44
+ return {ds: sorted(v) for ds, v in out.items()}
45
+
46
+
47
+ def dir_bytes(path):
48
+ return sum(os.path.getsize(os.path.join(r, f)) for r, _, fs in os.walk(path) for f in fs)
49
+
50
+
51
+ def plan_groups(src, group_bytes):
52
+ """Split each dataset's shard list (sorted by name) into runs whose p2 bytes stay under budget."""
53
+ p2 = groups_by_dataset(src, "p2")
54
+ plan = []
55
+ for ds, shards in sorted(p2.items()):
56
+ run, run_b = [], 0
57
+ for gp in shards:
58
+ b = dir_bytes(gp)
59
+ if run and run_b + b > group_bytes:
60
+ plan.append((ds, run)); run, run_b = [], 0
61
+ run.append(os.path.basename(gp)); run_b += b
62
+ if run:
63
+ plan.append((ds, run))
64
+ return plan
65
+
66
+
67
+ def make_group(args):
68
+ """Create one destination group (both sides): metadata, attrs, offsets. Returns write tasks."""
69
+ src, dst, side, ds, gname, members, cps = args
70
+ try:
71
+ srcs = [zarr.open_group(os.path.join(src, side, ds, m), mode="r") for m in members]
72
+ out_path = os.path.join(dst, side, ds, gname)
73
+ if os.path.isdir(out_path):
74
+ shutil.rmtree(out_path)
75
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
76
+ gd = zarr.open_group(out_path, mode="w")
77
+ attrs = {k: v for k, v in dict(srcs[0].attrs).items() if k not in DROP_ATTRS}
78
+ for g in srcs[1:]:
79
+ for k, v in attrs.items():
80
+ if g.attrs.get(k) != v:
81
+ raise RuntimeError(f"attr {k} differs between source groups of {ds}")
82
+ for k in LIST_ATTRS:
83
+ attrs[k] = sum((list(g.attrs[k]) for g in srcs), [])
84
+ attrs["n_calc"] = int(sum(int(g.attrs["n_calc"]) for g in srcs))
85
+ attrs["merged_from"] = members
86
+ gd.attrs.update(attrs)
87
+ names = sorted(srcs[0].array_keys())
88
+ for g in srcs[1:]:
89
+ if sorted(g.array_keys()) != names:
90
+ raise RuntimeError(f"array list differs between source groups of {ds}")
91
+ tasks = []
92
+ for name in names:
93
+ arrs = [g[name] for g in srcs]
94
+ if name.endswith("_offsets"):
95
+ parts, base = [np.asarray(arrs[0][...])], int(arrs[0][-1])
96
+ for a in arrs[1:]:
97
+ o = np.asarray(a[...])
98
+ parts.append(o[1:] + base); base += int(o[-1])
99
+ offs = np.concatenate(parts)
100
+ z = gd.create_array(name=name, shape=offs.shape, chunks=offs.shape, shards=offs.shape,
101
+ dtype=offs.dtype, compressors=arrs[0].compressors)
102
+ z[...] = offs
103
+ continue
104
+ lens = [int(a.shape[0]) for a in arrs]
105
+ total = sum(lens)
106
+ shape = (total,) + tuple(arrs[0].shape[1:])
107
+ chunk0 = int(arrs[0].chunks[0])
108
+ chunks = (max(1, min(total, chunk0)),) + tuple(arrs[0].shape[1:])
109
+ n_chunks = max(1, -(-total // chunks[0]))
110
+ shard_len = chunks[0] * min(cps, n_chunks)
111
+ shards = (shard_len,) + tuple(arrs[0].shape[1:])
112
+ gd.create_array(name=name, shape=shape, chunks=chunks, shards=shards,
113
+ dtype=arrs[0].dtype, compressors=arrs[0].compressors)
114
+ if total == 0:
115
+ continue
116
+ starts = np.concatenate([[0], np.cumsum(lens)[:-1]])
117
+ for a0 in range(0, total, shard_len):
118
+ a1 = min(total, a0 + shard_len)
119
+ pieces = []
120
+ for m, s0, n in zip(members, starts, lens):
121
+ lo, hi = max(a0, s0), min(a1, s0 + n)
122
+ if hi > lo:
123
+ pieces.append((m, int(lo - s0), int(hi - s0)))
124
+ tasks.append((src, side, ds, out_path, name, int(a0), int(a1), pieces))
125
+ return out_path, tasks, ""
126
+ except Exception:
127
+ return os.path.join(dst, side, ds, gname), [], traceback.format_exc(limit=4)
128
+
129
+
130
+ def write_block(args):
131
+ src, side, ds, out_path, name, a0, a1, pieces = args
132
+ t0 = time.time()
133
+ try:
134
+ chunks = [np.asarray(zarr.open_group(os.path.join(src, side, ds, m), mode="r")[name][lo:hi])
135
+ for m, lo, hi in pieces]
136
+ block = np.concatenate(chunks) if len(chunks) > 1 else chunks[0]
137
+ z = zarr.open_array(out_path + "/" + name, mode="r+")
138
+ z[a0:a1] = block
139
+ return name, block.nbytes, time.time() - t0, ""
140
+ except Exception:
141
+ return name, 0, time.time() - t0, traceback.format_exc(limit=4)
142
+
143
+
144
+ def verify_group(args):
145
+ """Every array of the merged group equals the concatenation of its sources (full compare for
146
+ arrays under 4 M elements, 3 random 200k windows otherwise); then consolidate metadata."""
147
+ src, dst, side, ds, gname = args
148
+ try:
149
+ gd = zarr.open_group(os.path.join(dst, side, ds, gname), mode="r+")
150
+ members = gd.attrs["merged_from"]
151
+ srcs = [zarr.open_group(os.path.join(src, side, ds, m), mode="r") for m in members]
152
+ rng = np.random.default_rng(abs(hash(gname)) % (2**32))
153
+ for name in gd.array_keys():
154
+ if name.endswith("_offsets"):
155
+ parts, base = [np.asarray(srcs[0][name][...])], int(srcs[0][name][-1])
156
+ for g in srcs[1:]:
157
+ o = np.asarray(g[name][...]); parts.append(o[1:] + base); base += int(o[-1])
158
+ if not np.array_equal(np.asarray(gd[name][...]), np.concatenate(parts)):
159
+ raise RuntimeError(f"{name} offsets differ")
160
+ continue
161
+ lens = [int(g[name].shape[0]) for g in srcs]
162
+ starts = np.concatenate([[0], np.cumsum(lens)[:-1]])
163
+ total = int(gd[name].shape[0])
164
+ if total != sum(lens):
165
+ raise RuntimeError(f"{name} length {total} != {sum(lens)}")
166
+ if total == 0:
167
+ continue
168
+ if gd[name].size <= 4_000_000:
169
+ windows = [(0, total)]
170
+ else:
171
+ windows = [(int(s), int(min(total, s + 200_000))) for s in rng.integers(0, total, 3)]
172
+ for w0, w1 in windows:
173
+ got = np.asarray(gd[name][w0:w1])
174
+ exp = []
175
+ for g, s0, n in zip(srcs, starts, lens):
176
+ lo, hi = max(w0, s0), min(w1, s0 + n)
177
+ if hi > lo:
178
+ exp.append(np.asarray(g[name][lo - s0:hi - s0]))
179
+ exp = np.concatenate(exp)
180
+ ok = np.array_equal(got, exp, equal_nan=True) if got.dtype.kind == "f" else np.array_equal(got, exp)
181
+ if not ok:
182
+ raise RuntimeError(f"{name} content differs in [{w0},{w1})")
183
+ n_ids = len(gd.attrs["calc_id"])
184
+ if n_ids != sum(len(g.attrs["calc_id"]) for g in srcs) or n_ids != int(gd.attrs["n_calc"]):
185
+ raise RuntimeError("calc_id list length")
186
+ zarr.consolidate_metadata(gd.store)
187
+ return gname, side, ds, "ok", ""
188
+ except Exception:
189
+ return gname, side, ds, "fail", traceback.format_exc(limit=4)
190
+
191
+
192
+ def main():
193
+ ap = argparse.ArgumentParser()
194
+ ap.add_argument("--src", required=True)
195
+ ap.add_argument("--dst", required=True)
196
+ ap.add_argument("--group-bytes", type=float, default=32e9)
197
+ ap.add_argument("--chunks-per-shard", type=int, default=64)
198
+ ap.add_argument("--workers", type=int, default=96)
199
+ ap.add_argument("--datasets", default="", help="comma list to restrict (smoke tests)")
200
+ args = ap.parse_args()
201
+ src, dst = os.path.abspath(args.src), os.path.abspath(args.dst)
202
+ t0 = time.time()
203
+ plan = plan_groups(src, args.group_bytes)
204
+ if args.datasets:
205
+ keep = set(args.datasets.split(","))
206
+ plan = [p for p in plan if p[0] in keep]
207
+ counter = {}
208
+ named = []
209
+ for ds, members in plan:
210
+ k = counter.get(ds, 0); counter[ds] = k + 1
211
+ named.append((ds, f"group_{k:03d}.zarr", members))
212
+ print(f"plan: {sum(len(m) for _, _, m in named)} source groups -> {len(named)} merged groups "
213
+ f"over {len(counter)} datasets ({(time.time()-t0)/60:.1f} min)", flush=True)
214
+ for ds, n in sorted(counter.items(), key=lambda kv: -kv[1])[:8]:
215
+ print(f" {ds}: {n} groups", flush=True)
216
+
217
+ # phase 1: create groups and gather write tasks (parallel over groups)
218
+ jobs = [(src, dst, side, ds, g, m, args.chunks_per_shard) for ds, g, m in named for side in ("p1", "p2")]
219
+ tasks = []
220
+ with mp.Pool(min(32, len(jobs))) as pool:
221
+ for out_path, t, err in pool.imap_unordered(make_group, jobs):
222
+ if err:
223
+ print(f"FAIL creating {out_path}\n{err}", flush=True); sys.exit(1)
224
+ tasks.extend(t)
225
+ # biggest blocks first so the tail is short
226
+ tasks.sort(key=lambda t: -(t[6] - t[5]))
227
+ print(f"phase 1 done: {len(jobs)} groups created, {len(tasks)} write blocks "
228
+ f"({(time.time()-t0)/60:.1f} min)", flush=True)
229
+
230
+ # phase 2: write blocks
231
+ n_ok = n_fail = 0; nbytes = 0
232
+ with mp.Pool(min(args.workers, max(1, len(tasks)))) as pool:
233
+ for k, (name, nb, dt, err) in enumerate(pool.imap_unordered(write_block, tasks), 1):
234
+ if err:
235
+ n_fail += 1; print(f"FAIL block {name}\n{err}", flush=True)
236
+ else:
237
+ n_ok += 1; nbytes += nb
238
+ if k % 500 == 0 or k == len(tasks):
239
+ el = time.time() - t0
240
+ print(f" blocks {k}/{len(tasks)} ok={n_ok} fail={n_fail} {nbytes/1e12:.3f} TB "
241
+ f"{el/60:.1f} min", flush=True)
242
+ if n_fail:
243
+ print("write failures, stopping before verification"); sys.exit(1)
244
+
245
+ # phase 3: verify and consolidate
246
+ vjobs = [(src, dst, side, ds, g) for ds, g, _ in named for side in ("p1", "p2")]
247
+ v_ok = v_fail = 0
248
+ with mp.Pool(min(args.workers, len(vjobs))) as pool:
249
+ for gname, side, ds, status, err in pool.imap_unordered(verify_group, vjobs):
250
+ if status == "ok":
251
+ v_ok += 1
252
+ else:
253
+ v_fail += 1; print(f"VERIFY FAIL {side}/{ds}/{gname}\n{err}", flush=True)
254
+ for f in glob.glob(os.path.join(src, "*")):
255
+ if os.path.isfile(f):
256
+ shutil.copy2(f, dst)
257
+ if os.path.isdir(os.path.join(src, "code")):
258
+ shutil.copytree(os.path.join(src, "code"), os.path.join(dst, "code"), dirs_exist_ok=True)
259
+ print(f"\ndone: {len(named)} merged groups per side, verify ok {v_ok} fail {v_fail}, "
260
+ f"{nbytes/1e12:.3f} TB written, wall {(time.time()-t0)/60:.1f} min")
261
+
262
+
263
+ if __name__ == "__main__":
264
+ mp.set_start_method("fork", force=True)
265
+ main()
fullC/code/omol_parse.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pass A parser: one ORCA 6.0 calculation (orca.out + orca.engrad) -> a plain-python record.
2
+
3
+ Design notes
4
+ ------------
5
+ * Single forward scan over orca.out. The file can be 600 MB, so nothing is loaded whole: the FOCK
6
+ block is consumed straight from the line iterator into its final numpy array.
7
+ * The scanner is a pushback iterator, so a sub-parser that reads one line too far can hand it back;
8
+ otherwise a section's terminating line (often the *next* section's header) would be swallowed.
9
+ * Every section is optional. Datasets differ (NBO on/off, RHF/UHF, ECPs, linear dependencies), so a
10
+ missing section leaves its fields as None rather than raising.
11
+ * The Fock matrix is returned as an int32 upper triangle in micro-Hartree, which is the storage
12
+ encoding and is lossless with respect to ORCA's 6-decimal print.
13
+ * Reduced orbital populations are aggregated to shell totals (s, p, d, f, g) per atom; the
14
+ individual components (pz, dxy, ...) are voluminous and low value, so they are skipped.
15
+
16
+ Returns a dict with keys grouped as: meta / system / atoms / pairs / orbitals / fock.
17
+ """
18
+ from __future__ import annotations
19
+ import io, os, re, subprocess, tarfile
20
+ import numpy as np
21
+
22
+ SHELLS = ("s", "p", "d", "f", "g")
23
+ EH_TO_UEH = 1e6
24
+ _COLHDR = re.compile(r"^\s+0(\s+\d+)+\s*$")
25
+ _BOND = re.compile(r"B\(\s*(\d+)-\s*(\w+)\s*,\s*(\d+)-\s*(\w+)\s*\)\s*:\s*(-?\d+\.\d+)")
26
+
27
+
28
+ class _PB:
29
+ """Line iterator with one-line pushback."""
30
+
31
+ def __init__(self, it):
32
+ self._it = iter(it)
33
+ self._buf = []
34
+
35
+ def __iter__(self):
36
+ return self
37
+
38
+ def __next__(self):
39
+ if self._buf:
40
+ return self._buf.pop()
41
+ return next(self._it)
42
+
43
+ def next(self, default=""):
44
+ try:
45
+ return self.__next__()
46
+ except StopIteration:
47
+ return default
48
+
49
+ def push(self, line):
50
+ self._buf.append(line)
51
+
52
+
53
+ def _f(tok):
54
+ try:
55
+ return float(tok)
56
+ except (TypeError, ValueError):
57
+ return None
58
+
59
+
60
+ def _after(line, sep):
61
+ _, _, rest = line.partition(sep)
62
+ return rest.strip()
63
+
64
+
65
+ def _num_after_colon(line):
66
+ return _f(line.split(":")[-1].split()[0]) if ":" in line else None
67
+
68
+
69
+ def _is_rule(t):
70
+ return bool(t) and set(t) <= set("-=*")
71
+
72
+
73
+ # ----------------------------------------------------------------------------- Fock block
74
+ def _read_matrix(pb, nbas, hdr):
75
+ """Read one nbas x nbas matrix printed in column blocks, given its first header line."""
76
+ F = np.zeros((nbas, nbas), dtype=np.float64)
77
+ done = 0
78
+ while done < nbas:
79
+ while hdr.strip() == "":
80
+ hdr = next(pb)
81
+ ncol = len(hdr.split())
82
+ rows = [next(pb) for _ in range(nbas)]
83
+ blk = np.fromstring(" ".join(rows), sep=" ", dtype=np.float64)
84
+ blk = blk.reshape(nbas, ncol + 1)[:, 1:]
85
+ F[:, done:done + ncol] = blk
86
+ done += ncol
87
+ if done < nbas:
88
+ hdr = next(pb)
89
+ return F
90
+
91
+
92
+ def _tri_u_eh(F):
93
+ iu = np.triu_indices(F.shape[0])
94
+ return np.rint(F[iu] * EH_TO_UEH).astype(np.int32)
95
+
96
+
97
+ def _next_matrix_header(pb, max_skip=6):
98
+ """Look for a column header, skipping blank and rule lines ('----', '****').
99
+ Anything else is pushed back and None is returned."""
100
+ for _ in range(max_skip + 1):
101
+ line = pb.next(None)
102
+ if line is None:
103
+ return None
104
+ t = line.strip()
105
+ if t == "" or _is_rule(t):
106
+ continue
107
+ if _COLHDR.match(line):
108
+ return line
109
+ pb.push(line)
110
+ return None
111
+ return None
112
+
113
+
114
+ # ----------------------------------------------------------------------------- sub-parsers
115
+ def _atom_charges(pb):
116
+ """' 0 Xe: 1.277884 [spin]' rows. Returns (charge, spin|None)."""
117
+ q, sp = [], []
118
+ for l2 in pb:
119
+ t = l2.strip()
120
+ if _is_rule(t):
121
+ continue
122
+ if not t:
123
+ if q:
124
+ break
125
+ continue
126
+ if ":" not in t:
127
+ pb.push(l2)
128
+ break
129
+ head, _, rest = l2.partition(":")
130
+ hp = head.split()
131
+ if not hp or not hp[0].isdigit():
132
+ pb.push(l2)
133
+ break
134
+ vals = rest.split()
135
+ if not vals:
136
+ break
137
+ q.append(float(vals[0]))
138
+ if len(vals) > 1:
139
+ sp.append(float(vals[1]))
140
+ return (np.array(q) if q else None, np.array(sp) if sp else None)
141
+
142
+
143
+ def _reduced_shells(pb, natm):
144
+ """Per-atom shell totals from a REDUCED ORBITAL CHARGES block. Returns (charge, spin|None),
145
+ each (natm, len(SHELLS)) or None."""
146
+ if not natm:
147
+ return None, None
148
+ charge = np.zeros((natm, len(SHELLS)))
149
+ spin = None
150
+ target = charge
151
+ atom = -1
152
+ for l2 in pb:
153
+ t = l2.strip()
154
+ if not t or _is_rule(t):
155
+ continue
156
+ if t == "CHARGE":
157
+ target = charge
158
+ continue
159
+ if t == "SPIN":
160
+ spin = np.zeros((natm, len(SHELLS)))
161
+ target = spin
162
+ continue
163
+ if ":" not in t: # next section banner
164
+ pb.push(l2)
165
+ break
166
+ parts = l2.split(":")
167
+ head = parts[0].split()
168
+ if head and head[0].isdigit():
169
+ atom = int(head[0])
170
+ if len(parts) >= 3 and 0 <= atom < natm:
171
+ tail = parts[1].split()
172
+ if tail and tail[-1] in SHELLS:
173
+ v = _f(parts[2].split()[0])
174
+ if v is not None:
175
+ target[atom, SHELLS.index(tail[-1])] = v
176
+ return charge, spin
177
+
178
+
179
+ def _bond_list(pb):
180
+ """'B( 0-Xe, 1-Cl) : 0.1834' three per line, ending at a blank line."""
181
+ out = []
182
+ for l2 in pb:
183
+ t = l2.strip()
184
+ if _is_rule(t):
185
+ continue
186
+ if not t:
187
+ if out:
188
+ break
189
+ continue
190
+ found = _BOND.findall(l2)
191
+ if not found:
192
+ pb.push(l2)
193
+ break
194
+ for i, _, j, _, v in found:
195
+ out.append((int(i), int(j), float(v)))
196
+ return out
197
+
198
+
199
+ def _mayer_table(pb):
200
+ cols = {k: [] for k in ("NA", "ZA", "QA", "VA", "BVA", "FA")}
201
+ for l2 in pb:
202
+ p = l2.split()
203
+ if len(p) != 8 or not p[0].isdigit():
204
+ pb.push(l2)
205
+ break
206
+ for k, v in zip(("NA", "ZA", "QA", "VA", "BVA", "FA"), p[2:]):
207
+ cols[k].append(float(v))
208
+ return {k: (np.array(v) if v else None) for k, v in cols.items()}
209
+
210
+
211
+ def _npa_summary(pb, r, natm):
212
+ """RHF rows have 7 fields (El, No, Charge, Core, Valence, Rydberg, Total); UHF rows have an
213
+ eighth, the natural spin density."""
214
+ if not natm:
215
+ return
216
+ q = np.full(natm, np.nan)
217
+ core = np.full(natm, np.nan)
218
+ val = np.full(natm, np.nan)
219
+ ryd = np.full(natm, np.nan)
220
+ spin = np.full(natm, np.nan)
221
+ for l2 in pb:
222
+ t = l2.strip()
223
+ if not t or _is_rule(t):
224
+ continue
225
+ p = t.split()
226
+ if t.startswith("* Total *"):
227
+ if len(p) >= 7:
228
+ r["npa_core"], r["npa_valence"], r["npa_rydberg"] = (
229
+ float(p[4]), float(p[5]), float(p[6]))
230
+ break
231
+ if len(p) in (7, 8) and p[1].isdigit() and _f(p[2]) is not None:
232
+ i = int(p[1]) - 1
233
+ if 0 <= i < natm:
234
+ q[i], core[i], val[i], ryd[i] = (float(p[2]), float(p[3]),
235
+ float(p[4]), float(p[5]))
236
+ if len(p) == 8:
237
+ spin[i] = float(p[7])
238
+ continue
239
+ if not np.isnan(q).all():
240
+ pb.push(l2)
241
+ break
242
+ if not np.isnan(q).all():
243
+ r["npa_q"], r["npa_atom_core"] = q, core
244
+ r["npa_atom_val"], r["npa_atom_ryd"] = val, ryd
245
+ if not np.isnan(spin).all():
246
+ r["npa_spin"] = spin
247
+
248
+
249
+ _CONFIG_SHELL = re.compile(r"(\d)([spdfg])\(\s*([\d.]+)\)")
250
+
251
+
252
+ def _natural_config(pb, natm):
253
+ """'Xe 1 [core]5s( 2.00)5p( 4.39)4f( 0.02)5d( 0.15)' -> per-atom occupancy by l."""
254
+ if not natm:
255
+ return None
256
+ out = np.zeros((natm, len(SHELLS)))
257
+ seen = False
258
+ for l2 in pb:
259
+ t = l2.strip()
260
+ if not t or _is_rule(t):
261
+ continue
262
+ p = t.split()
263
+ if len(p) >= 3 and p[1].isdigit() and ("[core]" in t or _CONFIG_SHELL.search(t)):
264
+ i = int(p[1]) - 1
265
+ if 0 <= i < natm:
266
+ for _, l, v in _CONFIG_SHELL.findall(t):
267
+ out[i, SHELLS.index(l)] += float(v)
268
+ seen = True
269
+ continue
270
+ if seen:
271
+ pb.push(l2)
272
+ break
273
+ return out if seen else None
274
+
275
+
276
+ def _orbital_energies(pb):
277
+ """Returns (eps_a, occ_a, eps_b, occ_b); the beta pair is None for RHF."""
278
+ eps_a = occ_a = eps_b = occ_b = None
279
+ eps, occ = [], []
280
+ spin = 0
281
+ for l2 in pb:
282
+ t = l2.strip()
283
+ if not t or _is_rule(t):
284
+ continue
285
+ if "SPIN UP" in t:
286
+ spin = 0
287
+ continue
288
+ if "SPIN DOWN" in t:
289
+ eps_a, occ_a = np.array(eps), np.array(occ)
290
+ eps, occ = [], []
291
+ spin = 1
292
+ continue
293
+ if t.startswith("NO") and "OCC" in t:
294
+ continue
295
+ p = t.split()
296
+ if len(p) == 4:
297
+ o, e = _f(p[1]), _f(p[2])
298
+ if o is not None and e is not None:
299
+ occ.append(o)
300
+ eps.append(e)
301
+ continue
302
+ pb.push(l2)
303
+ break
304
+ if spin == 0:
305
+ eps_a, occ_a = np.array(eps), np.array(occ)
306
+ else:
307
+ eps_b, occ_b = np.array(eps), np.array(occ)
308
+ return eps_a, occ_a, eps_b, occ_b
309
+
310
+
311
+ def _dipole(pb, r):
312
+ for l2 in pb:
313
+ t = l2.strip()
314
+ if t.startswith("Electronic contribution"):
315
+ r["dipole_elec"] = [float(x) for x in t.split(":")[1].split()]
316
+ elif t.startswith("Nuclear contribution"):
317
+ r["dipole_nuc"] = [float(x) for x in t.split(":")[1].split()]
318
+ elif t.startswith("Total Dipole Moment"):
319
+ r["dipole_total"] = [float(x) for x in t.split(":")[1].split()]
320
+ elif t.startswith("Magnitude (a.u.)"):
321
+ r["dipole_au"] = _num_after_colon(t)
322
+ elif t.startswith("Magnitude (Debye)"):
323
+ r["dipole_debye"] = _num_after_colon(t)
324
+ return
325
+
326
+
327
+ def _quadrupole(pb, r):
328
+ for l2 in pb:
329
+ t = l2.strip()
330
+ p = t.split()
331
+ if t.startswith("NUC") and len(p) >= 7:
332
+ r["quad_nuc"] = [float(x) for x in p[1:7]]
333
+ elif t.startswith("EL") and len(p) >= 7:
334
+ r["quad_elec"] = [float(x) for x in p[1:7]]
335
+ elif t.startswith("TOT") and len(p) >= 7:
336
+ r["quad_total"] = [float(x) for x in p[1:7]]
337
+ elif t.startswith("diagonalized tensor"):
338
+ nxt = next(pb).split()
339
+ if len(nxt) >= 3:
340
+ r["quad_diag"] = [float(x) for x in nxt[:3]]
341
+ elif t.startswith("Isotropic quadrupole"):
342
+ r["quad_iso"] = _num_after_colon(t)
343
+ return
344
+
345
+
346
+ # ----------------------------------------------------------------------------- main parser
347
+ def _blank_record():
348
+ return {
349
+ "version": None, "hftyp": None, "charge": None, "mult": None, "nelec": None,
350
+ "nbas": None, "naux": None, "smallest_ovlp_eig": None, "n_lindep": None,
351
+ "e_total": None, "e_nuc_rep": None, "e_one_elec": None, "e_two_elec": None,
352
+ "e_kinetic": None, "virial_ratio": None, "e_xc": None, "e_nl": None, "e_exchange": None,
353
+ "n_alpha_int": None, "n_beta_int": None,
354
+ "s2": None, "s2_ideal": None, "s2_dev": None,
355
+ "scf_converged": False, "scf_cycles": None,
356
+ "conv_denergy": None, "conv_maxdp": None, "conv_rmsdp": None, "conv_diiserr": None,
357
+ "dipole_elec": None, "dipole_nuc": None, "dipole_total": None,
358
+ "dipole_au": None, "dipole_debye": None,
359
+ "quad_nuc": None, "quad_elec": None, "quad_total": None, "quad_diag": None,
360
+ "quad_iso": None, "rot_const_cm": None, "rot_const_mhz": None,
361
+ "grad_norm": None, "grad_rms": None, "grad_max": None,
362
+ "run_time_s": None, "terminated_normally": False,
363
+ "nbo_available": False, "npa_available": False,
364
+ "npa_core": None, "npa_valence": None, "npa_rydberg": None,
365
+ "nbo_lewis": None, "nbo_nonlewis": None,
366
+ "elements": [], "coords": None, "ecp_ncore": {},
367
+ "mulliken_q": None, "mulliken_s": None, "loewdin_q": None, "loewdin_s": None,
368
+ "mayer_NA": None, "mayer_ZA": None, "mayer_QA": None,
369
+ "mayer_VA": None, "mayer_BVA": None, "mayer_FA": None,
370
+ "npa_q": None, "npa_atom_core": None, "npa_atom_val": None, "npa_atom_ryd": None,
371
+ "npa_spin": None, "natural_config": None,
372
+ "mulliken_shell_q": None, "loewdin_shell_q": None,
373
+ "mulliken_shell_s": None, "loewdin_shell_s": None,
374
+ "mayer_bo": [], "loewdin_bo": [], "mulliken_ovlp": [],
375
+ "eps_a": None, "occ_a": None, "eps_b": None, "occ_b": None,
376
+ "fock_a": None, "fock_b": None,
377
+ }
378
+
379
+
380
+ def parse_orca_out(fh):
381
+ r = _blank_record()
382
+ pb = _PB(fh)
383
+ coords = []
384
+ for line in pb:
385
+ s = line.strip()
386
+
387
+ # ---------------- header / settings
388
+ if r["version"] is None and "Program Version" in line:
389
+ r["version"] = line.split("Program Version")[1].split()[0]
390
+ elif "Hartree-Fock type" in line:
391
+ r["hftyp"] = _after(line, "....")
392
+ elif "Total Charge" in line and "...." in line:
393
+ r["charge"] = int(float(_after(line, "....")))
394
+ elif s.startswith("Multiplicity") and "Mult " in line:
395
+ r["mult"] = int(float(_after(line, "....")))
396
+ elif "Number of Electrons" in line and "...." in line:
397
+ r["nelec"] = int(float(_after(line, "....")))
398
+ elif line.startswith("Number of basis functions") and r["nbas"] is None:
399
+ r["nbas"] = int(_after(line, "..."))
400
+ elif "# of basis functions in Aux-J" in line:
401
+ r["naux"] = int(_after(line, "..."))
402
+ elif "Smallest eigenvalue" in line and r["smallest_ovlp_eig"] is None:
403
+ r["smallest_ovlp_eig"] = _f(_after(line, "..."))
404
+ elif "Number of eigenvalues below threshold" in line:
405
+ r["n_lindep"] = int(_after(line, "..."))
406
+ elif "ECP" in line and "replacing" in line and "core electrons" in line:
407
+ m = re.search(r"Type\s+(\S+)\s+ECP.*replacing\s+(\d+)\s+core electrons", line)
408
+ if m:
409
+ r["ecp_ncore"][m.group(1)] = int(m.group(2))
410
+
411
+ # ---------------- geometry
412
+ elif s == "CARTESIAN COORDINATES (ANGSTROEM)" and not r["elements"]:
413
+ next(pb)
414
+ for l2 in pb:
415
+ p = l2.split()
416
+ if len(p) != 4:
417
+ pb.push(l2)
418
+ break
419
+ r["elements"].append(p[0])
420
+ coords.append([float(p[1]), float(p[2]), float(p[3])])
421
+
422
+ # ---------------- energies
423
+ elif s.startswith("Total Energy") and ":" in line and r["e_total"] is None:
424
+ r["e_total"] = _num_after_colon(line)
425
+ elif s.startswith("Nuclear Repulsion") and ":" in line:
426
+ r["e_nuc_rep"] = _num_after_colon(line)
427
+ elif s.startswith("One Electron Energy"):
428
+ r["e_one_elec"] = _num_after_colon(line)
429
+ elif s.startswith("Two Electron Energy"):
430
+ r["e_two_elec"] = _num_after_colon(line)
431
+ elif s.startswith("Kinetic Energy"):
432
+ r["e_kinetic"] = _num_after_colon(line)
433
+ elif s.startswith("Virial Ratio"):
434
+ r["virial_ratio"] = _num_after_colon(line)
435
+ elif s.startswith("E(XC)"):
436
+ r["e_xc"] = _num_after_colon(line)
437
+ elif s.startswith("NL Energy, E(C,NL)"):
438
+ r["e_nl"] = _num_after_colon(line)
439
+ elif s.startswith("New exchange energy"):
440
+ r["e_exchange"] = _num_after_colon(line)
441
+ elif s.startswith("N(Alpha)"):
442
+ r["n_alpha_int"] = _num_after_colon(line)
443
+ elif s.startswith("N(Beta)"):
444
+ r["n_beta_int"] = _num_after_colon(line)
445
+ elif s.startswith("FINAL SINGLE POINT ENERGY") and r["e_total"] is None:
446
+ r["e_total"] = _f(s.split()[-1])
447
+
448
+ # ---------------- SCF convergence
449
+ elif "SCF CONVERGED AFTER" in line:
450
+ r["scf_converged"] = True
451
+ m = re.search(r"AFTER\s+(\d+)\s+CYCLES", line)
452
+ if m:
453
+ r["scf_cycles"] = int(m.group(1))
454
+ elif s.startswith("Last Energy change"):
455
+ r["conv_denergy"] = _f(_after(line, "...").split()[0])
456
+ elif s.startswith("Last MAX-Density change"):
457
+ r["conv_maxdp"] = _f(_after(line, "...").split()[0])
458
+ elif s.startswith("Last RMS-Density change"):
459
+ r["conv_rmsdp"] = _f(_after(line, "...").split()[0])
460
+ elif s.startswith("Last DIIS Error"):
461
+ r["conv_diiserr"] = _f(_after(line, "...").split()[0])
462
+ elif s.startswith("Expectation value of <S**2>"):
463
+ r["s2"] = _num_after_colon(line)
464
+ elif s.startswith("Ideal value S*(S+1)"):
465
+ r["s2_ideal"] = _num_after_colon(line)
466
+ elif s.startswith("Deviation") and r["s2"] is not None and r["s2_dev"] is None:
467
+ r["s2_dev"] = _num_after_colon(line)
468
+
469
+ # ---------------- orbitals and Fock
470
+ elif s == "ORBITAL ENERGIES":
471
+ ea, oa, eb, ob = _orbital_energies(pb)
472
+ r["eps_a"], r["occ_a"] = ea, oa
473
+ if eb is not None:
474
+ r["eps_b"], r["occ_b"] = eb, ob
475
+ elif s == "FOCK" and r["nbas"]:
476
+ hdr = _next_matrix_header(pb, max_skip=6)
477
+ if hdr is not None:
478
+ F = _read_matrix(pb, r["nbas"], hdr)
479
+ r["fock_a"] = _tri_u_eh(F)
480
+ del F
481
+ hdr_b = _next_matrix_header(pb, max_skip=6)
482
+ if hdr_b is not None:
483
+ Fb = _read_matrix(pb, r["nbas"], hdr_b)
484
+ r["fock_b"] = _tri_u_eh(Fb)
485
+ del Fb
486
+
487
+ # ---------------- population analyses
488
+ elif s.startswith("MULLIKEN ATOMIC CHARGES"):
489
+ r["mulliken_q"], r["mulliken_s"] = _atom_charges(pb)
490
+ elif s.startswith("LOEWDIN ATOMIC CHARGES"):
491
+ r["loewdin_q"], r["loewdin_s"] = _atom_charges(pb)
492
+ elif s.startswith("MULLIKEN REDUCED ORBITAL CHARGES"):
493
+ r["mulliken_shell_q"], r["mulliken_shell_s"] = _reduced_shells(pb, len(r["elements"]))
494
+ elif s.startswith("LOEWDIN REDUCED ORBITAL CHARGES"):
495
+ r["loewdin_shell_q"], r["loewdin_shell_s"] = _reduced_shells(pb, len(r["elements"]))
496
+ elif s.startswith("MULLIKEN OVERLAP CHARGES"):
497
+ r["mulliken_ovlp"] = _bond_list(pb)
498
+ elif s.startswith("LOEWDIN BOND ORDERS"):
499
+ r["loewdin_bo"] = _bond_list(pb)
500
+ elif s.startswith("ATOM") and "BVA" in s and "ZA" in s:
501
+ for k, v in _mayer_table(pb).items():
502
+ r[f"mayer_{k}"] = v
503
+ elif s.startswith("Mayer bond orders larger than"):
504
+ r["mayer_bo"] = _bond_list(pb)
505
+
506
+ # ---------------- NBO / NPA
507
+ elif "Now starting NBO" in line:
508
+ r["nbo_available"] = True
509
+ elif s.startswith("Summary of Natural Population Analysis") and r["npa_q"] is None:
510
+ r["npa_available"] = True
511
+ _npa_summary(pb, r, len(r["elements"]))
512
+ elif s.startswith("Atom No") and "Natural Electron Configuration" in s and r["natural_config"] is None:
513
+ r["natural_config"] = _natural_config(pb, len(r["elements"]))
514
+ elif s.startswith("Total Lewis") and r["nbo_lewis"] is None:
515
+ p = s.split()
516
+ if len(p) > 2:
517
+ r["nbo_lewis"] = _f(p[2])
518
+ elif s.startswith("Total non-Lewis") and r["nbo_nonlewis"] is None:
519
+ p = s.split()
520
+ if len(p) > 2:
521
+ r["nbo_nonlewis"] = _f(p[2])
522
+
523
+ # ---------------- properties
524
+ elif s == "DIPOLE MOMENT" and r["dipole_total"] is None:
525
+ _dipole(pb, r)
526
+ elif s == "QUADRUPOLE MOMENT" and r["quad_total"] is None:
527
+ _quadrupole(pb, r)
528
+ elif s.startswith("Rotational constants in cm-1"):
529
+ r["rot_const_cm"] = [float(x) for x in s.split(":")[1].split()]
530
+ elif s.startswith("Rotational constants in MHz"):
531
+ r["rot_const_mhz"] = [float(x) for x in s.split(":")[1].split()]
532
+ elif s.startswith("Norm of the Cartesian gradient"):
533
+ r["grad_norm"] = _f(_after(line, "..."))
534
+ elif s.startswith("RMS gradient"):
535
+ r["grad_rms"] = _f(_after(line, "..."))
536
+ elif s.startswith("MAX gradient"):
537
+ r["grad_max"] = _f(_after(line, "..."))
538
+ elif "ORCA TERMINATED NORMALLY" in line:
539
+ r["terminated_normally"] = True
540
+ elif s.startswith("TOTAL RUN TIME"):
541
+ m = re.search(r"(\d+) days (\d+) hours (\d+) minutes (\d+) seconds (\d+) msec", s)
542
+ if m:
543
+ d, h, mi, sec, ms = (int(x) for x in m.groups())
544
+ r["run_time_s"] = d * 86400 + h * 3600 + mi * 60 + sec + ms / 1000
545
+
546
+ r["coords"] = np.array(coords, dtype=np.float64) if coords else None
547
+ return r
548
+
549
+
550
+ # ----------------------------------------------------------------------------- engrad
551
+ def parse_engrad(fh):
552
+ """Returns (n_atoms, energy, gradient (n,3) Eh/bohr, Z (n,), coords_bohr (n,3))."""
553
+ lines = [l for l in fh if not l.lstrip().startswith("#") and l.strip()]
554
+ it = iter(lines)
555
+ n = int(next(it).split()[0])
556
+ energy = float(next(it).split()[0])
557
+ vals = [float(next(it).split()[0]) for _ in range(3 * n)]
558
+ zs, xyz = [], []
559
+ for _ in range(n):
560
+ p = next(it).split()
561
+ zs.append(int(p[0]))
562
+ xyz.append([float(x) for x in p[1:4]])
563
+ return n, energy, np.array(vals).reshape(n, 3), np.array(zs), np.array(xyz)
564
+
565
+
566
+ def iter_lines(fb, encoding="utf-8", chunk=1 << 20):
567
+ """Yield decoded lines from a binary stream. tarfile's stream mode ('r|') hands back objects
568
+ that TextIOWrapper rejects (no seekable()), so decoding is done here."""
569
+ buf = b""
570
+ while True:
571
+ data = fb.read(chunk)
572
+ if not data:
573
+ break
574
+ buf += data
575
+ parts = buf.split(b"\n")
576
+ buf = parts.pop()
577
+ for part in parts:
578
+ yield part.decode(encoding, "replace")
579
+ if buf:
580
+ yield buf.decode(encoding, "replace")
581
+
582
+
583
+ # ----------------------------------------------------------------------------- archive entry
584
+ def parse_archive(tar_path):
585
+ """Stream an orca.tar.zst and parse the members we need. Never writes to disk."""
586
+ proc = subprocess.Popen(["zstd", "-dc", tar_path], stdout=subprocess.PIPE,
587
+ stderr=subprocess.DEVNULL)
588
+ rec, grad = None, None
589
+ try:
590
+ with tarfile.open(fileobj=proc.stdout, mode="r|") as tf:
591
+ for member in tf:
592
+ name = os.path.basename(member.name)
593
+ if name == "orca.out":
594
+ rec = parse_orca_out(iter_lines(tf.extractfile(member)))
595
+ elif name == "orca.engrad":
596
+ grad = parse_engrad(iter_lines(tf.extractfile(member)))
597
+ finally:
598
+ if proc.stdout:
599
+ proc.stdout.close()
600
+ proc.wait()
601
+ if rec is None:
602
+ raise ValueError(f"no orca.out in {tar_path}")
603
+ if grad is not None:
604
+ n, e_grad, g, z, xyz_bohr = grad
605
+ rec["forces"] = -g
606
+ rec["atomic_numbers"] = z
607
+ rec["coords_bohr"] = xyz_bohr
608
+ rec["e_total_engrad"] = e_grad
609
+ else:
610
+ rec["forces"] = rec["atomic_numbers"] = None
611
+ rec["coords_bohr"] = rec["e_total_engrad"] = None
612
+ return rec
fullC/code/omol_store.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Zarr v3 shard writer for Pass A.
2
+
3
+ Layout
4
+ ------
5
+ Each worker writes self-contained *shards*, so there is no write contention and no resize logic:
6
+
7
+ store/p1/<dataset>/shard_<nnnn>_<nn>.zarr scalars + per-atom + per-pair
8
+ store/p2/<dataset>/shard_<nnnn>_<nn>.zarr the same, plus fock/, eps/, occ/
9
+
10
+ p2 duplicates the p1 arrays on purpose: the tables are tiny next to the matrices (<0.2 TB for the
11
+ whole collection) and it keeps p1 independently usable without the 6 TB matrix store.
12
+
13
+ Columns are *packed*: all float scalars live in one (n_calc, n_col) array, all per-atom floats in
14
+ one (n_atom_total, n_col) array, and so on, with the column names recorded in group attrs. Writing
15
+ one array per column meant ~80 Zarr arrays per shard, and zarr-python's sync wrapper costs enough
16
+ per array that shard writes dominated the run; packing cuts that to ~15 arrays.
17
+
18
+ Ragged quantities are a concatenated array plus an int64 offsets array of length n_calc+1, so
19
+ calculation i occupies [off[i], off[i+1]).
20
+
21
+ Codecs follow the benchmark: Blosc zstd 9 + bit-shuffle for the int32 Fock triangles (4.5x), Blosc
22
+ zstd 5 + byte-shuffle elsewhere.
23
+ """
24
+ from __future__ import annotations
25
+ import os
26
+ import numpy as np
27
+ import zarr
28
+ from zarr.codecs import BloscCodec
29
+
30
+ SHELLS = ("s", "p", "d", "f", "g")
31
+
32
+ FOCK_CODEC = [BloscCodec(cname="zstd", clevel=9, shuffle="bitshuffle")]
33
+ DATA_CODEC = [BloscCodec(cname="zstd", clevel=5, shuffle="shuffle")]
34
+
35
+ SCALARS_F8 = (
36
+ "e_total", "e_total_engrad", "e_nuc_rep", "e_one_elec", "e_two_elec", "e_kinetic",
37
+ "virial_ratio", "e_xc", "e_nl", "e_exchange", "n_alpha_int", "n_beta_int",
38
+ "s2", "s2_ideal", "s2_dev", "conv_denergy", "conv_maxdp", "conv_rmsdp", "conv_diiserr",
39
+ "smallest_ovlp_eig", "grad_norm", "grad_rms", "grad_max", "run_time_s",
40
+ "dipole_au", "dipole_debye", "quad_iso", "npa_core", "npa_valence", "npa_rydberg",
41
+ "nbo_lewis", "nbo_nonlewis", "homo_a", "lumo_a", "gap_a", "homo_b", "lumo_b", "gap_b",
42
+ )
43
+ SCALARS_I = ("charge", "mult", "nelec", "nbas", "naux", "n_lindep", "scf_cycles", "n_atoms")
44
+ FLAGS = ("scf_converged", "terminated_normally", "nbo_available", "npa_available",
45
+ "is_uhf", "has_fock")
46
+ VEC = (("dipole_elec", 3), ("dipole_nuc", 3), ("dipole_total", 3), ("rot_const_cm", 3),
47
+ ("rot_const_mhz", 3), ("quad_diag", 3), ("quad_nuc", 6), ("quad_elec", 6),
48
+ ("quad_total", 6))
49
+
50
+ ATOM_1D = ("mulliken_q", "mulliken_s", "loewdin_q", "loewdin_s",
51
+ "mayer_NA", "mayer_ZA", "mayer_QA", "mayer_VA", "mayer_BVA", "mayer_FA",
52
+ "npa_q", "npa_atom_core", "npa_atom_val", "npa_atom_ryd", "npa_spin")
53
+ ATOM_VEC3 = ("coords", "forces")
54
+ ATOM_SHELL = ("mulliken_shell_q", "mulliken_shell_s", "loewdin_shell_q", "loewdin_shell_s",
55
+ "natural_config")
56
+ PAIRS = ("mayer_bo", "loewdin_bo", "mulliken_ovlp")
57
+
58
+ ATOM_F8_COLS = [f"{k}_{ax}" for k in ATOM_VEC3 for ax in "xyz"] + list(ATOM_1D)
59
+ VEC_COLS = [f"{name}_{i}" for name, w in VEC for i in range(w)]
60
+ SHELL_COLS = [f"{k}_{sh}" for k in ATOM_SHELL for sh in SHELLS]
61
+
62
+
63
+ def frontier(eps, occ):
64
+ """HOMO, LUMO and gap in Eh. Orbitals removed for linear dependence print as exactly 0.0."""
65
+ if eps is None or occ is None or len(eps) == 0:
66
+ return np.nan, np.nan, np.nan
67
+ occupied = np.flatnonzero(occ > 0)
68
+ if occupied.size == 0:
69
+ return np.nan, np.nan, np.nan
70
+ h = int(occupied[-1])
71
+ homo = float(eps[h])
72
+ lumo = np.nan
73
+ for k in range(h + 1, len(eps)):
74
+ if eps[k] != 0.0:
75
+ lumo = float(eps[k])
76
+ break
77
+ return homo, lumo, (lumo - homo if lumo == lumo else np.nan)
78
+
79
+
80
+ def _fock_chunk_elems(median_nbas):
81
+ if median_nbas < 600:
82
+ return 65_536
83
+ if median_nbas <= 2000:
84
+ return 1_000_000
85
+ return 4_194_304
86
+
87
+
88
+ CHUNKS_PER_SHARD = 256
89
+
90
+
91
+ def put_array(g, name, data, codec=DATA_CODEC, chunks=None, overwrite=False):
92
+ """Create array `name` in group `g` holding `data`, using Zarr's sharding codec.
93
+
94
+ With sharding an array is a handful of files no matter how many chunks it holds. Without it
95
+ each chunk is a file: the first full run produced 1.5 to 4.7 files per calculation, on course
96
+ to exhaust the 10 M-inode scratch quota. One shard file holds CHUNKS_PER_SHARD chunks (capped
97
+ at the array itself), and the shard length is always a multiple of the chunk length as Zarr
98
+ requires. `codec=None` stores the bytes uncompressed (for incompressible fp32 coefficients).
99
+ """
100
+ data = np.ascontiguousarray(data)
101
+ if chunks is None:
102
+ if data.ndim == 1:
103
+ chunks = (max(1, min(data.shape[0], 1 << 22)),)
104
+ else:
105
+ chunks = (max(1, min(data.shape[0], 1 << 18)),) + data.shape[1:]
106
+ chunks = tuple(int(c) for c in chunks)
107
+ n_chunks = max(1, -(-data.shape[0] // chunks[0])) # ceil
108
+ shards = (chunks[0] * min(CHUNKS_PER_SHARD, n_chunks),) + tuple(data.shape[1:])
109
+ if overwrite and name in g:
110
+ del g[name]
111
+ z = g.create_array(name=name, shape=data.shape, chunks=chunks, shards=shards,
112
+ dtype=data.dtype, compressors=codec)
113
+ if data.size:
114
+ z[...] = data
115
+ return z
116
+
117
+
118
+ def write_shard(records, out_dir, shard_name, include_matrices):
119
+ """Write one shard group. Records are parser outputs augmented with calc_id/rel_path/dataset."""
120
+ os.makedirs(out_dir, exist_ok=True)
121
+ path = os.path.join(out_dir, shard_name)
122
+ g = zarr.open_group(path, mode="w")
123
+ n = len(records)
124
+ natom = [r["n_atoms"] for r in records]
125
+ atom_off = np.cumsum([0] + natom).astype("i8")
126
+
127
+ def put(name, data, codec=DATA_CODEC, chunks=None):
128
+ put_array(g, name, data, codec=codec, chunks=chunks)
129
+
130
+ # ---- identity and column names live in attrs: JSON, portable, no bytes dtype
131
+ g.attrs.update({
132
+ "schema": "omol_elec/pass_a/2",
133
+ "n_calc": n,
134
+ "shells": list(SHELLS),
135
+ "scalar_f8_cols": list(SCALARS_F8),
136
+ "scalar_i_cols": list(SCALARS_I),
137
+ "flag_cols": list(FLAGS),
138
+ "vec_cols": VEC_COLS,
139
+ "atom_f8_cols": ATOM_F8_COLS,
140
+ "atom_shell_cols": SHELL_COLS,
141
+ "pair_names": list(PAIRS),
142
+ "calc_id": [r["calc_id"] for r in records],
143
+ "rel_path": [r["rel_path"] for r in records],
144
+ "dataset": records[0]["dataset"] if n else "",
145
+ "hftyp": [(r.get("hftyp") or "?") for r in records],
146
+ "has_matrices": bool(include_matrices),
147
+ })
148
+
149
+ # ---- packed scalars
150
+ sf = np.full((n, len(SCALARS_F8)), np.nan)
151
+ for i, r in enumerate(records):
152
+ for j, k in enumerate(SCALARS_F8):
153
+ v = r.get(k)
154
+ if v is not None:
155
+ sf[i, j] = v
156
+ put("scalar_f8", sf)
157
+
158
+ si = np.full((n, len(SCALARS_I)), -1, dtype="i8")
159
+ for i, r in enumerate(records):
160
+ for j, k in enumerate(SCALARS_I):
161
+ v = r.get(k)
162
+ if v is not None:
163
+ si[i, j] = v
164
+ put("scalar_i", si)
165
+
166
+ fl = np.zeros((n, len(FLAGS)), dtype="i1")
167
+ for i, r in enumerate(records):
168
+ for j, k in enumerate(FLAGS):
169
+ if k == "is_uhf":
170
+ fl[i, j] = bool(r.get("hftyp") == "UHF")
171
+ elif k == "has_fock":
172
+ fl[i, j] = r.get("fock_a") is not None
173
+ else:
174
+ fl[i, j] = bool(r.get(k))
175
+ put("flags", fl)
176
+
177
+ vv = np.full((n, len(VEC_COLS)), np.nan)
178
+ for i, r in enumerate(records):
179
+ c = 0
180
+ for name, w in VEC:
181
+ v = r.get(name)
182
+ if v is not None and len(v) == w:
183
+ vv[i, c:c + w] = v
184
+ c += w
185
+ put("vec", vv)
186
+
187
+ # ---- per-atom, packed
188
+ put("atom_offsets", atom_off)
189
+ tot = int(atom_off[-1])
190
+ az = np.zeros(tot, dtype="i2")
191
+ af = np.full((tot, len(ATOM_F8_COLS)), np.nan)
192
+ ash = np.full((tot, len(SHELL_COLS)), np.nan, dtype="f4")
193
+ for i, r in enumerate(records):
194
+ a, b = int(atom_off[i]), int(atom_off[i + 1])
195
+ z = r.get("atomic_numbers")
196
+ if z is not None:
197
+ az[a:b] = np.asarray(z, dtype="i2")
198
+ c = 0
199
+ for k in ATOM_VEC3:
200
+ v = r.get(k)
201
+ if v is not None:
202
+ af[a:b, c:c + 3] = np.asarray(v, dtype="f8").reshape(-1, 3)
203
+ c += 3
204
+ for k in ATOM_1D:
205
+ v = r.get(k)
206
+ if v is not None:
207
+ af[a:b, c] = np.asarray(v, dtype="f8")
208
+ c += 1
209
+ c = 0
210
+ for k in ATOM_SHELL:
211
+ v = r.get(k)
212
+ if v is not None:
213
+ ash[a:b, c:c + len(SHELLS)] = np.asarray(v, dtype="f4").reshape(-1, len(SHELLS))
214
+ c += len(SHELLS)
215
+ put("atom_z", az)
216
+ put("atom_f8", af)
217
+ put("atom_shell", ash)
218
+
219
+ # ---- per-pair: one offsets/index/value triple per bond-order flavour
220
+ for key in PAIRS:
221
+ idx, val, offs = [], [], [0]
222
+ for r in records:
223
+ for i, j, v in (r.get(key) or []):
224
+ idx.append((i, j))
225
+ val.append(v)
226
+ offs.append(len(val))
227
+ put(f"pair_{key}_offsets", np.array(offs, dtype="i8"))
228
+ put(f"pair_{key}_index", np.array(idx, dtype="i4").reshape(-1, 2))
229
+ put(f"pair_{key}_value", np.array(val, dtype="f4"))
230
+
231
+ # ---- orbitals and matrices (p2 only)
232
+ if include_matrices:
233
+ med = int(np.median([r["nbas"] for r in records])) if n else 1000
234
+ fchunk = _fock_chunk_elems(med)
235
+ for spin in ("a", "b"):
236
+ eps_parts, occ_parts, offs = [], [], [0]
237
+ for r in records:
238
+ e, o = r.get(f"eps_{spin}"), r.get(f"occ_{spin}")
239
+ if e is None:
240
+ e, o = np.zeros(0), np.zeros(0)
241
+ eps_parts.append(np.asarray(e, dtype="f8"))
242
+ occ_parts.append(np.asarray(o, dtype="f8"))
243
+ offs.append(offs[-1] + len(e))
244
+ put(f"eps_{spin}_offsets", np.array(offs, dtype="i8"))
245
+ put(f"eps_{spin}", np.concatenate(eps_parts) if eps_parts else np.zeros(0))
246
+ put(f"occ_{spin}", np.concatenate(occ_parts) if occ_parts else np.zeros(0))
247
+
248
+ fparts, foffs = [], [0]
249
+ for r in records:
250
+ f = r.get(f"fock_{spin}")
251
+ f = np.zeros(0, dtype="i4") if f is None else np.asarray(f, dtype="i4")
252
+ fparts.append(f)
253
+ foffs.append(foffs[-1] + len(f))
254
+ flat = np.concatenate(fparts) if fparts else np.zeros(0, dtype="i4")
255
+ put(f"fock_{spin}_offsets", np.array(foffs, dtype="i8"))
256
+ put(f"fock_{spin}", flat, codec=FOCK_CODEC,
257
+ chunks=(max(1, min(len(flat), fchunk)),))
258
+ return path
259
+
260
+
261
+ def shard_bytes(rec):
262
+ """Rough in-memory footprint, used to decide when to flush a shard."""
263
+ b = 0
264
+ for k in ("fock_a", "fock_b", "eps_a", "eps_b", "occ_a", "occ_b"):
265
+ v = rec.get(k)
266
+ if v is not None:
267
+ b += v.nbytes
268
+ return b + 4096
269
+
270
+
271
+ # ----------------------------------------------------------------------------- reading
272
+ def read_calc(g, i):
273
+ """Unpack calculation i from an open shard group into a dict."""
274
+ out = {}
275
+ sf = g["scalar_f8"][i]
276
+ for j, k in enumerate(g.attrs["scalar_f8_cols"]):
277
+ out[k] = float(sf[j])
278
+ si = g["scalar_i"][i]
279
+ for j, k in enumerate(g.attrs["scalar_i_cols"]):
280
+ out[k] = int(si[j])
281
+ fl = g["flags"][i]
282
+ for j, k in enumerate(g.attrs["flag_cols"]):
283
+ out[k] = bool(fl[j])
284
+ vv = g["vec"][i]
285
+ c = 0
286
+ for name, w in VEC:
287
+ out[name] = np.asarray(vv[c:c + w])
288
+ c += w
289
+ out["calc_id"] = g.attrs["calc_id"][i]
290
+ out["rel_path"] = g.attrs["rel_path"][i]
291
+ out["hftyp"] = g.attrs["hftyp"][i]
292
+ out["dataset"] = g.attrs["dataset"]
293
+
294
+ a, b = int(g["atom_offsets"][i]), int(g["atom_offsets"][i + 1])
295
+ out["atomic_numbers"] = np.asarray(g["atom_z"][a:b])
296
+ af = np.asarray(g["atom_f8"][a:b])
297
+ cols = g.attrs["atom_f8_cols"]
298
+ out["coords"] = af[:, [cols.index(f"coords_{x}") for x in "xyz"]]
299
+ out["forces"] = af[:, [cols.index(f"forces_{x}") for x in "xyz"]]
300
+ for k in ATOM_1D:
301
+ out[k] = af[:, cols.index(k)]
302
+ ash = np.asarray(g["atom_shell"][a:b])
303
+ for j, k in enumerate(ATOM_SHELL):
304
+ out[k] = ash[:, j * len(SHELLS):(j + 1) * len(SHELLS)]
305
+ for key in PAIRS:
306
+ p0 = int(g[f"pair_{key}_offsets"][i])
307
+ p1 = int(g[f"pair_{key}_offsets"][i + 1])
308
+ out[key] = (np.asarray(g[f"pair_{key}_index"][p0:p1]),
309
+ np.asarray(g[f"pair_{key}_value"][p0:p1]))
310
+ if g.attrs.get("has_matrices"):
311
+ for spin in ("a", "b"):
312
+ e0 = int(g[f"eps_{spin}_offsets"][i])
313
+ e1 = int(g[f"eps_{spin}_offsets"][i + 1])
314
+ out[f"eps_{spin}"] = np.asarray(g[f"eps_{spin}"][e0:e1])
315
+ out[f"occ_{spin}"] = np.asarray(g[f"occ_{spin}"][e0:e1])
316
+ f0 = int(g[f"fock_{spin}_offsets"][i])
317
+ f1 = int(g[f"fock_{spin}_offsets"][i + 1])
318
+ out[f"fock_{spin}"] = np.asarray(g[f"fock_{spin}"][f0:f1])
319
+ return out
320
+
321
+
322
+ def inflate_fock(tri, nbas):
323
+ """int32 micro-Hartree upper triangle -> symmetric float64 matrix in Eh."""
324
+ M = np.zeros((nbas, nbas))
325
+ M[np.triu_indices(nbas)] = tri.astype(np.float64) * 1e-6
326
+ return M + M.T - np.diag(M.diagonal())
327
+
328
+
329
+ def read_mo(g, i, spin="a"):
330
+ """MO coefficient matrix C[ao, mo] of calculation i for one spin channel (after Pass B1).
331
+
332
+ Stored MO-major (C^T) so the occupied block is a contiguous prefix; this returns the
333
+ (nbas, n_stored) matrix with columns = MOs in ORCA AO order: all nbas orbitals in a full-C
334
+ store, the nocc occupied ones in an occupied-only store (see attrs["mo_content"]). Empty
335
+ (nbas, 0) when the channel is absent (beta of an RHF run) or the gbw was not paired.
336
+ """
337
+ nbas = int(g["scalar_i"][i][list(g.attrs["scalar_i_cols"]).index("nbas")])
338
+ o0, o1 = int(g[f"cmo_{spin}_offsets"][i]), int(g[f"cmo_{spin}_offsets"][i + 1])
339
+ if o1 == o0:
340
+ return np.zeros((nbas, 0), dtype=g[f"cmo_{spin}"].dtype)
341
+ # (nbas, nbas) in a full-C store, (nbas, nocc) in an occupied-only one (attrs["mo_content"])
342
+ return np.asarray(g[f"cmo_{spin}"][o0:o1]).reshape(-1, nbas).T
343
+
344
+
345
+ def read_cocc(g, i):
346
+ """Occupied MO coefficients and gbw orbital data for calculation i (after Pass B1).
347
+
348
+ Returns C_a (nbas, nocc_a) and C_b (nbas, nocc_b) in ORCA AO order, the occupations of those
349
+ columns, the full gbw orbital energies and occupations, and the B1 flags. Empty arrays when the
350
+ gbw was not paired; check flags['mo_ok'] before trusting the pairing.
351
+ """
352
+ out = {}
353
+ nbas = int(g["scalar_i"][i][list(g.attrs["scalar_i_cols"]).index("nbas")])
354
+ mi = g["mo_i"][i]
355
+ for j, k in enumerate(g.attrs["mo_i_cols"]):
356
+ out[k] = int(mi[j])
357
+ mf = g["mo_f8"][i]
358
+ for j, k in enumerate(g.attrs["mo_f8_cols"]):
359
+ out[k] = float(mf[j])
360
+ fl = g["mo_flags"][i]
361
+ out["flags"] = {k: bool(fl[j]) for j, k in enumerate(g.attrs["mo_flag_cols"])}
362
+ for s in "ab":
363
+ nocc = out[f"nocc_{s}"]
364
+ o0, o1 = int(g[f"cmo_{s}_offsets"][i]), int(g[f"cmo_{s}_offsets"][i + 1])
365
+ if o1 > o0 and nocc:
366
+ # first nocc rows of C^T, read without touching the virtual block
367
+ out[f"C_{s}"] = np.asarray(g[f"cmo_{s}"][o0:o0 + nocc * nbas]).reshape(nocc, nbas).T
368
+ else:
369
+ out[f"C_{s}"] = np.zeros((nbas, 0), dtype=g[f"cmo_{s}"].dtype)
370
+ for name in ("gbw_eps", "gbw_occ"):
371
+ a, b = int(g[f"{name}_{s}_offsets"][i]), int(g[f"{name}_{s}_offsets"][i + 1])
372
+ out[f"{name}_{s}"] = np.asarray(g[f"{name}_{s}"][a:b])
373
+ out[f"cocc_occ_{s}"] = out[f"gbw_occ_{s}"][:nocc]
374
+ return out
fullC/code/pass_a.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pass A driver: parse a list of OMol25 calculations and write Zarr shards.
2
+
3
+ Usage (one node, all cores):
4
+ python pass_a.py --list subsets/subset_100k.txt --out store_100k --workers 64
5
+
6
+ Usage (sbatch array): add --task-id N --n-tasks M to process a contiguous stripe.
7
+
8
+ Each worker buffers records per dataset and flushes a shard once the buffer exceeds --shard-bytes,
9
+ so shard files stay a manageable size whether the systems are 15 atoms or 250.
10
+ """
11
+ from __future__ import annotations
12
+ import argparse, os, sys, time, traceback
13
+ import multiprocessing as mp
14
+ import numpy as np
15
+
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ from omol_parse import parse_archive
18
+ from omol_store import write_shard, shard_bytes, frontier
19
+
20
+ M5250 = "/global/cfs/projectdirs/m5250/OMol_elec"
21
+
22
+
23
+ def dataset_of(rel):
24
+ parts = rel.split("/")
25
+ if parts[0] == "omol" and len(parts) > 2:
26
+ return "/".join(parts[:3])
27
+ return parts[0]
28
+
29
+
30
+ def _prepare(rec, rel):
31
+ """Attach identity and derived scalars; drop what the store does not keep."""
32
+ rec["rel_path"] = rel
33
+ rec["calc_id"] = rel.replace("/", "__")
34
+ rec["dataset"] = dataset_of(rel)
35
+ rec["n_atoms"] = len(rec["elements"])
36
+ rec["homo_a"], rec["lumo_a"], rec["gap_a"] = frontier(rec.get("eps_a"), rec.get("occ_a"))
37
+ rec["homo_b"], rec["lumo_b"], rec["gap_b"] = frontier(rec.get("eps_b"), rec.get("occ_b"))
38
+ return rec
39
+
40
+
41
+ def worker(args):
42
+ """Process one (dataset, chunk) unit and write exactly one p1 and one p2 shard.
43
+
44
+ Work is grouped by dataset upstream so each shard is large. Writing many small Zarr groups is
45
+ metadata-bound on CFS (roughly 80 arrays per shard), so few-and-large is far faster.
46
+ """
47
+ (wid, ds, chunk_idx, rels, out_root, shard_budget, task_id) = args
48
+ p1_root = os.path.join(out_root, "p1")
49
+ p2_root = os.path.join(out_root, "p2")
50
+ recs, buffered, n_sub = [], 0, 0
51
+ n_ok = n_fail = 0
52
+ failures = []
53
+ t0 = time.time()
54
+
55
+ def flush():
56
+ nonlocal recs, buffered, n_sub
57
+ if not recs:
58
+ return
59
+ name = f"shard_t{task_id:02d}_{chunk_idx:04d}_{n_sub:02d}.zarr"
60
+ write_shard(recs, os.path.join(p1_root, ds), name, include_matrices=False)
61
+ write_shard(recs, os.path.join(p2_root, ds), name, include_matrices=True)
62
+ n_sub += 1
63
+ recs, buffered = [], 0
64
+
65
+ for rel in rels:
66
+ tar = os.path.join(M5250, rel, "orca.tar.zst")
67
+ try:
68
+ rec = _prepare(parse_archive(tar), rel)
69
+ # A Fock matrix is not universal: some inputs omit Print[P_Fockian] entirely
70
+ # (about a quarter of omol/redo_orca6). Those rows are still complete for Project 1,
71
+ # so they are kept and flagged rather than dropped.
72
+ if rec["nbas"] is None or not rec["elements"]:
73
+ raise ValueError("incomplete record (nbas or geometry missing)")
74
+ recs.append(rec)
75
+ buffered += shard_bytes(rec)
76
+ n_ok += 1
77
+ if buffered > shard_budget:
78
+ flush()
79
+ except Exception as e:
80
+ n_fail += 1
81
+ failures.append(f"{rel}\t{type(e).__name__}\t{str(e)[:200]}")
82
+ flush()
83
+ dt = time.time() - t0
84
+ print(f"[w{wid:03d}] {ds}/{chunk_idx:04d}: ok={n_ok} fail={n_fail} "
85
+ f"{dt/max(len(rels),1):.2f}s/calc", flush=True)
86
+ return wid, n_ok, n_fail, failures, dt
87
+
88
+
89
+ def main():
90
+ ap = argparse.ArgumentParser()
91
+ ap.add_argument("--list", required=True)
92
+ ap.add_argument("--out", required=True)
93
+ ap.add_argument("--workers", type=int, default=32)
94
+ ap.add_argument("--limit", type=int, default=0)
95
+ ap.add_argument("--task-id", type=int, default=0)
96
+ ap.add_argument("--n-tasks", type=int, default=1)
97
+ ap.add_argument("--shard-bytes", type=float, default=1.5e9)
98
+ ap.add_argument("--calcs-per-chunk", type=int, default=1500,
99
+ help="calculations per work unit; one unit writes one shard")
100
+ args = ap.parse_args()
101
+
102
+ with open(args.list) as fh:
103
+ rels = [l.strip() for l in fh if l.strip()]
104
+ if args.limit:
105
+ rels = rels[:args.limit]
106
+ if args.n_tasks > 1:
107
+ rels = rels[args.task_id::args.n_tasks]
108
+ os.makedirs(args.out, exist_ok=True)
109
+ print(f"pass A: {len(rels):,} calculations, {args.workers} workers -> {args.out}", flush=True)
110
+
111
+ by_ds = {}
112
+ for rel in rels:
113
+ by_ds.setdefault(dataset_of(rel), []).append(rel)
114
+ units = []
115
+ for ds in sorted(by_ds):
116
+ lst = by_ds[ds]
117
+ for c, start in enumerate(range(0, len(lst), args.calcs_per_chunk)):
118
+ units.append((ds, c, lst[start:start + args.calcs_per_chunk]))
119
+ units.sort(key=lambda u: -len(u[2])) # longest first, so the tail is short
120
+ jobs = [(i % args.workers, ds, c, lst, args.out, args.shard_bytes, args.task_id)
121
+ for i, (ds, c, lst) in enumerate(units)]
122
+ print(f"{len(by_ds)} datasets -> {len(jobs)} work units "
123
+ f"(<= {args.calcs_per_chunk} calcs each)", flush=True)
124
+ t0 = time.time()
125
+ n_ok = n_fail = 0
126
+ all_fail = []
127
+ with mp.Pool(min(args.workers, len(jobs))) as pool:
128
+ done = 0
129
+ for wid, ok, fail, failures, dt in pool.imap_unordered(worker, jobs):
130
+ n_ok += ok
131
+ n_fail += fail
132
+ all_fail.extend(failures)
133
+ done += 1
134
+ el = time.time() - t0
135
+ print(f" units {done}/{len(jobs)} ok={n_ok:,} fail={n_fail:,} "
136
+ f"elapsed {el/60:.1f} min eta {el/done*(len(jobs)-done)/60:.1f} min", flush=True)
137
+ dt = time.time() - t0
138
+ fail_path = os.path.join(args.out, f"failures_task{args.task_id}.tsv")
139
+ if all_fail:
140
+ with open(fail_path, "w") as fh:
141
+ fh.write("rel_path\terror\tdetail\n" + "\n".join(all_fail) + "\n")
142
+ print(f"\nok {n_ok:,} failed {n_fail:,} wall {dt/60:.1f} min "
143
+ f"({dt*args.workers/max(n_ok,1):.2f} core-s per calc)")
144
+ if all_fail:
145
+ print(f"failures written to {fail_path}")
146
+
147
+
148
+ if __name__ == "__main__":
149
+ mp.set_start_method("fork", force=True) # forkserver hangs under srun on Perlmutter
150
+ main()
fullC/code/pass_b1.py ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pass B1: molecular-orbital coefficients from the gbw files into the p2 store.
2
+
3
+ For every p2 shard the worker reads each calculation's gbw (staged by Globus at
4
+ <gbw_root>/<dataset>/<calc_id>.gbw.zstd0), takes the FULL coefficient matrix of both spin
5
+ channels, checks that the gbw and the Pass A text describe the same calculation, and appends the
6
+ result to the shard group. Zarr lets arrays be added to an existing group, so p2 keeps its layout
7
+ and row order; every new array is row-aligned with the shard's existing calculations.
8
+
9
+ Added arrays:
10
+
11
+ cmo_a, cmo_a_offsets MO coefficients, MO-major: calculation i is
12
+ cmo_a[o[i]:o[i+1]].reshape(nbas, nbas) = C^T, i.e. row k is MO k
13
+ over the AOs (ORCA AO order). Occupied orbitals are the first
14
+ nocc rows, so C_occ is a contiguous prefix. float32 by default.
15
+ cmo_b, cmo_b_offsets the same for the beta channel (empty for RHF)
16
+ gbw_eps_a/b (+_offsets) fp64 orbital energies of all nbas orbitals from the gbw
17
+ gbw_occ_a/b (+_offsets) fp64 occupations of all nbas orbitals from the gbw
18
+ mo_i int columns: nocc_a, nocc_b, gbw_nbas, gbw_nop
19
+ mo_f8 diagnostics: occ_sum_a/b; eps_err_a/b = max |gbw - printed| over
20
+ the printed orbital energies; fc_offdiag_a/b = largest
21
+ off-diagonal of C_occ^T F C_occ (Eh); fc_diag_err_a/b =
22
+ max |diag(C_occ^T F C_occ) - eps_occ| (Eh); fc_bound_a/b = what
23
+ the 5e-7 Eh print rounding of F can do to that block
24
+ mo_flags gbw_found, nbas_match, nspin_match, nelec_match, spin_match,
25
+ eps_checked, eps_match, occ_contiguous, fock_checked, fock_match,
26
+ mo_ok
27
+
28
+ mo_ok is the conjunction of every check that could be run. fock_match is only meaningful when
29
+ fock_checked is set (a Fock matrix was printed and nbas agreed); it asks that the printed Fock
30
+ matrix be diagonal in the gbw's occupied orbitals to 1e-2 Eh. A mismatched pair is off by
31
+ 0.1 to 1 Eh, so the flag is a pairing test, not a convergence test. Typical values are ~1e-6 Eh,
32
+ but in near-linearly-dependent bases (smallest overlap eigenvalue ~1e-6, not removed by ORCA)
33
+ the 5e-7 Eh print rounding of F is amplified by the large MO coefficients into ~1e-3 Eh on the
34
+ occupied block even though F_print agrees with C^-T diag(e) C^-1 to 1e-5 in the AO basis. The
35
+ fc_bound columns give that rounding amplification per calculation (5e-7 x max_i ||C_i||_1^2);
36
+ compare fc_diag_err against it before reading a large value as an inconsistency.
37
+
38
+ Usage:
39
+ python pass_b1.py --store $PSCRATCH/omol_100k --gbw-root $PSCRATCH/gbw_100k --workers 48
40
+ """
41
+ from __future__ import annotations
42
+ import argparse, glob, json, os, sys, time, traceback
43
+ import multiprocessing as mp
44
+ import numpy as np
45
+ import zarr
46
+
47
+ # One thread per worker process: zarr's default pool (os.cpu_count() threads) times 64 to 96
48
+ # forked workers thrashed a 128-core node, cutting throughput several-fold.
49
+ zarr.config.set({"threading.max_workers": 1, "async.concurrency": 2})
50
+ try:
51
+ import numcodecs.blosc
52
+ numcodecs.blosc.set_nthreads(1)
53
+ numcodecs.blosc.use_threads = False
54
+ except Exception:
55
+ pass
56
+
57
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
58
+ from gbw_reader import read_gbw
59
+ from omol_store import put_array, inflate_fock
60
+
61
+ MO_I = ("nocc_a", "nocc_b", "gbw_nbas", "gbw_nop")
62
+ MO_F8 = ("occ_sum_a", "occ_sum_b", "eps_err_a", "eps_err_b",
63
+ "fc_offdiag_a", "fc_offdiag_b", "fc_diag_err_a", "fc_diag_err_b",
64
+ "fc_bound_a", "fc_bound_b")
65
+ MO_FLAGS = ("gbw_found", "nbas_match", "nspin_match", "nelec_match", "spin_match",
66
+ "eps_checked", "eps_match", "occ_contiguous", "fock_checked", "fock_match", "mo_ok")
67
+ INFORMATIONAL = ("eps_checked", "fock_checked", "mo_ok")
68
+ EPS_TOL = 5e-6 # printed to 6 decimals; rounding alone gives 5e-7
69
+ FOCK_TOL = 1e-2 # Eh; see the docstring on why the occupied block can be off by ~1e-3
70
+ CMO_CHUNK = 1 << 22
71
+ OLD_ARRAYS = ("cocc_a", "cocc_a_offsets", "cocc_b", "cocc_b_offsets", "cocc_occ_a",
72
+ "cocc_occ_a_offsets", "cocc_occ_b", "cocc_occ_b_offsets", "cocc_i", "cocc_f8",
73
+ "cocc_flags")
74
+
75
+
76
+ def p2_shards(store):
77
+ out = []
78
+ for depth in ("*", "*/*/*"):
79
+ out += glob.glob(os.path.join(store, "p2", depth, "*.zarr"))
80
+ return sorted(set(out))
81
+
82
+
83
+ def fock_check(F, C, eps):
84
+ """Largest off-diagonal of C^T F C and largest |diag - eps|, in Eh."""
85
+ M = C.T @ (F @ C)
86
+ d = np.diag(M).copy()
87
+ np.fill_diagonal(M, 0.0)
88
+ return float(np.abs(M).max()) if M.size else 0.0, float(np.abs(d - eps).max()) if d.size else 0.0
89
+
90
+
91
+ def process_shard(args):
92
+ sp, gbw_root, force, dtype = args
93
+ t0 = time.time()
94
+ try:
95
+ g = zarr.open_group(sp, mode="r+")
96
+ if g.attrs.get("has_mo") and g.attrs.get("mo_dtype") == dtype and not force:
97
+ return sp, "skip", {}, [], 0.0, ""
98
+ n = int(g.attrs["n_calc"])
99
+ ids = g.attrs["calc_id"]
100
+ ds = g.attrs["dataset"]
101
+ si = np.asarray(g["scalar_i"])
102
+ ic = {k: j for j, k in enumerate(g.attrs["scalar_i_cols"])}
103
+ fl = np.asarray(g["flags"]).astype(bool)
104
+ fc = {k: j for j, k in enumerate(g.attrs["flag_cols"])}
105
+ eps = {s: np.asarray(g[f"eps_{s}"]) for s in "ab"}
106
+ eoff = {s: np.asarray(g[f"eps_{s}_offsets"]) for s in "ab"}
107
+ foff = {s: np.asarray(g[f"fock_{s}_offsets"]) for s in "ab"}
108
+ nbas_all = si[:, ic["nbas"]].astype("i8")
109
+ nsp_all = np.where(fl[:, fc["is_uhf"]], 2, 1)
110
+
111
+ # Preallocate the coefficient buffers from the text's nbas (verified against the gbw
112
+ # below; a mismatch leaves that calculation's slot empty and flagged).
113
+ cap = {s: np.zeros(n + 1, dtype="i8") for s in "ab"}
114
+ cap["a"][1:] = np.cumsum(nbas_all ** 2)
115
+ cap["b"][1:] = np.cumsum(np.where(nsp_all == 2, nbas_all ** 2, 0))
116
+ buf = {s: np.zeros(int(cap[s][-1]), dtype=dtype) for s in "ab"}
117
+ filled = {s: np.zeros(n, dtype=bool) for s in "ab"}
118
+ geps = {s: [] for s in "ab"}
119
+ gocc = {s: [] for s in "ab"}
120
+ mi = np.zeros((n, len(MO_I)), dtype="i8")
121
+ mf = np.full((n, len(MO_F8)), np.nan)
122
+ mfl = np.zeros((n, len(MO_FLAGS)), dtype="i1")
123
+ failures = []
124
+
125
+ for i in range(n):
126
+ nbas = int(nbas_all[i])
127
+ nelec = int(si[i, ic["nelec"]])
128
+ mult = int(si[i, ic["mult"]])
129
+ is_uhf = bool(fl[i, fc["is_uhf"]])
130
+ has_fock = bool(fl[i, fc["has_fock"]])
131
+ flags = dict.fromkeys(MO_FLAGS, False)
132
+ path = os.path.join(gbw_root, ds, ids[i] + ".gbw.zstd0")
133
+ gb = None
134
+ if os.path.exists(path):
135
+ try:
136
+ gb = read_gbw(path)
137
+ flags["gbw_found"] = True
138
+ except Exception as e:
139
+ failures.append((ids[i], f"gbw read error: {type(e).__name__}: {str(e)[:120]}"))
140
+ else:
141
+ failures.append((ids[i], "gbw missing"))
142
+ if gb is None:
143
+ for s in "ab":
144
+ geps[s].append(np.zeros(0)); gocc[s].append(np.zeros(0))
145
+ mfl[i] = [flags[k] for k in MO_FLAGS]
146
+ continue
147
+
148
+ dim, nop = gb["nbas"], gb["nop"]
149
+ mi[i, MO_I.index("gbw_nbas")] = dim
150
+ mi[i, MO_I.index("gbw_nop")] = nop
151
+ flags["nbas_match"] = dim == nbas
152
+ flags["nspin_match"] = nop == (2 if is_uhf else 1)
153
+ occ_sum = {}
154
+ contiguous = True
155
+ eps_ok = True
156
+ eps_checked = False
157
+ fock_checked = fock_ok = True
158
+ for k, s in enumerate("ab"):
159
+ if k >= nop:
160
+ geps[s].append(np.zeros(0)); gocc[s].append(np.zeros(0))
161
+ occ_sum[s] = 0.0
162
+ continue
163
+ op = gb["ops"][k]
164
+ occ_v, en_v, C = op["occ"], op["energies"], op["C"]
165
+ mask = occ_v > 0
166
+ nocc = int(mask.sum())
167
+ idx = np.flatnonzero(mask)
168
+ if nocc and (idx[-1] != nocc - 1):
169
+ contiguous = False
170
+ if dim == nbas and (s == "a" or is_uhf):
171
+ # MO-major (C^T) so the occupied block is a contiguous prefix
172
+ buf[s][cap[s][i]:cap[s][i + 1]] = C.T.ravel().astype(dtype, copy=False)
173
+ filled[s][i] = True
174
+ geps[s].append(en_v.copy())
175
+ gocc[s].append(occ_v.copy())
176
+ mi[i, MO_I.index(f"nocc_{s}")] = nocc
177
+ occ_sum[s] = float(occ_v.sum())
178
+ mf[i, MO_F8.index(f"occ_sum_{s}")] = occ_sum[s]
179
+ # printed orbital energies (6 decimals) against the gbw. A reduced print level
180
+ # (the no-Fock metal_organics inputs) lists only the first few hundred orbitals,
181
+ # so compare over the printed prefix; energies of removed orbitals print as 0.
182
+ e_txt = eps[s][eoff[s][i]:eoff[s][i + 1]]
183
+ if 0 < len(e_txt) <= dim:
184
+ eps_checked = True
185
+ m = e_txt != 0.0
186
+ err = float(np.abs(en_v[:len(e_txt)][m] - e_txt[m]).max()) if m.any() else 0.0
187
+ mf[i, MO_F8.index(f"eps_err_{s}")] = err
188
+ if err > EPS_TOL:
189
+ eps_ok = False
190
+ elif len(e_txt) > dim:
191
+ eps_checked = True
192
+ eps_ok = False
193
+ # printed Fock diagonal in the gbw occupied orbitals
194
+ if has_fock and dim == nbas and nocc:
195
+ f0, f1 = int(foff[s][i]), int(foff[s][i + 1])
196
+ if f1 > f0:
197
+ Co = np.ascontiguousarray(C[:, mask])
198
+ F = inflate_fock(np.asarray(g[f"fock_{s}"][f0:f1]), nbas)
199
+ od, de = fock_check(F, Co, en_v[mask])
200
+ mf[i, MO_F8.index(f"fc_offdiag_{s}")] = od
201
+ mf[i, MO_F8.index(f"fc_diag_err_{s}")] = de
202
+ mf[i, MO_F8.index(f"fc_bound_{s}")] = 5e-7 * float(
203
+ (np.abs(Co).sum(axis=0) ** 2).max())
204
+ if od > FOCK_TOL or de > FOCK_TOL:
205
+ fock_ok = False
206
+ del F, Co
207
+ else:
208
+ fock_checked = False
209
+ else:
210
+ fock_checked = False
211
+ tot = occ_sum["a"] + occ_sum["b"]
212
+ flags["nelec_match"] = abs(tot - nelec) < 1e-6
213
+ if nop == 2:
214
+ flags["spin_match"] = abs((occ_sum["a"] - occ_sum["b"]) - (mult - 1)) < 1e-6
215
+ else:
216
+ flags["spin_match"] = mult == 1 and abs(occ_sum["a"] - nelec) < 1e-6
217
+ flags["eps_checked"] = eps_checked
218
+ flags["eps_match"] = eps_ok
219
+ flags["occ_contiguous"] = contiguous
220
+ flags["fock_checked"] = fock_checked
221
+ flags["fock_match"] = fock_ok
222
+ flags["mo_ok"] = all(flags[k] for k in MO_FLAGS if k not in INFORMATIONAL)
223
+ mfl[i] = [flags[k] for k in MO_FLAGS]
224
+ if not flags["mo_ok"]:
225
+ bad = [k for k in MO_FLAGS if k not in INFORMATIONAL and not flags[k]]
226
+ failures.append((ids[i], "failed: " + ",".join(bad)))
227
+
228
+ def ragged(parts, dt):
229
+ offs = np.zeros(len(parts) + 1, dtype="i8")
230
+ offs[1:] = np.cumsum([len(p) for p in parts])
231
+ flat = np.concatenate(parts).astype(dt) if parts else np.zeros(0, dt)
232
+ return flat, offs
233
+
234
+ for name in OLD_ARRAYS:
235
+ if name in g:
236
+ del g[name]
237
+ for s in "ab":
238
+ # offsets follow the filled slots; an unfilled slot (gbw missing or nbas mismatch)
239
+ # gets a zero-length block so the array stays dense
240
+ lens = np.where(filled[s], np.diff(cap[s]), 0)
241
+ offs = np.zeros(n + 1, dtype="i8")
242
+ offs[1:] = np.cumsum(lens)
243
+ if filled[s].all():
244
+ flat = buf[s]
245
+ else:
246
+ flat = np.concatenate([buf[s][cap[s][i]:cap[s][i + 1]] for i in range(n) if filled[s][i]]
247
+ ) if filled[s].any() else np.zeros(0, dtype)
248
+ put_array(g, f"cmo_{s}", flat, codec=None,
249
+ chunks=(max(1, min(len(flat), CMO_CHUNK)),), overwrite=True)
250
+ put_array(g, f"cmo_{s}_offsets", offs, overwrite=True)
251
+ flat, offs = ragged(geps[s], "f8")
252
+ put_array(g, f"gbw_eps_{s}", flat, overwrite=True)
253
+ put_array(g, f"gbw_eps_{s}_offsets", offs, overwrite=True)
254
+ flat, offs = ragged(gocc[s], "f8")
255
+ put_array(g, f"gbw_occ_{s}", flat, overwrite=True)
256
+ put_array(g, f"gbw_occ_{s}_offsets", offs, overwrite=True)
257
+ put_array(g, "mo_i", mi, overwrite=True)
258
+ put_array(g, "mo_f8", mf, overwrite=True)
259
+ put_array(g, "mo_flags", mfl, overwrite=True)
260
+ for k in ("has_cocc", "cocc_schema", "cocc_i_cols", "cocc_f8_cols", "cocc_flag_cols",
261
+ "cocc_layout", "cocc_gbw_root"):
262
+ g.attrs.pop(k, None)
263
+ g.attrs.update({
264
+ "has_mo": True,
265
+ "mo_schema": "omol_elec/pass_b1/2",
266
+ "mo_dtype": dtype,
267
+ "mo_i_cols": list(MO_I),
268
+ "mo_f8_cols": list(MO_F8),
269
+ "mo_flag_cols": list(MO_FLAGS),
270
+ "mo_layout": "cmo_x[o[i]:o[i+1]].reshape(nbas, nbas) = C^T (row k = MO k over AOs, "
271
+ "ORCA AO order); occupied MOs are the first nocc_x rows",
272
+ "mo_gbw_root": gbw_root,
273
+ })
274
+ stats = {
275
+ "n": n,
276
+ "found": int(mfl[:, MO_FLAGS.index("gbw_found")].sum()),
277
+ "ok": int(mfl[:, MO_FLAGS.index("mo_ok")].sum()),
278
+ "fock_checked": int(mfl[:, MO_FLAGS.index("fock_checked")].sum()),
279
+ "bytes_cmo": int(sum(int(g[f"cmo_{s}"].shape[0]) for s in "ab") * np.dtype(dtype).itemsize),
280
+ "eps_err_max": float(np.nanmax(mf[:, [2, 3]])) if np.isfinite(mf[:, [2, 3]]).any() else float("nan"),
281
+ "fc_offdiag_max": float(np.nanmax(mf[:, [4, 5]])) if np.isfinite(mf[:, [4, 5]]).any() else float("nan"),
282
+ "fc_offdiag_p50": float(np.nanmedian(mf[:, [4, 5]])) if np.isfinite(mf[:, [4, 5]]).any() else float("nan"),
283
+ }
284
+ for k in MO_FLAGS:
285
+ stats["fail_" + k] = int(n - mfl[:, MO_FLAGS.index(k)].sum())
286
+ return sp, "ok", stats, failures, time.time() - t0, ""
287
+ except Exception:
288
+ return sp, "fail", {}, [], time.time() - t0, traceback.format_exc(limit=4)
289
+
290
+
291
+ def main():
292
+ ap = argparse.ArgumentParser()
293
+ ap.add_argument("--store", required=True)
294
+ ap.add_argument("--gbw-root", required=True)
295
+ ap.add_argument("--workers", type=int, default=48)
296
+ ap.add_argument("--dtype", default="f4", choices=("f4", "f8"))
297
+ ap.add_argument("--limit", type=int, default=0)
298
+ ap.add_argument("--force", action="store_true", help="recompute shards that already have MOs")
299
+ args = ap.parse_args()
300
+ shards = p2_shards(args.store)
301
+ if args.limit:
302
+ shards = shards[:args.limit]
303
+ print(f"pass B1 (full C, {args.dtype}): {len(shards)} p2 shards in {args.store}, "
304
+ f"gbw from {args.gbw_root}", flush=True)
305
+ jobs = [(s, args.gbw_root, args.force, args.dtype) for s in shards]
306
+ t0 = time.time()
307
+ tot = {}
308
+ all_fail, shard_fail = [], []
309
+ n_skip = 0
310
+ eps_max = fc_max = 0.0
311
+ fc_p50 = []
312
+ with mp.Pool(min(args.workers, len(jobs))) as pool:
313
+ for k, (sp, status, st, failures, dt, err) in enumerate(pool.imap_unordered(process_shard, jobs), 1):
314
+ if status == "ok":
315
+ for key, v in st.items():
316
+ if key.startswith(("n", "found", "ok", "fock_checked", "bytes", "fail_")):
317
+ tot[key] = tot.get(key, 0) + v
318
+ if st["eps_err_max"] == st["eps_err_max"]:
319
+ eps_max = max(eps_max, st["eps_err_max"])
320
+ if st["fc_offdiag_max"] == st["fc_offdiag_max"]:
321
+ fc_max = max(fc_max, st["fc_offdiag_max"])
322
+ if st["fc_offdiag_p50"] == st["fc_offdiag_p50"]:
323
+ fc_p50.append(st["fc_offdiag_p50"])
324
+ all_fail.extend((sp, cid, why) for cid, why in failures)
325
+ elif status == "skip":
326
+ n_skip += 1
327
+ else:
328
+ shard_fail.append((sp, err))
329
+ print(f"SHARD FAIL {sp}\n{err}", flush=True)
330
+ if k % 50 == 0 or k == len(jobs):
331
+ el = time.time() - t0
332
+ print(f" {k}/{len(jobs)} calcs {tot.get('n',0):,} found {tot.get('found',0):,} "
333
+ f"ok {tot.get('ok',0):,} {tot.get('bytes_cmo',0)/1e9:.0f} GB {el/60:.1f} min "
334
+ f"eta {el/k*(len(jobs)-k)/60:.1f} min", flush=True)
335
+ dt = time.time() - t0
336
+ print(f"\nB1 done in {dt/60:.1f} min: shards ok {len(jobs)-n_skip-len(shard_fail)}, "
337
+ f"skipped {n_skip}, failed {len(shard_fail)}")
338
+ print(f"calculations {tot.get('n',0):,}: gbw found {tot.get('found',0):,}, "
339
+ f"mo_ok {tot.get('ok',0):,}, fock checked {tot.get('fock_checked',0):,}")
340
+ for k in MO_FLAGS:
341
+ print(f" not {k:15s}: {tot.get('fail_'+k, 0):,}")
342
+ print(f"C bytes {tot.get('bytes_cmo',0)/1e12:.3f} TB "
343
+ f"({tot.get('bytes_cmo',0)/max(tot.get('n',1),1)/1e6:.2f} MB/calc, {args.dtype})")
344
+ print(f"max eps error (gbw vs printed) {eps_max:.2e} Eh; "
345
+ f"C_occ^T F C_occ off-diagonal: median-of-shard-medians "
346
+ f"{np.median(fc_p50) if fc_p50 else float('nan'):.2e}, max {fc_max:.2e} Eh")
347
+ out = os.path.join(args.store, "b1_failures.tsv")
348
+ with open(out, "w") as fh:
349
+ fh.write("shard\tcalc_id\treason\n")
350
+ for sp, cid, why in all_fail:
351
+ fh.write(f"{os.path.relpath(sp, args.store)}\t{cid}\t{why}\n")
352
+ print(f"{len(all_fail)} per-calculation problems written to {out}")
353
+ with open(os.path.join(args.store, "b1_summary.json"), "w") as fh:
354
+ json.dump({"totals": tot, "dtype": args.dtype, "eps_err_max": eps_max,
355
+ "fc_offdiag_max": fc_max, "wall_s": dt,
356
+ "shard_failures": [s for s, _ in shard_fail]}, fh, indent=1)
357
+
358
+
359
+ if __name__ == "__main__":
360
+ mp.set_start_method("fork", force=True)
361
+ main()
fullC/code/pyproject.toml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "omol-elec-process"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "basis-set-exchange>=0.12",
9
+ "hdf5plugin>=7.1.0",
10
+ "numpy>=2.5.2",
11
+ "pandas>=3.0.5",
12
+ "pyarrow>=25.0.1",
13
+ "pyscf>=2.14.0",
14
+ "scipy>=1.18.1",
15
+ "tqdm>=4.70.0",
16
+ "zarr>=3.3.0",
17
+ "zstandard>=0.25.0",
18
+ ]
fullC/code/repack_store.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Re-pack a Pass A store into the sharded Zarr layout.
2
+
3
+ Shards written before the 2026-09-04 fix hold one file per chunk (1.5 to 4.7 files per
4
+ calculation); the fixed writer groups 256 chunks per file. This copies every shard group of a
5
+ store array by array, keeping dtype, chunk shape and codecs and adding the sharding codec, and
6
+ verifies each copy element for element before marking it done. Groups already in the sharded
7
+ layout are copied unchanged. Safe to re-run: a destination group carrying the `repack_verified`
8
+ attribute is skipped.
9
+
10
+ python repack_store.py --src $PSCRATCH/omol_store_100k --dst $PSCRATCH/omol_100k --workers 64
11
+ """
12
+ from __future__ import annotations
13
+ import argparse, glob, os, shutil, sys, time, traceback
14
+ import multiprocessing as mp
15
+ import numpy as np
16
+ import zarr
17
+
18
+ # One thread per worker process: zarr's default pool (os.cpu_count() threads) times 64 to 96
19
+ # forked workers thrashed a 128-core node, cutting throughput several-fold.
20
+ zarr.config.set({"threading.max_workers": 1, "async.concurrency": 2})
21
+ try:
22
+ import numcodecs.blosc
23
+ numcodecs.blosc.set_nthreads(1)
24
+ numcodecs.blosc.use_threads = False
25
+ except Exception:
26
+ pass
27
+
28
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
29
+ from omol_store import CHUNKS_PER_SHARD
30
+
31
+
32
+ def shard_paths(root):
33
+ out = []
34
+ for side in ("p1", "p2"):
35
+ for depth in ("*", "*/*/*"):
36
+ out += glob.glob(os.path.join(root, side, depth, "*.zarr"))
37
+ return sorted(set(out))
38
+
39
+
40
+ def count_files(path):
41
+ return sum(len(fs) for _, _, fs in os.walk(path))
42
+
43
+
44
+ def equal(a, b):
45
+ if a.shape != b.shape or a.dtype != b.dtype:
46
+ return False
47
+ if a.dtype.kind == "f":
48
+ return bool(np.array_equal(a, b, equal_nan=True))
49
+ return bool(np.array_equal(a, b))
50
+
51
+
52
+ def repack_group(args):
53
+ src, dst = args
54
+ t0 = time.time()
55
+ try:
56
+ if os.path.isdir(dst):
57
+ if zarr.open_group(dst, mode="r").attrs.get("repack_verified"):
58
+ return dst, "skip", 0, 0, 0.0, ""
59
+ shutil.rmtree(dst)
60
+ gs = zarr.open_group(src, mode="r")
61
+ attrs = dict(gs.attrs)
62
+ gd = zarr.open_group(dst, mode="w")
63
+ gd.attrs.update(attrs)
64
+ for name in sorted(gs.array_keys()):
65
+ zs = gs[name]
66
+ data = np.asarray(zs[...])
67
+ chunks = tuple(int(c) for c in zs.chunks)
68
+ n_chunks = max(1, -(-zs.shape[0] // chunks[0]))
69
+ shards = zs.shards or ((chunks[0] * min(CHUNKS_PER_SHARD, n_chunks),)
70
+ + tuple(zs.shape[1:]))
71
+ zd = gd.create_array(name=name, shape=zs.shape, chunks=chunks, shards=shards,
72
+ dtype=zs.dtype, compressors=zs.compressors)
73
+ if data.size:
74
+ zd[...] = data
75
+ if not equal(data, np.asarray(zd[...])):
76
+ raise RuntimeError(f"read-back mismatch in {name}")
77
+ gd = zarr.open_group(dst, mode="r+")
78
+ if dict(gd.attrs) != attrs or sorted(gd.array_keys()) != sorted(gs.array_keys()):
79
+ raise RuntimeError("attrs or array list differ after copy")
80
+ gd.attrs["repack_verified"] = True
81
+ return dst, "ok", count_files(src), count_files(dst), time.time() - t0, ""
82
+ except Exception:
83
+ return dst, "fail", 0, 0, time.time() - t0, traceback.format_exc(limit=3)
84
+
85
+
86
+ def main():
87
+ ap = argparse.ArgumentParser()
88
+ ap.add_argument("--src", required=True)
89
+ ap.add_argument("--dst", required=True)
90
+ ap.add_argument("--workers", type=int, default=64)
91
+ ap.add_argument("--limit", type=int, default=0)
92
+ ap.add_argument("--pattern", default="", help="only shards whose basename contains this")
93
+ args = ap.parse_args()
94
+ src = os.path.abspath(args.src)
95
+ dst = os.path.abspath(args.dst)
96
+ shards = shard_paths(src)
97
+ if args.pattern:
98
+ shards = [s for s in shards if args.pattern in os.path.basename(s)]
99
+ if args.limit:
100
+ shards = shards[:args.limit]
101
+ jobs = [(s, os.path.join(dst, os.path.relpath(s, src))) for s in shards]
102
+ print(f"repack {len(jobs)} shard groups: {src} -> {dst}", flush=True)
103
+ os.makedirs(dst, exist_ok=True)
104
+ for f in glob.glob(os.path.join(src, "*.tsv")):
105
+ shutil.copy2(f, dst)
106
+ t0 = time.time()
107
+ n_ok = n_skip = n_fail = 0
108
+ files_in = files_out = 0
109
+ with mp.Pool(min(args.workers, len(jobs))) as pool:
110
+ for k, (path, status, fi, fo, dt, err) in enumerate(pool.imap_unordered(repack_group, jobs), 1):
111
+ if status == "ok":
112
+ n_ok += 1
113
+ files_in += fi
114
+ files_out += fo
115
+ elif status == "skip":
116
+ n_skip += 1
117
+ else:
118
+ n_fail += 1
119
+ print(f"FAIL {path}\n{err}", flush=True)
120
+ if k % 100 == 0 or k == len(jobs):
121
+ el = time.time() - t0
122
+ print(f" {k}/{len(jobs)} ok={n_ok} skip={n_skip} fail={n_fail} "
123
+ f"files {files_in:,} -> {files_out:,} {el/60:.1f} min", flush=True)
124
+ print(f"\ndone: ok {n_ok}, skipped {n_skip}, failed {n_fail}, "
125
+ f"files {files_in:,} -> {files_out:,}, wall {(time.time()-t0)/60:.1f} min")
126
+
127
+
128
+ if __name__ == "__main__":
129
+ mp.set_start_method("fork", force=True)
130
+ main()
fullC/code/uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
fullC/code/verify_store.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify a Pass A Zarr store: structural checks on every shard, plus a full re-parse comparison
2
+ for a random sample of calculations. This is the gate before scaling to the full run.
3
+ """
4
+ from __future__ import annotations
5
+ import argparse, glob, os, random, sys
6
+ import numpy as np
7
+ import zarr
8
+
9
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
10
+ from omol_parse import parse_archive
11
+ from omol_store import (read_calc, inflate_fock, frontier, SCALARS_F8, SCALARS_I, FLAGS,
12
+ ATOM_1D, ATOM_SHELL, PAIRS)
13
+
14
+ M5250 = "/global/cfs/projectdirs/m5250/OMol_elec"
15
+
16
+
17
+ def shard_paths(root, side):
18
+ out = []
19
+ for depth in ("*", "*/*/*"):
20
+ out += glob.glob(os.path.join(root, side, depth, "*.zarr"))
21
+ return sorted(set(out))
22
+
23
+
24
+ def close(a, b, tol=0.0):
25
+ if a is None or b is None:
26
+ return a is None and b is None
27
+ a = np.asarray(a, dtype=float)
28
+ b = np.asarray(b, dtype=float)
29
+ if a.shape != b.shape:
30
+ return False
31
+ return bool(np.all((np.isnan(a) & np.isnan(b)) | (np.abs(a - b) <= tol)))
32
+
33
+
34
+ def main():
35
+ ap = argparse.ArgumentParser()
36
+ ap.add_argument("--store", required=True)
37
+ ap.add_argument("--sample", type=int, default=30)
38
+ ap.add_argument("--seed", type=int, default=7)
39
+ args = ap.parse_args()
40
+
41
+ p1 = shard_paths(args.store, "p1")
42
+ p2 = shard_paths(args.store, "p2")
43
+ print(f"shards: p1 {len(p1)}, p2 {len(p2)}")
44
+ if len(p1) != len(p2):
45
+ print(" ERROR: p1 and p2 shard counts differ")
46
+
47
+ total = 0
48
+ problems = []
49
+ nbas_all, natm_all, uhf_n, nofock = [], [], 0, 0
50
+ for sp in p2:
51
+ g = zarr.open_group(sp, mode="r")
52
+ n = int(g.attrs["n_calc"])
53
+ total += n
54
+ si = np.asarray(g["scalar_i"])
55
+ icol = {k: j for j, k in enumerate(g.attrs["scalar_i_cols"])}
56
+ nbas = si[:, icol["nbas"]]
57
+ natm = si[:, icol["n_atoms"]]
58
+ nbas_all.append(nbas)
59
+ natm_all.append(natm)
60
+ for nm, key in (("atom", "atom_offsets"), ("fock_a", "fock_a_offsets"),
61
+ ("fock_b", "fock_b_offsets"), ("eps_a", "eps_a_offsets")):
62
+ o = np.asarray(g[key])
63
+ if len(o) != n + 1 or o[0] != 0 or np.any(np.diff(o) < 0):
64
+ problems.append(f"{os.path.basename(sp)}: bad {nm} offsets")
65
+ if not np.array_equal(np.diff(np.asarray(g["atom_offsets"])), natm):
66
+ problems.append(f"{os.path.basename(sp)}: atom offsets != n_atoms")
67
+ want = nbas.astype("i8") * (nbas.astype("i8") + 1) // 2
68
+ flags = np.asarray(g["flags"])
69
+ fcol = {k: j for j, k in enumerate(g.attrs["flag_cols"])}
70
+ is_uhf = flags[:, fcol["is_uhf"]].astype(bool)
71
+ has_f = flags[:, fcol["has_fock"]].astype(bool)
72
+ uhf_n += int(is_uhf.sum())
73
+ nofock += int((~has_f).sum())
74
+ fa = np.diff(np.asarray(g["fock_a_offsets"]))
75
+ if not np.array_equal(fa[has_f], want[has_f]):
76
+ problems.append(f"{os.path.basename(sp)}: fock_a length != nbas(nbas+1)/2")
77
+ if np.any(fa[~has_f] != 0):
78
+ problems.append(f"{os.path.basename(sp)}: fock_a stored where has_fock is false")
79
+ fb = np.diff(np.asarray(g["fock_b_offsets"]))
80
+ if np.any((fb > 0) != (is_uhf & has_f)):
81
+ problems.append(f"{os.path.basename(sp)}: beta Fock presence != is_uhf & has_fock")
82
+ if not np.array_equal(fb[is_uhf & has_f], want[is_uhf & has_f]):
83
+ problems.append(f"{os.path.basename(sp)}: beta Fock length wrong")
84
+ if len(g.attrs["calc_id"]) != n or len(g.attrs["rel_path"]) != n:
85
+ problems.append(f"{os.path.basename(sp)}: attrs length != n_calc")
86
+ if np.any(~np.asarray(g["flags"])[:, fcol["terminated_normally"]].astype(bool)):
87
+ problems.append(f"{os.path.basename(sp)}: some runs not terminated normally")
88
+ nbas_all = np.concatenate(nbas_all) if nbas_all else np.zeros(0)
89
+ natm_all = np.concatenate(natm_all) if natm_all else np.zeros(0)
90
+ print(f"calculations: {total:,} ({uhf_n:,} UHF, {total-uhf_n:,} RHF, "
91
+ f"{nofock:,} without a Fock matrix)")
92
+ if total:
93
+ print(f" nbas min {nbas_all.min()} median {int(np.median(nbas_all))} max {nbas_all.max()}")
94
+ print(f" atoms min {natm_all.min()} median {int(np.median(natm_all))} max {natm_all.max()}")
95
+ for p in problems[:12]:
96
+ print(" STRUCT ERROR:", p)
97
+ if not problems:
98
+ print(" structural checks passed on every shard")
99
+
100
+ rng = random.Random(args.seed)
101
+ picks = []
102
+ for sp in p2:
103
+ g = zarr.open_group(sp, mode="r")
104
+ n = int(g.attrs["n_calc"])
105
+ if n:
106
+ picks.append((sp, rng.randrange(n)))
107
+ rng.shuffle(picks)
108
+ picks = picks[:args.sample]
109
+ print(f"\nre-parse comparison on {len(picks)} calculations:")
110
+
111
+ nbad = 0
112
+ for sp, i in picks:
113
+ g = zarr.open_group(sp, mode="r")
114
+ stored = read_calc(g, i)
115
+ rel = stored["rel_path"]
116
+ fresh = parse_archive(os.path.join(M5250, rel, "orca.tar.zst"))
117
+ fresh["n_atoms"] = len(fresh["elements"])
118
+ fresh["homo_a"], fresh["lumo_a"], fresh["gap_a"] = frontier(fresh["eps_a"], fresh["occ_a"])
119
+ fresh["homo_b"], fresh["lumo_b"], fresh["gap_b"] = frontier(fresh["eps_b"], fresh["occ_b"])
120
+ bad = []
121
+ for k in SCALARS_F8:
122
+ a, b = stored[k], fresh.get(k)
123
+ if b is None:
124
+ continue
125
+ if not close(a, b, tol=abs(float(b)) * 1e-12 + 1e-12):
126
+ bad.append(f"{k}: {a} vs {b}")
127
+ for k in SCALARS_I:
128
+ b = fresh.get(k)
129
+ if b is not None and stored[k] != int(b):
130
+ bad.append(f"{k}: {stored[k]} vs {b}")
131
+ for k in ("scf_converged", "terminated_normally", "nbo_available", "npa_available"):
132
+ if stored[k] != bool(fresh.get(k)):
133
+ bad.append(f"{k}: {stored[k]} vs {fresh.get(k)}")
134
+ if stored["is_uhf"] != (fresh["hftyp"] == "UHF"):
135
+ bad.append("is_uhf mismatch")
136
+ if not close(stored["coords"], fresh["coords"], 1e-9):
137
+ bad.append("coords differ")
138
+ if fresh["forces"] is not None and not close(stored["forces"], fresh["forces"], 1e-12):
139
+ bad.append("forces differ")
140
+ if fresh["atomic_numbers"] is not None and not np.array_equal(
141
+ stored["atomic_numbers"], fresh["atomic_numbers"]):
142
+ bad.append("atomic numbers differ")
143
+ for k in ATOM_1D:
144
+ if fresh.get(k) is not None and not close(stored[k], fresh[k], 1e-9):
145
+ bad.append(f"{k} differs")
146
+ for k in ATOM_SHELL:
147
+ if fresh.get(k) is not None and not close(stored[k], fresh[k], 2e-5):
148
+ bad.append(f"{k} differs")
149
+ for k in PAIRS:
150
+ idx, val = stored[k]
151
+ ref = fresh.get(k) or []
152
+ if len(val) != len(ref):
153
+ bad.append(f"{k} count {len(val)} vs {len(ref)}")
154
+ elif ref:
155
+ if (not np.array_equal(idx, np.array([[a, b] for a, b, _ in ref]))
156
+ or not close(val, np.array([v for _, _, v in ref]), 1e-4)):
157
+ bad.append(f"{k} content differs")
158
+ if fresh["fock_a"] is None:
159
+ if stored["has_fock"] or len(stored["fock_a"]):
160
+ bad.append("fock_a stored but source has none")
161
+ elif not np.array_equal(stored["fock_a"], fresh["fock_a"]):
162
+ bad.append("fock_a differs")
163
+ fb = fresh.get("fock_b")
164
+ if fb is None:
165
+ if len(stored["fock_b"]):
166
+ bad.append("fock_b present but should be absent")
167
+ elif not np.array_equal(stored["fock_b"], fb):
168
+ bad.append("fock_b differs")
169
+ if not close(stored["eps_a"], fresh["eps_a"], 1e-12):
170
+ bad.append("eps_a differs")
171
+ if stored["has_fock"]:
172
+ F = inflate_fock(stored["fock_a"], stored["nbas"])
173
+ if np.abs(F - F.T).max() != 0:
174
+ bad.append("inflated Fock not symmetric")
175
+ if bad:
176
+ nbad += 1
177
+ print(f" MISMATCH {rel}")
178
+ for b in bad[:6]:
179
+ print(f" {b}")
180
+ else:
181
+ print(f" ok {rel[:76]}")
182
+ print(f"\n{len(picks)-nbad}/{len(picks)} exact, {len(problems)} structural problems")
183
+
184
+ def du(p):
185
+ return sum(os.path.getsize(os.path.join(r, f)) for r, _, fs in os.walk(p) for f in fs)
186
+ b1 = sum(du(p) for p in p1)
187
+ b2 = sum(du(p) for p in p2)
188
+ print(f"\nsize: p1 {b1/1e9:.3f} GB ({b1/max(total,1)/1e3:.1f} kB/calc), "
189
+ f"p2 {b2/1e9:.3f} GB ({b2/max(total,1)/1e6:.3f} MB/calc)")
190
+ if total:
191
+ print(f"extrapolated to 3.73 M: p1 {b1/total*3.73e6/1e12:.2f} TB, "
192
+ f"p2 {b2/total*3.73e6/1e12:.2f} TB")
193
+
194
+
195
+ if __name__ == "__main__":
196
+ main()
fullC/failures_task3.tsv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ rel_path error detail
2
+ pdb_fragments_400K/4d42_EBS02_state0_0_1_ZINC000004179832_ligstate0_-1_1 ReadError empty file
fullC/p2/ml_elytes/group_000.zarr/atom_shell/zarr.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 80773,
4
+ 25
5
+ ],
6
+ "data_type": "float32",
7
+ "chunk_grid": {
8
+ "name": "regular",
9
+ "configuration": {
10
+ "chunk_shape": [
11
+ 81880,
12
+ 25
13
+ ]
14
+ }
15
+ },
16
+ "chunk_key_encoding": {
17
+ "name": "default",
18
+ "configuration": {
19
+ "separator": "/"
20
+ }
21
+ },
22
+ "fill_value": 0.0,
23
+ "codecs": [
24
+ {
25
+ "name": "sharding_indexed",
26
+ "configuration": {
27
+ "chunk_shape": [
28
+ 8188,
29
+ 25
30
+ ],
31
+ "codecs": [
32
+ {
33
+ "name": "bytes",
34
+ "configuration": {
35
+ "endian": "little"
36
+ }
37
+ },
38
+ {
39
+ "name": "blosc",
40
+ "configuration": {
41
+ "typesize": 4,
42
+ "cname": "zstd",
43
+ "clevel": 5,
44
+ "shuffle": "shuffle",
45
+ "blocksize": 0
46
+ }
47
+ }
48
+ ],
49
+ "index_codecs": [
50
+ {
51
+ "name": "bytes",
52
+ "configuration": {
53
+ "endian": "little"
54
+ }
55
+ },
56
+ {
57
+ "name": "crc32c"
58
+ }
59
+ ],
60
+ "index_location": "end"
61
+ }
62
+ }
63
+ ],
64
+ "attributes": {},
65
+ "zarr_format": 3,
66
+ "node_type": "array",
67
+ "storage_transformers": []
68
+ }
fullC/p2/ml_elytes/group_000.zarr/atom_z/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 80773
4
+ ],
5
+ "data_type": "int16",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 81880
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 8188
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 2,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/cmo_a_offsets/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 563
4
+ ],
5
+ "data_type": "int64",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 563
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 563
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 8,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/cmo_b/zarr.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 304516765
4
+ ],
5
+ "data_type": "float32",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 268435456
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0.0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 4194304
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ }
35
+ ],
36
+ "index_codecs": [
37
+ {
38
+ "name": "bytes",
39
+ "configuration": {
40
+ "endian": "little"
41
+ }
42
+ },
43
+ {
44
+ "name": "crc32c"
45
+ }
46
+ ],
47
+ "index_location": "end"
48
+ }
49
+ }
50
+ ],
51
+ "attributes": {},
52
+ "zarr_format": 3,
53
+ "node_type": "array",
54
+ "storage_transformers": []
55
+ }
fullC/p2/ml_elytes/group_000.zarr/eps_b_offsets/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 563
4
+ ],
5
+ "data_type": "int64",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 563
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 563
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 8,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/fock_a_offsets/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 563
4
+ ],
5
+ "data_type": "int64",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 563
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 563
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 8,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/gbw_eps_a/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 1750480
4
+ ],
5
+ "data_type": "float64",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 1809760
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0.0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 180976
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 8,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/gbw_eps_b/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 94663
4
+ ],
5
+ "data_type": "float64",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 95705
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0.0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 19141
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 8,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/gbw_occ_a/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 1750480
4
+ ],
5
+ "data_type": "float64",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 1809760
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0.0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 180976
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 8,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/gbw_occ_b/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 94663
4
+ ],
5
+ "data_type": "float64",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 95705
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0.0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 19141
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 8,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/mo_f8/zarr.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 562,
4
+ 10
5
+ ],
6
+ "data_type": "float64",
7
+ "chunk_grid": {
8
+ "name": "regular",
9
+ "configuration": {
10
+ "chunk_shape": [
11
+ 600,
12
+ 10
13
+ ]
14
+ }
15
+ },
16
+ "chunk_key_encoding": {
17
+ "name": "default",
18
+ "configuration": {
19
+ "separator": "/"
20
+ }
21
+ },
22
+ "fill_value": 0.0,
23
+ "codecs": [
24
+ {
25
+ "name": "sharding_indexed",
26
+ "configuration": {
27
+ "chunk_shape": [
28
+ 60,
29
+ 10
30
+ ],
31
+ "codecs": [
32
+ {
33
+ "name": "bytes",
34
+ "configuration": {
35
+ "endian": "little"
36
+ }
37
+ },
38
+ {
39
+ "name": "blosc",
40
+ "configuration": {
41
+ "typesize": 8,
42
+ "cname": "zstd",
43
+ "clevel": 5,
44
+ "shuffle": "shuffle",
45
+ "blocksize": 0
46
+ }
47
+ }
48
+ ],
49
+ "index_codecs": [
50
+ {
51
+ "name": "bytes",
52
+ "configuration": {
53
+ "endian": "little"
54
+ }
55
+ },
56
+ {
57
+ "name": "crc32c"
58
+ }
59
+ ],
60
+ "index_location": "end"
61
+ }
62
+ }
63
+ ],
64
+ "attributes": {},
65
+ "zarr_format": 3,
66
+ "node_type": "array",
67
+ "storage_transformers": []
68
+ }
fullC/p2/ml_elytes/group_000.zarr/occ_a/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 1750480
4
+ ],
5
+ "data_type": "float64",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 1809760
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0.0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 180976
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 8,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/pair_loewdin_bo_value/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 238967
4
+ ],
5
+ "data_type": "float32",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 245930
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0.0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 24593
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 4,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/pair_mayer_bo_value/zarr.json ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 159446
4
+ ],
5
+ "data_type": "float32",
6
+ "chunk_grid": {
7
+ "name": "regular",
8
+ "configuration": {
9
+ "chunk_shape": [
10
+ 164350
11
+ ]
12
+ }
13
+ },
14
+ "chunk_key_encoding": {
15
+ "name": "default",
16
+ "configuration": {
17
+ "separator": "/"
18
+ }
19
+ },
20
+ "fill_value": 0.0,
21
+ "codecs": [
22
+ {
23
+ "name": "sharding_indexed",
24
+ "configuration": {
25
+ "chunk_shape": [
26
+ 16435
27
+ ],
28
+ "codecs": [
29
+ {
30
+ "name": "bytes",
31
+ "configuration": {
32
+ "endian": "little"
33
+ }
34
+ },
35
+ {
36
+ "name": "blosc",
37
+ "configuration": {
38
+ "typesize": 4,
39
+ "cname": "zstd",
40
+ "clevel": 5,
41
+ "shuffle": "shuffle",
42
+ "blocksize": 0
43
+ }
44
+ }
45
+ ],
46
+ "index_codecs": [
47
+ {
48
+ "name": "bytes",
49
+ "configuration": {
50
+ "endian": "little"
51
+ }
52
+ },
53
+ {
54
+ "name": "crc32c"
55
+ }
56
+ ],
57
+ "index_location": "end"
58
+ }
59
+ }
60
+ ],
61
+ "attributes": {},
62
+ "zarr_format": 3,
63
+ "node_type": "array",
64
+ "storage_transformers": []
65
+ }
fullC/p2/ml_elytes/group_000.zarr/pair_mulliken_ovlp_index/zarr.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 534826,
4
+ 2
5
+ ],
6
+ "data_type": "int32",
7
+ "chunk_grid": {
8
+ "name": "regular",
9
+ "configuration": {
10
+ "chunk_shape": [
11
+ 557680,
12
+ 2
13
+ ]
14
+ }
15
+ },
16
+ "chunk_key_encoding": {
17
+ "name": "default",
18
+ "configuration": {
19
+ "separator": "/"
20
+ }
21
+ },
22
+ "fill_value": 0,
23
+ "codecs": [
24
+ {
25
+ "name": "sharding_indexed",
26
+ "configuration": {
27
+ "chunk_shape": [
28
+ 55768,
29
+ 2
30
+ ],
31
+ "codecs": [
32
+ {
33
+ "name": "bytes",
34
+ "configuration": {
35
+ "endian": "little"
36
+ }
37
+ },
38
+ {
39
+ "name": "blosc",
40
+ "configuration": {
41
+ "typesize": 4,
42
+ "cname": "zstd",
43
+ "clevel": 5,
44
+ "shuffle": "shuffle",
45
+ "blocksize": 0
46
+ }
47
+ }
48
+ ],
49
+ "index_codecs": [
50
+ {
51
+ "name": "bytes",
52
+ "configuration": {
53
+ "endian": "little"
54
+ }
55
+ },
56
+ {
57
+ "name": "crc32c"
58
+ }
59
+ ],
60
+ "index_location": "end"
61
+ }
62
+ }
63
+ ],
64
+ "attributes": {},
65
+ "zarr_format": 3,
66
+ "node_type": "array",
67
+ "storage_transformers": []
68
+ }
fullC/p2/ml_elytes/group_000.zarr/scalar_f8/zarr.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "shape": [
3
+ 562,
4
+ 38
5
+ ],
6
+ "data_type": "float64",
7
+ "chunk_grid": {
8
+ "name": "regular",
9
+ "configuration": {
10
+ "chunk_shape": [
11
+ 600,
12
+ 38
13
+ ]
14
+ }
15
+ },
16
+ "chunk_key_encoding": {
17
+ "name": "default",
18
+ "configuration": {
19
+ "separator": "/"
20
+ }
21
+ },
22
+ "fill_value": 0.0,
23
+ "codecs": [
24
+ {
25
+ "name": "sharding_indexed",
26
+ "configuration": {
27
+ "chunk_shape": [
28
+ 60,
29
+ 38
30
+ ],
31
+ "codecs": [
32
+ {
33
+ "name": "bytes",
34
+ "configuration": {
35
+ "endian": "little"
36
+ }
37
+ },
38
+ {
39
+ "name": "blosc",
40
+ "configuration": {
41
+ "typesize": 8,
42
+ "cname": "zstd",
43
+ "clevel": 5,
44
+ "shuffle": "shuffle",
45
+ "blocksize": 0
46
+ }
47
+ }
48
+ ],
49
+ "index_codecs": [
50
+ {
51
+ "name": "bytes",
52
+ "configuration": {
53
+ "endian": "little"
54
+ }
55
+ },
56
+ {
57
+ "name": "crc32c"
58
+ }
59
+ ],
60
+ "index_location": "end"
61
+ }
62
+ }
63
+ ],
64
+ "attributes": {},
65
+ "zarr_format": 3,
66
+ "node_type": "array",
67
+ "storage_transformers": []
68
+ }
fullC/p2/ml_elytes/group_000.zarr/zarr.json ADDED
The diff for this file is too large to render. See raw diff
 
fullC/p2/ml_elytes/group_001.zarr/zarr.json ADDED
The diff for this file is too large to render. See raw diff
 
fullC/p2/ml_elytes/group_002.zarr/zarr.json ADDED
The diff for this file is too large to render. See raw diff
 
fullC/subset_100k.txt ADDED
The diff for this file is too large to render. See raw diff
 
fullC/subset_100k_counts.tsv ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset population sampled pct_of_dataset
2
+ ani1xbb 737210 18494 2.509
3
+ omol/metal_organics/restart5to6 364470 9309 2.554
4
+ omol/solvated_protein/outputs_240923 335669 8373 2.494
5
+ omol/electrolytes/solvated_090624 302916 7609 2.512
6
+ ani2x 215642 5480 2.541
7
+ trans1x 213731 5309 2.484
8
+ geom_orca6 199805 5055 2.530
9
+ omol/electrolytes/md_based 165660 4183 2.525
10
+ tm_react 158190 3910 2.472
11
+ omol/metal_organics/outputs_low_spin_241118 97884 2570 2.626
12
+ pdb_fragments_300K 93334 2369 2.538
13
+ pdb_fragments_400K 92698 2209 2.383
14
+ ml_mo 77603 1955 2.519
15
+ rgd_uks 75316 1902 2.525
16
+ electrolytes_reactivity 66974 1651 2.465
17
+ ml_protein_interface 61859 1473 2.381
18
+ omol/metal_organics/outputs_072324 60890 1531 2.514
19
+ scaled_separations_exp 53219 1326 2.492
20
+ ml_elytes 51599 1320 2.558
21
+ orbnet_denali 51102 1275 2.495
22
+ pmechdb 49832 1228 2.464
23
+ omol/solvated_protein/outputs_241002 46667 1188 2.546
24
+ electrolytes_redox 46081 1183 2.567
25
+ protein_interface 44972 1140 2.535
26
+ spice 44450 1143 2.571
27
+ protein_core 35406 874 2.469
28
+ rna 34745 841 2.420
29
+ electrolytes_scaled_sep 30769 782 2.542
30
+ omol/electrolytes/outputs_unsolvated_120424 29054 722 2.485
31
+ dna 24647 585 2.374
32
+ droplet 18694 433 2.316
33
+ rpmd 18652 449 2.407
34
+ pdb_pockets_300K 16927 459 2.712
35
+ 5A_elytes 14202 353 2.486
36
+ omol/metal_organics/outputs_ln_082524 14195 360 2.536
37
+ low_spin_23 12939 282 2.179
38
+ omol/redo_orca6/metal_organics 7555 161 2.131
39
+ nakb 5606 137 2.444
40
+ omol/torsion_profiles/outputs_120324 4248 98 2.307
41
+ mo_hydrides 3396 93 2.739
42
+ pdb_pockets_400K 3210 64 1.994
43
+ rmechdb 2803 70 2.497
44
+ noble_gas 1915 52 2.715
45
+ noble_gas_compounds 18 0 0.000
fullC/subset_100k_missing.txt ADDED
File without changes
occC/b1_failures.tsv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ shard calc_id reason
2
+ p2/ani1xbb/shard_t03_0005_00.zarr ani1xbb__aniBB_022_377503_0_3 failed: fock_match
occC/b1_summary.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "totals": {
3
+ "n": 99999,
4
+ "found": 99999,
5
+ "ok": 99998,
6
+ "fock_checked": 99954,
7
+ "bytes_cmo": 1521762062968,
8
+ "fail_gbw_found": 0,
9
+ "fail_nbas_match": 0,
10
+ "fail_nspin_match": 0,
11
+ "fail_nelec_match": 0,
12
+ "fail_spin_match": 0,
13
+ "fail_eps_checked": 0,
14
+ "fail_eps_match": 0,
15
+ "fail_occ_contiguous": 0,
16
+ "fail_fock_checked": 45,
17
+ "fail_fock_match": 1,
18
+ "fail_mo_ok": 1
19
+ },
20
+ "dtype": "f4",
21
+ "eps_err_max": 4.999999996257998e-07,
22
+ "fc_offdiag_max": 0.002244156607543126,
23
+ "wall_s": 1131.7759289741516,
24
+ "shard_failures": []
25
+ }
occC/basis_def2-TZVPD_orca6.json ADDED
The diff for this file is too large to render. See raw diff
 
occC/failures_task3.tsv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ rel_path error detail
2
+ pdb_fragments_400K/4d42_EBS02_state0_0_1_ZINC000004179832_ligstate0_-1_1 ReadError empty file
occC/subset_100k.txt ADDED
The diff for this file is too large to render. See raw diff
 
occC/subset_100k_counts.tsv ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset population sampled pct_of_dataset
2
+ ani1xbb 737210 18494 2.509
3
+ omol/metal_organics/restart5to6 364470 9309 2.554
4
+ omol/solvated_protein/outputs_240923 335669 8373 2.494
5
+ omol/electrolytes/solvated_090624 302916 7609 2.512
6
+ ani2x 215642 5480 2.541
7
+ trans1x 213731 5309 2.484
8
+ geom_orca6 199805 5055 2.530
9
+ omol/electrolytes/md_based 165660 4183 2.525
10
+ tm_react 158190 3910 2.472
11
+ omol/metal_organics/outputs_low_spin_241118 97884 2570 2.626
12
+ pdb_fragments_300K 93334 2369 2.538
13
+ pdb_fragments_400K 92698 2209 2.383
14
+ ml_mo 77603 1955 2.519
15
+ rgd_uks 75316 1902 2.525
16
+ electrolytes_reactivity 66974 1651 2.465
17
+ ml_protein_interface 61859 1473 2.381
18
+ omol/metal_organics/outputs_072324 60890 1531 2.514
19
+ scaled_separations_exp 53219 1326 2.492
20
+ ml_elytes 51599 1320 2.558
21
+ orbnet_denali 51102 1275 2.495
22
+ pmechdb 49832 1228 2.464
23
+ omol/solvated_protein/outputs_241002 46667 1188 2.546
24
+ electrolytes_redox 46081 1183 2.567
25
+ protein_interface 44972 1140 2.535
26
+ spice 44450 1143 2.571
27
+ protein_core 35406 874 2.469
28
+ rna 34745 841 2.420
29
+ electrolytes_scaled_sep 30769 782 2.542
30
+ omol/electrolytes/outputs_unsolvated_120424 29054 722 2.485
31
+ dna 24647 585 2.374
32
+ droplet 18694 433 2.316
33
+ rpmd 18652 449 2.407
34
+ pdb_pockets_300K 16927 459 2.712
35
+ 5A_elytes 14202 353 2.486
36
+ omol/metal_organics/outputs_ln_082524 14195 360 2.536
37
+ low_spin_23 12939 282 2.179
38
+ omol/redo_orca6/metal_organics 7555 161 2.131
39
+ nakb 5606 137 2.444
40
+ omol/torsion_profiles/outputs_120324 4248 98 2.307
41
+ mo_hydrides 3396 93 2.739
42
+ pdb_pockets_400K 3210 64 1.994
43
+ rmechdb 2803 70 2.497
44
+ noble_gas 1915 52 2.715
45
+ noble_gas_compounds 18 0 0.000
occC/subset_100k_missing.txt ADDED
File without changes