Download fullC/code/derive_occ_store.py from ericqu/OME: direct link, hf CLI and curl.
- Browser
- Download file 6.79 kB
-
https://huggingface.co/datasets/ericqu/OME/resolve/main/fullC/code/derive_occ_store.py
- Command line
-
hf download hf://datasets/ericqu/OME/fullC/code/derive_occ_store.py
-
curl -L -o derive_occ_store.py https://huggingface.co/datasets/ericqu/OME/resolve/main/fullC/code/derive_occ_store.py
6.79 kB
| """Derive the occupied-only variant of a full-C store. | |
| For every p2 shard the group directory is copied file for file (no decode or re-encode of the | |
| Fock and table arrays), except the `cmo_*` arrays, which are rewritten with only the occupied | |
| rows of each calculation's C^T block. Both variants share one schema: `mo_content` in the group | |
| attributes is "full" or "occupied", and `cmo_x[o[i]:o[i+1]].reshape(-1, nbas)` is C^T restricted to | |
| the stored orbitals either way. p1 and the root files are copied as they are. | |
| python derive_occ_store.py --src $PSCRATCH/omol_100k --dst $PSCRATCH/omol_100k_occ --workers 64 | |
| """ | |
| from __future__ import annotations | |
| import argparse, glob, os, shutil, sys, time, traceback | |
| import multiprocessing as mp | |
| import numpy as np | |
| import zarr | |
| zarr.config.set({"threading.max_workers": 1, "async.concurrency": 2}) | |
| try: | |
| import numcodecs.blosc | |
| numcodecs.blosc.set_nthreads(1) | |
| numcodecs.blosc.use_threads = False | |
| except Exception: | |
| pass | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from omol_store import put_array | |
| CMO_CHUNK = 1 << 22 | |
| def p2_shards(store): | |
| out = [] | |
| for depth in ("*", "*/*/*"): | |
| out += glob.glob(os.path.join(store, "p2", depth, "*.zarr")) | |
| return sorted(set(out)) | |
| def derive(args): | |
| src, dst = args | |
| t0 = time.time() | |
| try: | |
| if os.path.isdir(dst): | |
| if zarr.open_group(dst, mode="r").attrs.get("occ_derived_verified"): | |
| return dst, "skip", 0, 0.0, "" | |
| shutil.rmtree(dst) | |
| gs = zarr.open_group(src, mode="r") | |
| if gs.attrs.get("mo_content", "full") != "full": | |
| raise RuntimeError("source is not a full-C store") | |
| skip = {n for n in gs.array_keys() if n.startswith("cmo_")} | |
| shutil.copytree(src, dst, ignore=lambda d, names: [n for n in names if d == src and n in skip]) | |
| # the copied root zarr.json may carry consolidated metadata that still lists the excluded | |
| # arrays; drop it and re-consolidate once the new arrays are in place | |
| import json | |
| meta_path = os.path.join(dst, "zarr.json") | |
| meta = json.load(open(meta_path)) | |
| if "consolidated_metadata" in meta: | |
| meta["consolidated_metadata"] = None | |
| json.dump(meta, open(meta_path, "w")) | |
| gd = zarr.open_group(dst, mode="r+", use_consolidated=False) | |
| n = int(gs.attrs["n_calc"]) | |
| nbas = np.asarray(gs["scalar_i"])[:, list(gs.attrs["scalar_i_cols"]).index("nbas")].astype("i8") | |
| mi = np.asarray(gs["mo_i"]) | |
| nocc = {s: mi[:, list(gs.attrs["mo_i_cols"]).index(f"nocc_{s}")].astype("i8") for s in "ab"} | |
| written = 0 | |
| for s in "ab": | |
| zsrc = gs[f"cmo_{s}"] | |
| off_src = np.asarray(gs[f"cmo_{s}_offsets"]) | |
| lens = np.where(np.diff(off_src) > 0, nocc[s] * nbas, 0) | |
| offs = np.zeros(n + 1, dtype="i8") | |
| offs[1:] = np.cumsum(lens) | |
| buf = np.empty(int(offs[-1]), dtype=zsrc.dtype) | |
| for i in range(n): | |
| if lens[i]: | |
| a = int(off_src[i]) | |
| buf[offs[i]:offs[i + 1]] = zsrc[a:a + int(lens[i])] | |
| put_array(gd, f"cmo_{s}", buf, codec=None, | |
| chunks=(max(1, min(len(buf), CMO_CHUNK)),), overwrite=True) | |
| put_array(gd, f"cmo_{s}_offsets", offs, overwrite=True) | |
| # verify: every stored block equals the source prefix | |
| back = np.asarray(gd[f"cmo_{s}"][...]) | |
| if not np.array_equal(back, buf): | |
| raise RuntimeError(f"read-back mismatch cmo_{s}") | |
| written += buf.nbytes | |
| # verify the copied arrays too (cheap ones fully, Fock by a spot check of the first calc) | |
| for name in gs.array_keys(): | |
| if name in skip: | |
| continue | |
| if name.startswith("fock_") and not name.endswith("_offsets"): | |
| k = min(int(gs[name].shape[0]), 200_000) | |
| if not np.array_equal(np.asarray(gs[name][:k]), np.asarray(gd[name][:k])): | |
| raise RuntimeError(f"copy mismatch {name}") | |
| else: | |
| a, b = np.asarray(gs[name][...]), np.asarray(gd[name][...]) | |
| ok = np.array_equal(a, b, equal_nan=True) if a.dtype.kind == "f" else np.array_equal(a, b) | |
| if not ok: | |
| raise RuntimeError(f"copy mismatch {name}") | |
| gd.attrs.update({ | |
| "mo_content": "occupied", | |
| "mo_layout": "cmo_x[o[i]:o[i+1]].reshape(nocc_x, nbas) = C_occ^T (row k = occupied MO k " | |
| "over AOs, ORCA AO order); derived from the full-C store", | |
| "occ_derived_verified": True, | |
| }) | |
| if gs.metadata.consolidated_metadata is not None: | |
| zarr.consolidate_metadata(gd.store) | |
| return dst, "ok", written, time.time() - t0, "" | |
| except Exception: | |
| return dst, "fail", 0, time.time() - t0, traceback.format_exc(limit=4) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--src", required=True) | |
| ap.add_argument("--dst", required=True) | |
| ap.add_argument("--workers", type=int, default=64) | |
| args = ap.parse_args() | |
| src, dst = os.path.abspath(args.src), os.path.abspath(args.dst) | |
| os.makedirs(dst, exist_ok=True) | |
| # p1 and root files verbatim | |
| if not os.path.isdir(os.path.join(dst, "p1")): | |
| shutil.copytree(os.path.join(src, "p1"), os.path.join(dst, "p1")) | |
| for name in os.listdir(src): | |
| p = os.path.join(src, name) | |
| if os.path.isfile(p): | |
| shutil.copy2(p, dst) | |
| elif name == "code": | |
| shutil.copytree(p, os.path.join(dst, "code"), dirs_exist_ok=True) | |
| shards = p2_shards(src) | |
| jobs = [(s, os.path.join(dst, os.path.relpath(s, src))) for s in shards] | |
| print(f"derive occupied-only store: {len(jobs)} p2 shards {src} -> {dst}", flush=True) | |
| t0 = time.time() | |
| n_ok = n_skip = n_fail = 0 | |
| written = 0 | |
| with mp.Pool(min(args.workers, len(jobs))) as pool: | |
| for k, (path, status, w, dt, err) in enumerate(pool.imap_unordered(derive, jobs), 1): | |
| if status == "ok": | |
| n_ok += 1; written += w | |
| elif status == "skip": | |
| n_skip += 1 | |
| else: | |
| n_fail += 1 | |
| print(f"FAIL {path}\n{err}", flush=True) | |
| if k % 100 == 0 or k == len(jobs): | |
| print(f" {k}/{len(jobs)} ok={n_ok} skip={n_skip} fail={n_fail} " | |
| f"cocc {written/1e9:.1f} GB {(time.time()-t0)/60:.1f} min", flush=True) | |
| print(f"\ndone: ok {n_ok}, skipped {n_skip}, failed {n_fail}, occupied C {written/1e9:.1f} GB, " | |
| f"wall {(time.time()-t0)/60:.1f} min") | |
| if __name__ == "__main__": | |
| mp.set_start_method("fork", force=True) | |
| main() | |