Datasets:
File size: 5,051 Bytes
46709a8 | 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 | """v2 step 3: write the deduplicated, split release by copying stored rows byte for byte.
Every kept triplet (fold from <split_dir>/<subset>/{train,val,test}.parquet) is written to
<out>/<subset>/<fold>/<subset>_<fold>_<NNNN>.aselmdb
in ascending ms_id order (R, S, P rows of a triplet adjacent), at most <per_shard> triplets per file. The files are
cut on the full split list, and then the BROKEN triplets are left out, so lemat_train_0213 and lemat_train_0479
hold per_shard - 1 triplets and the other files do not change. Rows are NOT
re-serialised: the zlib-compressed JSON value stored in the SciLM shard is copied unchanged under a new LMDB key
("1".."3n"; the id is not part of the stored value), then "nextid" = 3n+1 is written exactly as ase_db_backends does.
Each file is written as <name>.tmp and renamed only after its transaction committed.
usage: v2_write.py <scilm_root> <scilm_index_dir> <split_dir> <out_root> [per_shard=50000] [workers=48] [subsets]
"""
import glob, os, sys, zlib, json
import numpy as np, pyarrow.parquet as pq
from ase.io.jsonio import encode
from multiprocessing import Pool
FOLDS = ["train", "val", "test"]
src_root, idx_dir, split_dir, out = sys.argv[1:5]
per = int(sys.argv[5]) if len(sys.argv) > 5 else 50000; nw = int(sys.argv[6]) if len(sys.argv) > 6 else 48
SUBS = sys.argv[7].split(",") if len(sys.argv) > 7 else ["lemat", "mp20bat", "oc20", "oc22"]
# saddle ms_ids of the 2 lemat triplets with broken forces (max |F| at the saddle 4.78e11 and 1.02e8 eV/A), found
# after the split was drawn. They stay in the split lists, so that the file cuts do not move, and are not written.
BROKEN = [35584423, 79800988]
def load_index(s):
Z = [np.load(f) for f in sorted(glob.glob(f"{idx_dir}/{s}__*.npz"))]
shards = [str(z["shard"]) for z in Z]
ms = np.concatenate([z["ms"] for z in Z]); key = np.concatenate([z["key"] for z in Z])
fi = np.concatenate([np.full(len(z["ms"]), i, np.int32) for i, z in enumerate(Z)])
o = np.argsort(ms); ms, key, fi = ms[o], key[o], fi[o]
assert (np.diff(ms) > 0).all(), f"{s}: repeated ms_id in the source"
return ms, key, fi, shards
def plan():
jobs = []
for s in SUBS:
ms, key, fi, shards = load_index(s)
for f in FOLDS:
fr = np.sort(np.asarray(pq.read_table(f"{split_dir}/{s}/{f}.parquet").column("ms_id")))
sad = fr[fr % 3 == 1]
assert np.array_equal(fr, np.sort(np.concatenate([sad - 1, sad, sad + 1]))), f"{s}/{f}: incomplete triplets"
pos = np.searchsorted(ms, fr); assert (pos < len(ms)).all() and np.array_equal(ms[pos], fr), f"{s}/{f}: ms_id missing in source"
n = (len(sad) + per - 1) // per
for k in range(n):
rows = pos[3 * k * per: 3 * (k + 1) * per]
rows = rows[~np.isin(ms[rows] // 3, np.array(BROKEN) // 3)] # leave out the 3 rows of a BROKEN triplet
name = f"{s}/{f}/{s}_{f}_{k:04d}.aselmdb"
jobs.append((name, [shards[i] for i in range(len(shards))], fi[rows], key[rows], ms[rows]))
return jobs
def work(job):
import lmdb
name, shards, fi, key, ms = job
dst = f"{out}/{name}"
if os.path.exists(dst): return name, len(ms), "exists"
os.makedirs(os.path.dirname(dst), exist_ok=True)
vals = [None] * len(ms)
for f in np.unique(fi): # read grouped by source file, in key order
env = lmdb.open(f"{src_root}/{shards[f]}", subdir=False, readonly=True, lock=False, readahead=False, meminit=False)
sel = np.where(fi == f)[0]; sel = sel[np.argsort(key[sel])]
with env.begin(buffers=False) as t:
for i in sel:
v = t.get(str(int(key[i])).encode("ascii")); assert v is not None, (name, shards[f], key[i]); vals[i] = v
env.close()
tmp = dst + ".tmp"
for p in (tmp, tmp + "-lock"):
if os.path.exists(p): os.remove(p)
env = lmdb.open(tmp, subdir=False, map_size=2 ** 41, meminit=False, lock=False, sync=True)
with env.begin(write=True) as t:
for i, v in enumerate(vals):
assert t.put(str(i + 1).encode("ascii"), v, overwrite=False)
t.put(b"nextid", zlib.compress(bytes(encode(len(vals) + 1), "utf-8")), overwrite=False)
env.sync(True); env.close()
os.rename(tmp, dst)
return name, len(ms), "written"
if __name__ == "__main__":
jobs = plan(); jobs.sort(key=lambda j: -len(j[4]))
print(f"{len(jobs)} output shards, {sum(len(j[4]) for j in jobs)} rows", flush=True)
man = [(j[0], len(j[4]) // 3, int(j[4][0]), int(j[4][-1])) for j in sorted(jobs)]
os.makedirs(out, exist_ok=True)
if len(SUBS) == 4:
with open(f"{out}/.manifest.tsv", "w") as fh:
fh.write("file\ttriplets\tfirst_ms_id\tlast_ms_id\n")
for m in man: fh.write("\t".join(map(str, m)) + "\n")
with Pool(nw) as pool:
for n, (name, r, st) in enumerate(pool.imap_unordered(work, jobs), 1):
print(f" {n}/{len(jobs)} {name}: {r} rows {st}", flush=True)
|