"""Pass 3: drop duplicates and write a composition-disjoint train/val/test split. Keeps one representative per duplicate cluster (pass 2). Every CHEMICAL SYSTEM (the set of elements of the triplet) is assigned as a whole to train / val / test with probabilities 0.90 / 0.05 / 0.05 (seeded), globally across all four subsets, so no element set appears in two folds - not within a subset and not across subsets (lemat and mp20bat share materials chemistry). Output, same convention as the released splits (every frame ms_id of every kept triplet): splits_chemsys_dedup//{train,val,test}.parquet column ms_id duplicates.parquet columns saddle_ms_id, representative_saddle_ms_id (every triplet; equal = kept) and a report comparing the old split (how much of old test shares a chemical system / formula with old train). usage: dedup_pass3.py [seed] """ import glob, sys, os, json import numpy as np, pyarrow as pa, pyarrow.parquet as pq OUT = "/scratch/08405/ilgar/saddleflow/data/dedup_2026-09-28"; ROOT = "/scratch/08405/ilgar/MaterialsSaddles" SUBSETS = ["lemat", "mp20bat", "oc20", "oc22"]; FR = {"train": 0.90, "val": 0.05, "test": 0.05} seed = int(sys.argv[1]) if len(sys.argv) > 1 else 0 M = [np.load(f, allow_pickle=False) for f in sorted(glob.glob(f"{OUT}/meta/*.npz"))] ms = np.concatenate([m["ms"] for m in M]); sub = np.concatenate([m["sub"] for m in M]) cs = np.concatenate([m["chemsys"] for m in M]); fo = np.concatenate([m["formula"] for m in M]) o = np.argsort(ms); ms, sub, cs, fo = ms[o], sub[o], cs[o], fo[o] assert len(np.unique(ms)) == len(ms), "duplicate triplet rows across meta files" C = [np.load(f) for f in sorted(glob.glob(f"{OUT}/clusters/b*.npz"))] cms = np.concatenate([c["ms"] for c in C]); crep = np.concatenate([c["rep"] for c in C]) oc = np.argsort(cms); cms, crep = cms[oc], crep[oc] assert np.array_equal(cms, ms), "clusters and metadata cover different triplets" keep = crep == ms rep = {"triplets": int(len(ms)), "duplicates_removed": int((~keep).sum())} # old split per triplet (saddle ms_id) old = np.full(len(ms), "", dtype=object) for s in SUBSETS: for k in FR: ids = np.asarray(pq.read_table(f"{ROOT}/splits/{s}/{k}.parquet").column("ms_id")); ids = ids[ids % 3 == 1] old[np.searchsorted(ms, ids)] = k assert (old != "").all(), "triplets missing from the old split" # leakage in the OLD split: test triplets whose chemical system / formula also occurs in old train (any subset) tr_cs = set(cs[old == "train"]); tr_fo = set(fo[old == "train"]) for s_i, s in enumerate(SUBSETS): t = (old == "test") & (sub == s_i) rep[f"old_{s}_test_chemsys_in_train_pct"] = round(100 * np.mean([c in tr_cs for c in cs[t]]), 1) rep[f"old_{s}_test_formula_in_train_pct"] = round(100 * np.mean([f in tr_fo for f in fo[t]]), 1) rep[f"{s}_duplicates_removed_pct"] = round(100 * np.mean(~keep[sub == s_i]), 2) rep[f"{s}_old_test_duplicates_removed_pct"] = round(100 * np.mean(~keep[t]), 2) # new split: whole chemical systems, seeded rng = np.random.default_rng(seed); systems = np.unique(cs[keep]) draw = rng.choice(list(FR), size=len(systems), p=list(FR.values())); assign = dict(zip(systems, draw)) new = np.array([assign.get(c, "") for c in cs], dtype=object); new[~keep] = "" rep["chemical_systems"] = int(len(systems)); rep["seed"] = seed os.makedirs(f"{OUT}/splits_chemsys_dedup", exist_ok=True) for s_i, s in enumerate(SUBSETS): os.makedirs(f"{OUT}/splits_chemsys_dedup/{s}", exist_ok=True); n = {} for k in FR: sad = ms[(sub == s_i) & (new == k)]; n[k] = int(len(sad)) frames = np.sort(np.concatenate([sad - 1, sad, sad + 1])) pq.write_table(pa.table({"ms_id": pa.array(frames, pa.int64())}), f"{OUT}/splits_chemsys_dedup/{s}/{k}.parquet") tot = sum(n.values()); rep[f"{s}_new_triplets"] = n rep[f"{s}_new_fractions"] = {k: round(v / tot, 4) for k, v in n.items()} rep[f"{s}_new_test_chemical_systems"] = int(len(set(cs[(sub == s_i) & (new == "test")]))) # sanity: no chemical system in two folds for a in FR: for b in FR: if a < b: assert not (set(cs[new == a]) & set(cs[new == b])), (a, b) pq.write_table(pa.table({"saddle_ms_id": pa.array(ms, pa.int64()), "representative_saddle_ms_id": pa.array(crep, pa.int64())}), f"{OUT}/duplicates.parquet") json.dump(rep, open(f"{OUT}/REPORT.json", "w"), indent=1); print(json.dumps(rep, indent=1))