File size: 18,569 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
"""Pass B1: molecular-orbital coefficients from the gbw files into the p2 store.

For every p2 shard the worker reads each calculation's gbw (staged by Globus at
<gbw_root>/<dataset>/<calc_id>.gbw.zstd0), takes the FULL coefficient matrix of both spin
channels, checks that the gbw and the Pass A text describe the same calculation, and appends the
result to the shard group. Zarr lets arrays be added to an existing group, so p2 keeps its layout
and row order; every new array is row-aligned with the shard's existing calculations.

Added arrays:

    cmo_a, cmo_a_offsets        MO coefficients, MO-major: calculation i is
                                cmo_a[o[i]:o[i+1]].reshape(nbas, nbas) = C^T, i.e. row k is MO k
                                over the AOs (ORCA AO order). Occupied orbitals are the first
                                nocc rows, so C_occ is a contiguous prefix. float32 by default.
    cmo_b, cmo_b_offsets        the same for the beta channel (empty for RHF)
    gbw_eps_a/b (+_offsets)     fp64 orbital energies of all nbas orbitals from the gbw
    gbw_occ_a/b (+_offsets)     fp64 occupations of all nbas orbitals from the gbw
    mo_i                        int columns: nocc_a, nocc_b, gbw_nbas, gbw_nop
    mo_f8                       diagnostics: occ_sum_a/b; eps_err_a/b = max |gbw - printed| over
                                the printed orbital energies; fc_offdiag_a/b = largest
                                off-diagonal of C_occ^T F C_occ (Eh); fc_diag_err_a/b =
                                max |diag(C_occ^T F C_occ) - eps_occ| (Eh); fc_bound_a/b = what
                                the 5e-7 Eh print rounding of F can do to that block
    mo_flags                    gbw_found, nbas_match, nspin_match, nelec_match, spin_match,
                                eps_checked, eps_match, occ_contiguous, fock_checked, fock_match,
                                mo_ok

mo_ok is the conjunction of every check that could be run. fock_match is only meaningful when
fock_checked is set (a Fock matrix was printed and nbas agreed); it asks that the printed Fock
matrix be diagonal in the gbw's occupied orbitals to 1e-2 Eh. A mismatched pair is off by
0.1 to 1 Eh, so the flag is a pairing test, not a convergence test. Typical values are ~1e-6 Eh,
but in near-linearly-dependent bases (smallest overlap eigenvalue ~1e-6, not removed by ORCA)
the 5e-7 Eh print rounding of F is amplified by the large MO coefficients into ~1e-3 Eh on the
occupied block even though F_print agrees with C^-T diag(e) C^-1 to 1e-5 in the AO basis. The
fc_bound columns give that rounding amplification per calculation (5e-7 x max_i ||C_i||_1^2);
compare fc_diag_err against it before reading a large value as an inconsistency.

Usage:
    python pass_b1.py --store $PSCRATCH/omol_100k --gbw-root $PSCRATCH/gbw_100k --workers 48
"""
from __future__ import annotations
import argparse, glob, json, os, sys, time, traceback
import multiprocessing as mp
import numpy as np
import zarr

# One thread per worker process: zarr's default pool (os.cpu_count() threads) times 64 to 96
# forked workers thrashed a 128-core node, cutting throughput several-fold.
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 gbw_reader import read_gbw
from omol_store import put_array, inflate_fock

MO_I = ("nocc_a", "nocc_b", "gbw_nbas", "gbw_nop")
MO_F8 = ("occ_sum_a", "occ_sum_b", "eps_err_a", "eps_err_b",
         "fc_offdiag_a", "fc_offdiag_b", "fc_diag_err_a", "fc_diag_err_b",
         "fc_bound_a", "fc_bound_b")
MO_FLAGS = ("gbw_found", "nbas_match", "nspin_match", "nelec_match", "spin_match",
            "eps_checked", "eps_match", "occ_contiguous", "fock_checked", "fock_match", "mo_ok")
INFORMATIONAL = ("eps_checked", "fock_checked", "mo_ok")
EPS_TOL = 5e-6      # printed to 6 decimals; rounding alone gives 5e-7
FOCK_TOL = 1e-2     # Eh; see the docstring on why the occupied block can be off by ~1e-3
CMO_CHUNK = 1 << 22
OLD_ARRAYS = ("cocc_a", "cocc_a_offsets", "cocc_b", "cocc_b_offsets", "cocc_occ_a",
              "cocc_occ_a_offsets", "cocc_occ_b", "cocc_occ_b_offsets", "cocc_i", "cocc_f8",
              "cocc_flags")


def p2_shards(store):
    out = []
    for depth in ("*", "*/*/*"):
        out += glob.glob(os.path.join(store, "p2", depth, "*.zarr"))
    return sorted(set(out))


def fock_check(F, C, eps):
    """Largest off-diagonal of C^T F C and largest |diag - eps|, in Eh."""
    M = C.T @ (F @ C)
    d = np.diag(M).copy()
    np.fill_diagonal(M, 0.0)
    return float(np.abs(M).max()) if M.size else 0.0, float(np.abs(d - eps).max()) if d.size else 0.0


def process_shard(args):
    sp, gbw_root, force, dtype = args
    t0 = time.time()
    try:
        g = zarr.open_group(sp, mode="r+")
        if g.attrs.get("has_mo") and g.attrs.get("mo_dtype") == dtype and not force:
            return sp, "skip", {}, [], 0.0, ""
        n = int(g.attrs["n_calc"])
        ids = g.attrs["calc_id"]
        ds = g.attrs["dataset"]
        si = np.asarray(g["scalar_i"])
        ic = {k: j for j, k in enumerate(g.attrs["scalar_i_cols"])}
        fl = np.asarray(g["flags"]).astype(bool)
        fc = {k: j for j, k in enumerate(g.attrs["flag_cols"])}
        eps = {s: np.asarray(g[f"eps_{s}"]) for s in "ab"}
        eoff = {s: np.asarray(g[f"eps_{s}_offsets"]) for s in "ab"}
        foff = {s: np.asarray(g[f"fock_{s}_offsets"]) for s in "ab"}
        nbas_all = si[:, ic["nbas"]].astype("i8")
        nsp_all = np.where(fl[:, fc["is_uhf"]], 2, 1)

        # Preallocate the coefficient buffers from the text's nbas (verified against the gbw
        # below; a mismatch leaves that calculation's slot empty and flagged).
        cap = {s: np.zeros(n + 1, dtype="i8") for s in "ab"}
        cap["a"][1:] = np.cumsum(nbas_all ** 2)
        cap["b"][1:] = np.cumsum(np.where(nsp_all == 2, nbas_all ** 2, 0))
        buf = {s: np.zeros(int(cap[s][-1]), dtype=dtype) for s in "ab"}
        filled = {s: np.zeros(n, dtype=bool) for s in "ab"}
        geps = {s: [] for s in "ab"}
        gocc = {s: [] for s in "ab"}
        mi = np.zeros((n, len(MO_I)), dtype="i8")
        mf = np.full((n, len(MO_F8)), np.nan)
        mfl = np.zeros((n, len(MO_FLAGS)), dtype="i1")
        failures = []

        for i in range(n):
            nbas = int(nbas_all[i])
            nelec = int(si[i, ic["nelec"]])
            mult = int(si[i, ic["mult"]])
            is_uhf = bool(fl[i, fc["is_uhf"]])
            has_fock = bool(fl[i, fc["has_fock"]])
            flags = dict.fromkeys(MO_FLAGS, False)
            path = os.path.join(gbw_root, ds, ids[i] + ".gbw.zstd0")
            gb = None
            if os.path.exists(path):
                try:
                    gb = read_gbw(path)
                    flags["gbw_found"] = True
                except Exception as e:
                    failures.append((ids[i], f"gbw read error: {type(e).__name__}: {str(e)[:120]}"))
            else:
                failures.append((ids[i], "gbw missing"))
            if gb is None:
                for s in "ab":
                    geps[s].append(np.zeros(0)); gocc[s].append(np.zeros(0))
                mfl[i] = [flags[k] for k in MO_FLAGS]
                continue

            dim, nop = gb["nbas"], gb["nop"]
            mi[i, MO_I.index("gbw_nbas")] = dim
            mi[i, MO_I.index("gbw_nop")] = nop
            flags["nbas_match"] = dim == nbas
            flags["nspin_match"] = nop == (2 if is_uhf else 1)
            occ_sum = {}
            contiguous = True
            eps_ok = True
            eps_checked = False
            fock_checked = fock_ok = True
            for k, s in enumerate("ab"):
                if k >= nop:
                    geps[s].append(np.zeros(0)); gocc[s].append(np.zeros(0))
                    occ_sum[s] = 0.0
                    continue
                op = gb["ops"][k]
                occ_v, en_v, C = op["occ"], op["energies"], op["C"]
                mask = occ_v > 0
                nocc = int(mask.sum())
                idx = np.flatnonzero(mask)
                if nocc and (idx[-1] != nocc - 1):
                    contiguous = False
                if dim == nbas and (s == "a" or is_uhf):
                    # MO-major (C^T) so the occupied block is a contiguous prefix
                    buf[s][cap[s][i]:cap[s][i + 1]] = C.T.ravel().astype(dtype, copy=False)
                    filled[s][i] = True
                geps[s].append(en_v.copy())
                gocc[s].append(occ_v.copy())
                mi[i, MO_I.index(f"nocc_{s}")] = nocc
                occ_sum[s] = float(occ_v.sum())
                mf[i, MO_F8.index(f"occ_sum_{s}")] = occ_sum[s]
                # printed orbital energies (6 decimals) against the gbw. A reduced print level
                # (the no-Fock metal_organics inputs) lists only the first few hundred orbitals,
                # so compare over the printed prefix; energies of removed orbitals print as 0.
                e_txt = eps[s][eoff[s][i]:eoff[s][i + 1]]
                if 0 < len(e_txt) <= dim:
                    eps_checked = True
                    m = e_txt != 0.0
                    err = float(np.abs(en_v[:len(e_txt)][m] - e_txt[m]).max()) if m.any() else 0.0
                    mf[i, MO_F8.index(f"eps_err_{s}")] = err
                    if err > EPS_TOL:
                        eps_ok = False
                elif len(e_txt) > dim:
                    eps_checked = True
                    eps_ok = False
                # printed Fock diagonal in the gbw occupied orbitals
                if has_fock and dim == nbas and nocc:
                    f0, f1 = int(foff[s][i]), int(foff[s][i + 1])
                    if f1 > f0:
                        Co = np.ascontiguousarray(C[:, mask])
                        F = inflate_fock(np.asarray(g[f"fock_{s}"][f0:f1]), nbas)
                        od, de = fock_check(F, Co, en_v[mask])
                        mf[i, MO_F8.index(f"fc_offdiag_{s}")] = od
                        mf[i, MO_F8.index(f"fc_diag_err_{s}")] = de
                        mf[i, MO_F8.index(f"fc_bound_{s}")] = 5e-7 * float(
                            (np.abs(Co).sum(axis=0) ** 2).max())
                        if od > FOCK_TOL or de > FOCK_TOL:
                            fock_ok = False
                        del F, Co
                    else:
                        fock_checked = False
                else:
                    fock_checked = False
            tot = occ_sum["a"] + occ_sum["b"]
            flags["nelec_match"] = abs(tot - nelec) < 1e-6
            if nop == 2:
                flags["spin_match"] = abs((occ_sum["a"] - occ_sum["b"]) - (mult - 1)) < 1e-6
            else:
                flags["spin_match"] = mult == 1 and abs(occ_sum["a"] - nelec) < 1e-6
            flags["eps_checked"] = eps_checked
            flags["eps_match"] = eps_ok
            flags["occ_contiguous"] = contiguous
            flags["fock_checked"] = fock_checked
            flags["fock_match"] = fock_ok
            flags["mo_ok"] = all(flags[k] for k in MO_FLAGS if k not in INFORMATIONAL)
            mfl[i] = [flags[k] for k in MO_FLAGS]
            if not flags["mo_ok"]:
                bad = [k for k in MO_FLAGS if k not in INFORMATIONAL and not flags[k]]
                failures.append((ids[i], "failed: " + ",".join(bad)))

        def ragged(parts, dt):
            offs = np.zeros(len(parts) + 1, dtype="i8")
            offs[1:] = np.cumsum([len(p) for p in parts])
            flat = np.concatenate(parts).astype(dt) if parts else np.zeros(0, dt)
            return flat, offs

        for name in OLD_ARRAYS:
            if name in g:
                del g[name]
        for s in "ab":
            # offsets follow the filled slots; an unfilled slot (gbw missing or nbas mismatch)
            # gets a zero-length block so the array stays dense
            lens = np.where(filled[s], np.diff(cap[s]), 0)
            offs = np.zeros(n + 1, dtype="i8")
            offs[1:] = np.cumsum(lens)
            if filled[s].all():
                flat = buf[s]
            else:
                flat = np.concatenate([buf[s][cap[s][i]:cap[s][i + 1]] for i in range(n) if filled[s][i]]
                                      ) if filled[s].any() else np.zeros(0, dtype)
            put_array(g, f"cmo_{s}", flat, codec=None,
                      chunks=(max(1, min(len(flat), CMO_CHUNK)),), overwrite=True)
            put_array(g, f"cmo_{s}_offsets", offs, overwrite=True)
            flat, offs = ragged(geps[s], "f8")
            put_array(g, f"gbw_eps_{s}", flat, overwrite=True)
            put_array(g, f"gbw_eps_{s}_offsets", offs, overwrite=True)
            flat, offs = ragged(gocc[s], "f8")
            put_array(g, f"gbw_occ_{s}", flat, overwrite=True)
            put_array(g, f"gbw_occ_{s}_offsets", offs, overwrite=True)
        put_array(g, "mo_i", mi, overwrite=True)
        put_array(g, "mo_f8", mf, overwrite=True)
        put_array(g, "mo_flags", mfl, overwrite=True)
        for k in ("has_cocc", "cocc_schema", "cocc_i_cols", "cocc_f8_cols", "cocc_flag_cols",
                  "cocc_layout", "cocc_gbw_root"):
            g.attrs.pop(k, None)
        g.attrs.update({
            "has_mo": True,
            "mo_schema": "omol_elec/pass_b1/2",
            "mo_dtype": dtype,
            "mo_i_cols": list(MO_I),
            "mo_f8_cols": list(MO_F8),
            "mo_flag_cols": list(MO_FLAGS),
            "mo_layout": "cmo_x[o[i]:o[i+1]].reshape(nbas, nbas) = C^T (row k = MO k over AOs, "
                         "ORCA AO order); occupied MOs are the first nocc_x rows",
            "mo_gbw_root": gbw_root,
        })
        stats = {
            "n": n,
            "found": int(mfl[:, MO_FLAGS.index("gbw_found")].sum()),
            "ok": int(mfl[:, MO_FLAGS.index("mo_ok")].sum()),
            "fock_checked": int(mfl[:, MO_FLAGS.index("fock_checked")].sum()),
            "bytes_cmo": int(sum(int(g[f"cmo_{s}"].shape[0]) for s in "ab") * np.dtype(dtype).itemsize),
            "eps_err_max": float(np.nanmax(mf[:, [2, 3]])) if np.isfinite(mf[:, [2, 3]]).any() else float("nan"),
            "fc_offdiag_max": float(np.nanmax(mf[:, [4, 5]])) if np.isfinite(mf[:, [4, 5]]).any() else float("nan"),
            "fc_offdiag_p50": float(np.nanmedian(mf[:, [4, 5]])) if np.isfinite(mf[:, [4, 5]]).any() else float("nan"),
        }
        for k in MO_FLAGS:
            stats["fail_" + k] = int(n - mfl[:, MO_FLAGS.index(k)].sum())
        return sp, "ok", stats, failures, time.time() - t0, ""
    except Exception:
        return sp, "fail", {}, [], time.time() - t0, traceback.format_exc(limit=4)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--store", required=True)
    ap.add_argument("--gbw-root", required=True)
    ap.add_argument("--workers", type=int, default=48)
    ap.add_argument("--dtype", default="f4", choices=("f4", "f8"))
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--force", action="store_true", help="recompute shards that already have MOs")
    args = ap.parse_args()
    shards = p2_shards(args.store)
    if args.limit:
        shards = shards[:args.limit]
    print(f"pass B1 (full C, {args.dtype}): {len(shards)} p2 shards in {args.store}, "
          f"gbw from {args.gbw_root}", flush=True)
    jobs = [(s, args.gbw_root, args.force, args.dtype) for s in shards]
    t0 = time.time()
    tot = {}
    all_fail, shard_fail = [], []
    n_skip = 0
    eps_max = fc_max = 0.0
    fc_p50 = []
    with mp.Pool(min(args.workers, len(jobs))) as pool:
        for k, (sp, status, st, failures, dt, err) in enumerate(pool.imap_unordered(process_shard, jobs), 1):
            if status == "ok":
                for key, v in st.items():
                    if key.startswith(("n", "found", "ok", "fock_checked", "bytes", "fail_")):
                        tot[key] = tot.get(key, 0) + v
                if st["eps_err_max"] == st["eps_err_max"]:
                    eps_max = max(eps_max, st["eps_err_max"])
                if st["fc_offdiag_max"] == st["fc_offdiag_max"]:
                    fc_max = max(fc_max, st["fc_offdiag_max"])
                if st["fc_offdiag_p50"] == st["fc_offdiag_p50"]:
                    fc_p50.append(st["fc_offdiag_p50"])
                all_fail.extend((sp, cid, why) for cid, why in failures)
            elif status == "skip":
                n_skip += 1
            else:
                shard_fail.append((sp, err))
                print(f"SHARD FAIL {sp}\n{err}", flush=True)
            if k % 50 == 0 or k == len(jobs):
                el = time.time() - t0
                print(f"  {k}/{len(jobs)}  calcs {tot.get('n',0):,} found {tot.get('found',0):,} "
                      f"ok {tot.get('ok',0):,}  {tot.get('bytes_cmo',0)/1e9:.0f} GB  {el/60:.1f} min  "
                      f"eta {el/k*(len(jobs)-k)/60:.1f} min", flush=True)
    dt = time.time() - t0
    print(f"\nB1 done in {dt/60:.1f} min: shards ok {len(jobs)-n_skip-len(shard_fail)}, "
          f"skipped {n_skip}, failed {len(shard_fail)}")
    print(f"calculations {tot.get('n',0):,}: gbw found {tot.get('found',0):,}, "
          f"mo_ok {tot.get('ok',0):,}, fock checked {tot.get('fock_checked',0):,}")
    for k in MO_FLAGS:
        print(f"  not {k:15s}: {tot.get('fail_'+k, 0):,}")
    print(f"C bytes {tot.get('bytes_cmo',0)/1e12:.3f} TB  "
          f"({tot.get('bytes_cmo',0)/max(tot.get('n',1),1)/1e6:.2f} MB/calc, {args.dtype})")
    print(f"max eps error (gbw vs printed) {eps_max:.2e} Eh; "
          f"C_occ^T F C_occ off-diagonal: median-of-shard-medians "
          f"{np.median(fc_p50) if fc_p50 else float('nan'):.2e}, max {fc_max:.2e} Eh")
    out = os.path.join(args.store, "b1_failures.tsv")
    with open(out, "w") as fh:
        fh.write("shard\tcalc_id\treason\n")
        for sp, cid, why in all_fail:
            fh.write(f"{os.path.relpath(sp, args.store)}\t{cid}\t{why}\n")
    print(f"{len(all_fail)} per-calculation problems written to {out}")
    with open(os.path.join(args.store, "b1_summary.json"), "w") as fh:
        json.dump({"totals": tot, "dtype": args.dtype, "eps_err_max": eps_max,
                   "fc_offdiag_max": fc_max, "wall_s": dt,
                   "shard_failures": [s for s, _ in shard_fail]}, fh, indent=1)


if __name__ == "__main__":
    mp.set_start_method("fork", force=True)
    main()