OME / fullC /code /export_basis.py
ericqu's picture
Add files using upload-large-folder tool
39ea985 verified
Raw
History Blame Contribute Delete
8.91 kB
"""Per-element basis set, ECP and effective nuclear charge, exported from the gbw with orca_2json.
Why from the gbw and not a library: the orbital basis is def2-TZVPD as ORCA 6 stores it, and
neither pyscf nor Basis Set Exchange carry the lanthanide entries. The export is exact for every
element and it is what makes S and H reconstructible from geometry alone.
Shell order: orca_2json lists an atom's shells in the order ORCA uses for its AO basis (verified on
XeCl4 against the exported orbital labels: def2-TZVP shells grouped by l, then the TZVPD
augmentation shells), so the per-element shell list here IS the AO layout of that element in
every matrix of the store. Spherical functions; m order p=(z,x,y), d=(z2,xz,yz,x2-y2,xy),
f=(0,+1,-1,+2,-2,+3,-3).
ECP-leak bug in orca_2json 6.0.0: an atom's ECP block is repeated onto the following atoms, so a
block is trusted only if ElementNumber - NuclearCharge > 0 and the block's N_core equals that
difference, and each ECP element is taken preferably from a molecule where it is the first
ECP-bearing atom. Blocks are cross-checked between two source molecules whenever possible.
python export_basis.py --store $PSCRATCH/omol_100k --gbw-root $PSCRATCH/gbw_100k \
--out $PSCRATCH/omol_100k/basis_def2-TZVPD_orca6.json
"""
from __future__ import annotations
import argparse, glob, json, os, shutil, struct, subprocess, sys, tempfile
import numpy as np
import zarr
import zstandard as zstd
ORCA = "/global/common/software/m5293/orca_6_0_0"
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 "
"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 "
"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()
ECP_Z_MIN = 37 # def2 ECPs start at Rb
def p1_shards(store):
out = []
for depth in ("*", "*/*/*"):
out += glob.glob(os.path.join(store, "p1", depth, "*.zarr"))
return sorted(set(out))
def candidates(store, gbw_root, per_element=3):
"""For each element, the smallest calculations containing it whose gbw is staged.
For ECP elements prefer calculations where the element is the first ECP-bearing atom."""
best = {} # Z -> list of (rank, nbas, dataset, calc_id)
for sp in p1_shards(store):
g = zarr.open_group(sp, mode="r")
ds = g.attrs["dataset"]
ids = g.attrs["calc_id"]
nbas = np.asarray(g["scalar_i"])[:, list(g.attrs["scalar_i_cols"]).index("nbas")]
off = np.asarray(g["atom_offsets"])
az = np.asarray(g["atom_z"])
for i in range(len(ids)):
zs = az[off[i]:off[i + 1]]
heavy = zs >= ECP_Z_MIN
first_heavy = int(zs[heavy][0]) if heavy.any() else None
for Z in np.unique(zs):
Z = int(Z)
rank = 0 if (Z < ECP_Z_MIN or first_heavy == Z) else 1
best.setdefault(Z, []).append((rank, int(nbas[i]), ds, ids[i]))
out = {}
for Z, lst in best.items():
lst.sort()
picked = []
for rank, nb, ds, cid in lst:
path = os.path.join(gbw_root, ds, cid + ".gbw.zstd0")
if os.path.exists(path):
picked.append((ds, cid, nb, rank, path))
if len(picked) >= per_element:
break
out[Z] = picked
return out
def gbw_base_path(raw):
return raw[40:40 + 512].split(b"\x00", 1)[0].decode()
def run_orca_2json(gbw_zstd, workdir):
raw = zstd.ZstdDecompressor().decompressobj().decompress(open(gbw_zstd, "rb").read())
base = gbw_base_path(raw)
if base:
os.makedirs(os.path.dirname(base) or ".", exist_ok=True)
name = os.path.join(workdir, "x")
with open(name + ".gbw", "wb") as fh:
fh.write(raw)
with open(name + ".json.conf", "w") as fh:
json.dump({"Basisset": True}, fh)
env = dict(os.environ, LD_LIBRARY_PATH=ORCA + ":" + os.environ.get("LD_LIBRARY_PATH", ""))
r = subprocess.run([os.path.join(ORCA, "orca_2json"), name + ".gbw", "-json"],
capture_output=True, text=True, env=env, cwd=workdir, timeout=600)
if not os.path.exists(name + ".json"):
raise RuntimeError(f"orca_2json failed: {r.stdout[-500:]} {r.stderr[-500:]}")
d = json.load(open(name + ".json"))
for f in glob.glob(name + "*"):
os.remove(f)
return d["Molecule"]["Atoms"]
def shell_key(basis):
return json.dumps(basis, sort_keys=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--store", required=True)
ap.add_argument("--gbw-root", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--per-element", type=int, default=2)
args = ap.parse_args()
cands = candidates(args.store, args.gbw_root, args.per_element)
print(f"{len(cands)} elements present; "
f"{sum(1 for v in cands.values() if not v)} without a staged gbw", flush=True)
workdir = tempfile.mkdtemp(prefix="orca2json_", dir=os.environ.get("PSCRATCH", "/tmp"))
cache = {}
elements = {}
problems = []
for Z in sorted(cands):
seen_basis, seen_ecp, zeff_seen, sources = [], [], set(), []
for ds, cid, nb, rank, path in cands[Z]:
if path not in cache:
try:
cache[path] = run_orca_2json(path, workdir)
except Exception as e:
problems.append(f"Z={Z} {cid}: {e}")
continue
atoms = cache[path]
prev_ecp_elem = None
for a in atoms:
zi = int(a["ElementNumber"])
zeff = float(a["NuclearCharge"])
has_ecp = zi - zeff > 0
if zi == Z:
seen_basis.append(shell_key(a["Basis"]))
zeff_seen.add(zeff)
if has_ecp:
blk = a.get("ECPs")
ncore = int(round(zi - zeff))
# trust the block only when it cannot be a leak: consistent N_core and
# no different ECP element printed before this atom
if blk and int(blk.get("N_core", -1)) == ncore and prev_ecp_elem in (None, Z):
seen_ecp.append(shell_key(blk))
sources.append(cid)
if has_ecp:
prev_ecp_elem = zi
if not seen_basis:
problems.append(f"Z={Z}: no basis exported")
continue
if len(set(seen_basis)) != 1:
problems.append(f"Z={Z}: basis differs between occurrences ({len(set(seen_basis))} variants)")
if len(zeff_seen) != 1:
problems.append(f"Z={Z}: NuclearCharge differs between occurrences {sorted(zeff_seen)}")
zeff = sorted(zeff_seen)[0]
ecp = None
if Z - zeff > 0:
if not seen_ecp:
problems.append(f"Z={Z}: ECP expected (Z_eff={zeff}) but no trustworthy block found")
else:
if len(set(seen_ecp)) != 1:
problems.append(f"Z={Z}: ECP block differs between sources")
ecp = json.loads(seen_ecp[0])
basis = json.loads(seen_basis[0])
nao = sum({"s": 1, "p": 3, "d": 5, "f": 7, "g": 9, "h": 11}[s["Shell"]] for s in basis)
elements[str(Z)] = {
"symbol": SYMBOLS[Z], "Z": Z, "Z_eff": zeff, "n_core": int(round(Z - zeff)),
"n_ao": nao, "shells": [s["Shell"] for s in basis], "basis": basis, "ecp": ecp,
"n_sources": len(set(sources)), "n_ecp_blocks_checked": len(seen_ecp),
}
print(f" Z={Z:3d} {SYMBOLS[Z]:2s} Z_eff={zeff:5.1f} shells={''.join(s['Shell'] for s in basis)} "
f"nao={nao} ecp={'yes' if ecp else 'no'} sources={len(set(sources))}", flush=True)
shutil.rmtree(workdir, ignore_errors=True)
out = {
"basis_name": "def2-TZVPD as stored by ORCA 6.0.0 (exported with orca_2json, Basisset only)",
"conventions": {
"functions": "spherical harmonics",
"ao_order": "per atom, shells in the listed order; within a shell m order "
"p=(z,x,y) d=(z2,xz,yz,x2-y2,xy) f=(0,+1,-1,+2,-2,+3,-3)",
"sign_vs_pyscf": "f(+3) and f(-3) carry the opposite sign to pyscf's real solid harmonics",
"normalisation": "contraction coefficients exactly as orca_2json prints them",
"ecp": "ECPs.potential: per l, ecp = [exponents, coefficients, powers]; N_core electrons replaced",
},
"elements": elements,
"problems": problems,
}
with open(args.out, "w") as fh:
json.dump(out, fh, indent=1)
print(f"\nwrote {args.out}: {len(elements)} elements, {len(problems)} problems")
for p in problems:
print(" PROBLEM:", p)
if __name__ == "__main__":
main()