File size: 4,268 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
"""Minimal reader for ORCA 6 .gbw files (reverse-engineered, validated against orca.out on OMol25 data).

Layout: 64-byte header of little-endian int64 words; word 3 (byte 24) points to the MO block:
  int32 n_operators (1 = RHF/RKS, 2 = UHF/UKS), int32 dim, then for each operator
  dim*dim float64 coefficients stored so that reshape(dim, dim) gives C[ao, mo], dim float64 occupations,
  dim float64 orbital energies (Eh), dim int32 irreps, dim int32 core flags.
Returns C[ao, mo] (columns = MOs) in ORCA AO ordering; C^T S C = I verified to 1e-7 against pyscf S.
"""
import struct, numpy as np, zstandard as zstd

def read_gbw(path):
    b = open(path, "rb").read()
    if path.endswith(".zstd0") or b[:4] == b"\x28\xb5\x2f\xfd":
        b = zstd.ZstdDecompressor().decompressobj().decompress(b)
    hdr = struct.unpack_from("<8q", b, 0)
    ptr = hdr[3]
    nop, dim = struct.unpack_from("<ii", b, ptr); off = ptr + 8
    ops = []
    for _ in range(nop):
        C = np.frombuffer(b, dtype="<f8", count=dim*dim, offset=off).reshape(dim, dim).copy(); off += dim*dim*8
        occ = np.frombuffer(b, dtype="<f8", count=dim, offset=off).copy(); off += dim*8
        en = np.frombuffer(b, dtype="<f8", count=dim, offset=off).copy(); off += dim*8
        irrep = np.frombuffer(b, dtype="<i4", count=dim, offset=off).copy(); off += dim*4
        core = np.frombuffer(b, dtype="<i4", count=dim, offset=off).copy(); off += dim*4
        ops.append(dict(C=C, occ=occ, energies=en, irrep=irrep, core=core))
    return dict(nbas=dim, nop=nop, ops=ops, header=hdr)

if __name__ == "__main__":
    import sys
    sys.path.insert(0, "/global/u1/e/ericqu/omol_elec_process")
    from check_overlap import parse, orca_overlap
    from pyscf import gto
    G = "/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/gbw_pilot"; S_ = "/global/cfs/projectdirs/m5293/ericqu/omol_elec_process/samples"
    def inflate(v):
        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())
    for rel in sys.argv[1:]:
        name = rel.split("/")[0]
        g = read_gbw(f"{G}/{rel}/orca.gbw.zstd0"); z = np.load(f"{G}/{rel}/density_mat.npz")
        atoms, charge, mult, hftyp, nbas, eps, F = parse(f"{S_}/{rel}/orca.out")
        a = g["ops"][0]; C, occ, en = a["C"], a["occ"], a["energies"]
        nmo = int((eps != 0).sum())
        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}"
        # density from gbw vs npz
        P_npz = inflate(z["orca.scfp"])
        if g["nop"] == 2:
            b_ = g["ops"][1]; Pg = C @ np.diag(occ) @ C.T + b_["C"] @ np.diag(b_["occ"]) @ b_["C"].T
        else:
            Pg = C @ np.diag(occ) @ C.T
        line += f" | P(gbw)-P(npz) max {np.abs(Pg-P_npz).max():.1e}"
        # S from C when no linear dependence: S = C^-T C^-1 ; F = C^-T diag(eps) C^-1
        if nmo == nbas:
            Ci = np.linalg.inv(C); F_rec = Ci.T @ np.diag(en) @ Ci; S_rec = Ci.T @ Ci
            line += f" | F(gbw)-F(printed): max {np.abs(F_rec-F).max():.1e}, rms {np.sqrt(((F_rec-F)**2).mean()):.1e}"
            try:
                mol = gto.M(atom=atoms, basis="def2-tzvpd", ecp="def2-tzvpd", unit="Angstrom", charge=charge, spin=mult-1, verbose=0)
                S, _ = orca_overlap(mol); line += f" | S(gbw)-S(pyscf) max {np.abs(S_rec-S).max():.1e}"
            except Exception as e:
                line += f" | pyscf basis unavailable ({type(e).__name__})"
        else:
            line += f" | {nbas-nmo} lin.dep. removed: C is {nbas}x{nmo}, F/S not invertible from C alone"
            try:
                mol = gto.M(atom=atoms, basis="def2-tzvpd", ecp="def2-tzvpd", unit="Angstrom", charge=charge, spin=mult-1, verbose=0)
                S, _ = orca_overlap(mol); Ck = C[:, :nmo]
                line += f" | C^T S C - I max {np.abs(Ck.T @ S @ Ck - np.eye(nmo)).max():.1e}"
                F_rec = S @ Ck @ np.diag(en[:nmo]) @ Ck.T @ S
                line += f" | F(S C e C^T S)-F(printed) max {np.abs(F_rec-F).max():.1e}"
            except Exception as e:
                line += f" | pyscf basis unavailable ({type(e).__name__})"
        print(line, flush=True)