File size: 8,909 Bytes
39ea985 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | """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()
|