File size: 15,534 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
363
364
365
366
367
368
369
370
371
372
373
374
375
"""Zarr v3 shard writer for Pass A.

Layout
------
Each worker writes self-contained *shards*, so there is no write contention and no resize logic:

    store/p1/<dataset>/shard_<nnnn>_<nn>.zarr   scalars + per-atom + per-pair
    store/p2/<dataset>/shard_<nnnn>_<nn>.zarr   the same, plus fock/, eps/, occ/

p2 duplicates the p1 arrays on purpose: the tables are tiny next to the matrices (<0.2 TB for the
whole collection) and it keeps p1 independently usable without the 6 TB matrix store.

Columns are *packed*: all float scalars live in one (n_calc, n_col) array, all per-atom floats in
one (n_atom_total, n_col) array, and so on, with the column names recorded in group attrs. Writing
one array per column meant ~80 Zarr arrays per shard, and zarr-python's sync wrapper costs enough
per array that shard writes dominated the run; packing cuts that to ~15 arrays.

Ragged quantities are a concatenated array plus an int64 offsets array of length n_calc+1, so
calculation i occupies [off[i], off[i+1]).

Codecs follow the benchmark: Blosc zstd 9 + bit-shuffle for the int32 Fock triangles (4.5x), Blosc
zstd 5 + byte-shuffle elsewhere.
"""
from __future__ import annotations
import os
import numpy as np
import zarr
from zarr.codecs import BloscCodec

SHELLS = ("s", "p", "d", "f", "g")

FOCK_CODEC = [BloscCodec(cname="zstd", clevel=9, shuffle="bitshuffle")]
DATA_CODEC = [BloscCodec(cname="zstd", clevel=5, shuffle="shuffle")]

SCALARS_F8 = (
    "e_total", "e_total_engrad", "e_nuc_rep", "e_one_elec", "e_two_elec", "e_kinetic",
    "virial_ratio", "e_xc", "e_nl", "e_exchange", "n_alpha_int", "n_beta_int",
    "s2", "s2_ideal", "s2_dev", "conv_denergy", "conv_maxdp", "conv_rmsdp", "conv_diiserr",
    "smallest_ovlp_eig", "grad_norm", "grad_rms", "grad_max", "run_time_s",
    "dipole_au", "dipole_debye", "quad_iso", "npa_core", "npa_valence", "npa_rydberg",
    "nbo_lewis", "nbo_nonlewis", "homo_a", "lumo_a", "gap_a", "homo_b", "lumo_b", "gap_b",
)
SCALARS_I = ("charge", "mult", "nelec", "nbas", "naux", "n_lindep", "scf_cycles", "n_atoms")
FLAGS = ("scf_converged", "terminated_normally", "nbo_available", "npa_available",
         "is_uhf", "has_fock")
VEC = (("dipole_elec", 3), ("dipole_nuc", 3), ("dipole_total", 3), ("rot_const_cm", 3),
       ("rot_const_mhz", 3), ("quad_diag", 3), ("quad_nuc", 6), ("quad_elec", 6),
       ("quad_total", 6))

ATOM_1D = ("mulliken_q", "mulliken_s", "loewdin_q", "loewdin_s",
           "mayer_NA", "mayer_ZA", "mayer_QA", "mayer_VA", "mayer_BVA", "mayer_FA",
           "npa_q", "npa_atom_core", "npa_atom_val", "npa_atom_ryd", "npa_spin")
ATOM_VEC3 = ("coords", "forces")
ATOM_SHELL = ("mulliken_shell_q", "mulliken_shell_s", "loewdin_shell_q", "loewdin_shell_s",
              "natural_config")
PAIRS = ("mayer_bo", "loewdin_bo", "mulliken_ovlp")

ATOM_F8_COLS = [f"{k}_{ax}" for k in ATOM_VEC3 for ax in "xyz"] + list(ATOM_1D)
VEC_COLS = [f"{name}_{i}" for name, w in VEC for i in range(w)]
SHELL_COLS = [f"{k}_{sh}" for k in ATOM_SHELL for sh in SHELLS]


def frontier(eps, occ):
    """HOMO, LUMO and gap in Eh. Orbitals removed for linear dependence print as exactly 0.0."""
    if eps is None or occ is None or len(eps) == 0:
        return np.nan, np.nan, np.nan
    occupied = np.flatnonzero(occ > 0)
    if occupied.size == 0:
        return np.nan, np.nan, np.nan
    h = int(occupied[-1])
    homo = float(eps[h])
    lumo = np.nan
    for k in range(h + 1, len(eps)):
        if eps[k] != 0.0:
            lumo = float(eps[k])
            break
    return homo, lumo, (lumo - homo if lumo == lumo else np.nan)


def _fock_chunk_elems(median_nbas):
    if median_nbas < 600:
        return 65_536
    if median_nbas <= 2000:
        return 1_000_000
    return 4_194_304


CHUNKS_PER_SHARD = 256


def put_array(g, name, data, codec=DATA_CODEC, chunks=None, overwrite=False):
    """Create array `name` in group `g` holding `data`, using Zarr's sharding codec.

    With sharding an array is a handful of files no matter how many chunks it holds. Without it
    each chunk is a file: the first full run produced 1.5 to 4.7 files per calculation, on course
    to exhaust the 10 M-inode scratch quota. One shard file holds CHUNKS_PER_SHARD chunks (capped
    at the array itself), and the shard length is always a multiple of the chunk length as Zarr
    requires. `codec=None` stores the bytes uncompressed (for incompressible fp32 coefficients).
    """
    data = np.ascontiguousarray(data)
    if chunks is None:
        if data.ndim == 1:
            chunks = (max(1, min(data.shape[0], 1 << 22)),)
        else:
            chunks = (max(1, min(data.shape[0], 1 << 18)),) + data.shape[1:]
    chunks = tuple(int(c) for c in chunks)
    n_chunks = max(1, -(-data.shape[0] // chunks[0]))          # ceil
    shards = (chunks[0] * min(CHUNKS_PER_SHARD, n_chunks),) + tuple(data.shape[1:])
    if overwrite and name in g:
        del g[name]
    z = g.create_array(name=name, shape=data.shape, chunks=chunks, shards=shards,
                       dtype=data.dtype, compressors=codec)
    if data.size:
        z[...] = data
    return z


def write_shard(records, out_dir, shard_name, include_matrices):
    """Write one shard group. Records are parser outputs augmented with calc_id/rel_path/dataset."""
    os.makedirs(out_dir, exist_ok=True)
    path = os.path.join(out_dir, shard_name)
    g = zarr.open_group(path, mode="w")
    n = len(records)
    natom = [r["n_atoms"] for r in records]
    atom_off = np.cumsum([0] + natom).astype("i8")

    def put(name, data, codec=DATA_CODEC, chunks=None):
        put_array(g, name, data, codec=codec, chunks=chunks)

    # ---- identity and column names live in attrs: JSON, portable, no bytes dtype
    g.attrs.update({
        "schema": "omol_elec/pass_a/2",
        "n_calc": n,
        "shells": list(SHELLS),
        "scalar_f8_cols": list(SCALARS_F8),
        "scalar_i_cols": list(SCALARS_I),
        "flag_cols": list(FLAGS),
        "vec_cols": VEC_COLS,
        "atom_f8_cols": ATOM_F8_COLS,
        "atom_shell_cols": SHELL_COLS,
        "pair_names": list(PAIRS),
        "calc_id": [r["calc_id"] for r in records],
        "rel_path": [r["rel_path"] for r in records],
        "dataset": records[0]["dataset"] if n else "",
        "hftyp": [(r.get("hftyp") or "?") for r in records],
        "has_matrices": bool(include_matrices),
    })

    # ---- packed scalars
    sf = np.full((n, len(SCALARS_F8)), np.nan)
    for i, r in enumerate(records):
        for j, k in enumerate(SCALARS_F8):
            v = r.get(k)
            if v is not None:
                sf[i, j] = v
    put("scalar_f8", sf)

    si = np.full((n, len(SCALARS_I)), -1, dtype="i8")
    for i, r in enumerate(records):
        for j, k in enumerate(SCALARS_I):
            v = r.get(k)
            if v is not None:
                si[i, j] = v
    put("scalar_i", si)

    fl = np.zeros((n, len(FLAGS)), dtype="i1")
    for i, r in enumerate(records):
        for j, k in enumerate(FLAGS):
            if k == "is_uhf":
                fl[i, j] = bool(r.get("hftyp") == "UHF")
            elif k == "has_fock":
                fl[i, j] = r.get("fock_a") is not None
            else:
                fl[i, j] = bool(r.get(k))
    put("flags", fl)

    vv = np.full((n, len(VEC_COLS)), np.nan)
    for i, r in enumerate(records):
        c = 0
        for name, w in VEC:
            v = r.get(name)
            if v is not None and len(v) == w:
                vv[i, c:c + w] = v
            c += w
    put("vec", vv)

    # ---- per-atom, packed
    put("atom_offsets", atom_off)
    tot = int(atom_off[-1])
    az = np.zeros(tot, dtype="i2")
    af = np.full((tot, len(ATOM_F8_COLS)), np.nan)
    ash = np.full((tot, len(SHELL_COLS)), np.nan, dtype="f4")
    for i, r in enumerate(records):
        a, b = int(atom_off[i]), int(atom_off[i + 1])
        z = r.get("atomic_numbers")
        if z is not None:
            az[a:b] = np.asarray(z, dtype="i2")
        c = 0
        for k in ATOM_VEC3:
            v = r.get(k)
            if v is not None:
                af[a:b, c:c + 3] = np.asarray(v, dtype="f8").reshape(-1, 3)
            c += 3
        for k in ATOM_1D:
            v = r.get(k)
            if v is not None:
                af[a:b, c] = np.asarray(v, dtype="f8")
            c += 1
        c = 0
        for k in ATOM_SHELL:
            v = r.get(k)
            if v is not None:
                ash[a:b, c:c + len(SHELLS)] = np.asarray(v, dtype="f4").reshape(-1, len(SHELLS))
            c += len(SHELLS)
    put("atom_z", az)
    put("atom_f8", af)
    put("atom_shell", ash)

    # ---- per-pair: one offsets/index/value triple per bond-order flavour
    for key in PAIRS:
        idx, val, offs = [], [], [0]
        for r in records:
            for i, j, v in (r.get(key) or []):
                idx.append((i, j))
                val.append(v)
            offs.append(len(val))
        put(f"pair_{key}_offsets", np.array(offs, dtype="i8"))
        put(f"pair_{key}_index", np.array(idx, dtype="i4").reshape(-1, 2))
        put(f"pair_{key}_value", np.array(val, dtype="f4"))

    # ---- orbitals and matrices (p2 only)
    if include_matrices:
        med = int(np.median([r["nbas"] for r in records])) if n else 1000
        fchunk = _fock_chunk_elems(med)
        for spin in ("a", "b"):
            eps_parts, occ_parts, offs = [], [], [0]
            for r in records:
                e, o = r.get(f"eps_{spin}"), r.get(f"occ_{spin}")
                if e is None:
                    e, o = np.zeros(0), np.zeros(0)
                eps_parts.append(np.asarray(e, dtype="f8"))
                occ_parts.append(np.asarray(o, dtype="f8"))
                offs.append(offs[-1] + len(e))
            put(f"eps_{spin}_offsets", np.array(offs, dtype="i8"))
            put(f"eps_{spin}", np.concatenate(eps_parts) if eps_parts else np.zeros(0))
            put(f"occ_{spin}", np.concatenate(occ_parts) if occ_parts else np.zeros(0))

            fparts, foffs = [], [0]
            for r in records:
                f = r.get(f"fock_{spin}")
                f = np.zeros(0, dtype="i4") if f is None else np.asarray(f, dtype="i4")
                fparts.append(f)
                foffs.append(foffs[-1] + len(f))
            flat = np.concatenate(fparts) if fparts else np.zeros(0, dtype="i4")
            put(f"fock_{spin}_offsets", np.array(foffs, dtype="i8"))
            put(f"fock_{spin}", flat, codec=FOCK_CODEC,
                chunks=(max(1, min(len(flat), fchunk)),))
    return path


def shard_bytes(rec):
    """Rough in-memory footprint, used to decide when to flush a shard."""
    b = 0
    for k in ("fock_a", "fock_b", "eps_a", "eps_b", "occ_a", "occ_b"):
        v = rec.get(k)
        if v is not None:
            b += v.nbytes
    return b + 4096


# ----------------------------------------------------------------------------- reading
def read_calc(g, i):
    """Unpack calculation i from an open shard group into a dict."""
    out = {}
    sf = g["scalar_f8"][i]
    for j, k in enumerate(g.attrs["scalar_f8_cols"]):
        out[k] = float(sf[j])
    si = g["scalar_i"][i]
    for j, k in enumerate(g.attrs["scalar_i_cols"]):
        out[k] = int(si[j])
    fl = g["flags"][i]
    for j, k in enumerate(g.attrs["flag_cols"]):
        out[k] = bool(fl[j])
    vv = g["vec"][i]
    c = 0
    for name, w in VEC:
        out[name] = np.asarray(vv[c:c + w])
        c += w
    out["calc_id"] = g.attrs["calc_id"][i]
    out["rel_path"] = g.attrs["rel_path"][i]
    out["hftyp"] = g.attrs["hftyp"][i]
    out["dataset"] = g.attrs["dataset"]

    a, b = int(g["atom_offsets"][i]), int(g["atom_offsets"][i + 1])
    out["atomic_numbers"] = np.asarray(g["atom_z"][a:b])
    af = np.asarray(g["atom_f8"][a:b])
    cols = g.attrs["atom_f8_cols"]
    out["coords"] = af[:, [cols.index(f"coords_{x}") for x in "xyz"]]
    out["forces"] = af[:, [cols.index(f"forces_{x}") for x in "xyz"]]
    for k in ATOM_1D:
        out[k] = af[:, cols.index(k)]
    ash = np.asarray(g["atom_shell"][a:b])
    for j, k in enumerate(ATOM_SHELL):
        out[k] = ash[:, j * len(SHELLS):(j + 1) * len(SHELLS)]
    for key in PAIRS:
        p0 = int(g[f"pair_{key}_offsets"][i])
        p1 = int(g[f"pair_{key}_offsets"][i + 1])
        out[key] = (np.asarray(g[f"pair_{key}_index"][p0:p1]),
                    np.asarray(g[f"pair_{key}_value"][p0:p1]))
    if g.attrs.get("has_matrices"):
        for spin in ("a", "b"):
            e0 = int(g[f"eps_{spin}_offsets"][i])
            e1 = int(g[f"eps_{spin}_offsets"][i + 1])
            out[f"eps_{spin}"] = np.asarray(g[f"eps_{spin}"][e0:e1])
            out[f"occ_{spin}"] = np.asarray(g[f"occ_{spin}"][e0:e1])
            f0 = int(g[f"fock_{spin}_offsets"][i])
            f1 = int(g[f"fock_{spin}_offsets"][i + 1])
            out[f"fock_{spin}"] = np.asarray(g[f"fock_{spin}"][f0:f1])
    return out


def inflate_fock(tri, nbas):
    """int32 micro-Hartree upper triangle -> symmetric float64 matrix in Eh."""
    M = np.zeros((nbas, nbas))
    M[np.triu_indices(nbas)] = tri.astype(np.float64) * 1e-6
    return M + M.T - np.diag(M.diagonal())


def read_mo(g, i, spin="a"):
    """MO coefficient matrix C[ao, mo] of calculation i for one spin channel (after Pass B1).

    Stored MO-major (C^T) so the occupied block is a contiguous prefix; this returns the
    (nbas, n_stored) matrix with columns = MOs in ORCA AO order: all nbas orbitals in a full-C
    store, the nocc occupied ones in an occupied-only store (see attrs["mo_content"]). Empty
    (nbas, 0) when the channel is absent (beta of an RHF run) or the gbw was not paired.
    """
    nbas = int(g["scalar_i"][i][list(g.attrs["scalar_i_cols"]).index("nbas")])
    o0, o1 = int(g[f"cmo_{spin}_offsets"][i]), int(g[f"cmo_{spin}_offsets"][i + 1])
    if o1 == o0:
        return np.zeros((nbas, 0), dtype=g[f"cmo_{spin}"].dtype)
    # (nbas, nbas) in a full-C store, (nbas, nocc) in an occupied-only one (attrs["mo_content"])
    return np.asarray(g[f"cmo_{spin}"][o0:o1]).reshape(-1, nbas).T


def read_cocc(g, i):
    """Occupied MO coefficients and gbw orbital data for calculation i (after Pass B1).

    Returns C_a (nbas, nocc_a) and C_b (nbas, nocc_b) in ORCA AO order, the occupations of those
    columns, the full gbw orbital energies and occupations, and the B1 flags. Empty arrays when the
    gbw was not paired; check flags['mo_ok'] before trusting the pairing.
    """
    out = {}
    nbas = int(g["scalar_i"][i][list(g.attrs["scalar_i_cols"]).index("nbas")])
    mi = g["mo_i"][i]
    for j, k in enumerate(g.attrs["mo_i_cols"]):
        out[k] = int(mi[j])
    mf = g["mo_f8"][i]
    for j, k in enumerate(g.attrs["mo_f8_cols"]):
        out[k] = float(mf[j])
    fl = g["mo_flags"][i]
    out["flags"] = {k: bool(fl[j]) for j, k in enumerate(g.attrs["mo_flag_cols"])}
    for s in "ab":
        nocc = out[f"nocc_{s}"]
        o0, o1 = int(g[f"cmo_{s}_offsets"][i]), int(g[f"cmo_{s}_offsets"][i + 1])
        if o1 > o0 and nocc:
            # first nocc rows of C^T, read without touching the virtual block
            out[f"C_{s}"] = np.asarray(g[f"cmo_{s}"][o0:o0 + nocc * nbas]).reshape(nocc, nbas).T
        else:
            out[f"C_{s}"] = np.zeros((nbas, 0), dtype=g[f"cmo_{s}"].dtype)
        for name in ("gbw_eps", "gbw_occ"):
            a, b = int(g[f"{name}_{s}_offsets"][i]), int(g[f"{name}_{s}_offsets"][i + 1])
            out[f"{name}_{s}"] = np.asarray(g[f"{name}_{s}"][a:b])
        out[f"cocc_occ_{s}"] = out[f"gbw_occ_{s}"][:nocc]
    return out