MaterialsSaddles / scripts /dedup /verify_dedup.py
sunghjung3's picture
Merge v2-dedup (77d73af) into main, part 12
46709a8 verified
Raw History Blame Contribute Delete
6.75 kB
"""Audit 2-4 of the dedup, with code written independently of pass 2 (ASE get_distances for the minimum image;
assignment re-solved per species on the MIC distance matrix; no early stopping).
2. PRECISION: random removed triplets -> recompute saddle / endpoint max-atom distances to their representative.
3. RECALL: random kept triplets -> compare with EVERY same-composition triplet in the bucket (not only cluster
representatives) and count true matches that were not clustered together (missed duplicates).
4. SPLIT FILES: every kept triplet in exactly one new fold, no removed triplet in any fold, all three frames present,
no chemical system in two folds, and the pass-1 bucket geometry equals the original shard rows (sample).
usage: verify_dedup.py [n_precision] [n_recall]
"""
import glob, sys, zlib
import numpy as np, pyarrow.parquet as pq
from collections import defaultdict, Counter
from scipy.optimize import linear_sum_assignment
from ase.geometry import get_distances
OUT = "/scratch/08405/ilgar/saddleflow/data/dedup_2026-09-28"; ROOT = "/scratch/08405/ilgar/MaterialsSaddles"; NB = 64; THR = 0.2
NP = int(sys.argv[1]) if len(sys.argv) > 1 else 3000; NR = int(sys.argv[2]) if len(sys.argv) > 2 else 2000
rng = np.random.default_rng(12345)
def maxd_ind(p1, p2, z, cell):
"""Independent max-atom distance: MIC via ASE, per-species assignment minimising summed squared distance."""
pbc = abs(np.linalg.det(cell)) > 1e-6; mx = 0.0
for v in np.unique(z):
i = np.where(z == v)[0]
_, D = get_distances(p1[i], p2[i], cell=cell if pbc else None, pbc=pbc)
r, k = linear_sum_assignment(D ** 2); mx = max(mx, float(D[r, k].max()))
return mx
def same_lattice(c1, c2):
L1, L2 = np.linalg.norm(c1, axis=1), np.linalg.norm(c2, axis=1)
return np.all(np.abs(L1 - L2) <= 0.02 * L2) and np.abs(c1 - c2).max() <= 0.02 * L2.max()
def triplet_match(a, b):
"""True if b duplicates a: same lattice, saddle and both endpoints (either orientation) within THR."""
if not same_lattice(a["cell"], b["cell"]): return False, None
cm = 0.5 * (a["cell"] + b["cell"])
map_ = lambda x, c: (x @ np.linalg.inv(c)) @ cm if abs(np.linalg.det(c)) > 1e-6 else x
A = {k: map_(a[k], a["cell"]) for k in "RSP"}; B = {k: map_(b[k], b["cell"]) for k in "RSP"}
s = maxd_ind(A["S"], B["S"], a["z"], cm)
if s >= THR: return False, s
same = max(maxd_ind(A["R"], B["R"], a["z"], cm), maxd_ind(A["P"], B["P"], a["z"], cm))
swap = max(maxd_ind(A["R"], B["P"], a["z"], cm), maxd_ind(A["P"], B["R"], a["z"], cm))
return min(same, swap) < THR, s
def load_bucket(b):
parts = [np.load(f) for f in sorted(glob.glob(f"{OUT}/buckets/b{b:02d}/*.npz"))]
cat = lambda k: np.concatenate([p[k] for p in parts])
ms, nat, comp, cell = cat("ms"), cat("nat"), cat("comp"), cat("cell"); Z, R, S, P = cat("z"), cat("R"), cat("S"), cat("P")
off = np.concatenate([[0], np.cumsum(nat)])
get = lambda i: dict(ms=int(ms[i]), z=Z[off[i]:off[i+1]], cell=cell[i], R=R[off[i]:off[i+1]].astype(float),
S=S[off[i]:off[i+1]].astype(float), P=P[off[i]:off[i+1]].astype(float))
return ms, comp, get
cl = pq.read_table(f"{OUT}/duplicates.parquet"); cms = np.asarray(cl.column(0)); crep = np.asarray(cl.column(1))
o = np.argsort(cms); cms, crep = cms[o], crep[o]; rep_of = lambda m: int(crep[np.searchsorted(cms, m)])
# ---- 2 + 3, over a random subset of buckets
prec_fail, prec_n, prec_s = [], 0, []
rec_miss, rec_n = [], 0
buckets = rng.permutation(NB)[:16]
for b in buckets:
ms, comp, get = load_bucket(int(b)); idx_of = {int(m): i for i, m in enumerate(ms)}
removed = [i for i, m in enumerate(ms) if rep_of(int(m)) != int(m)]
for i in rng.permutation(removed)[: NP // len(buckets)]:
a = get(i); r = get(idx_of[rep_of(a["ms"])]); ok, s = triplet_match(r, a); prec_n += 1; prec_s.append(s if s is not None else np.nan)
if not ok: prec_fail.append((a["ms"], r["ms"], s))
groups = defaultdict(list)
for i, c in enumerate(comp): groups[c].append(i)
kept = [i for i, m in enumerate(ms) if rep_of(int(m)) == int(m) and len(groups[comp[i]]) > 1 and len(groups[comp[i]]) <= 3000]
for i in rng.permutation(kept)[: NR // len(buckets)]:
a = get(i); rec_n += 1
for j in groups[comp[i]]:
if j == i: continue
bb = get(j)
if rep_of(bb["ms"]) == a["ms"]: continue # already in a's cluster
ok, _ = triplet_match(a, bb)
if ok: rec_miss.append((a["ms"], bb["ms"], rep_of(bb["ms"]))); break
print(f"[2 precision] removed triplets re-checked: {prec_n}; NOT matching their representative: {len(prec_fail)} {prec_fail[:5]}")
print(f" saddle max-atom distance of removed vs representative: median {np.nanmedian(prec_s):.4f}, max {np.nanmax(prec_s):.4f} A")
print(f"[3 recall] kept triplets checked against all same-composition triplets: {rec_n}; with a missed duplicate elsewhere: {len(rec_miss)} ({100*len(rec_miss)/max(rec_n,1):.2f}%) {rec_miss[:5]}")
# ---- 4: split files
SUBS = ["lemat", "mp20bat", "oc20", "oc22"]; fold_of = {}; problems = Counter()
for s in SUBS:
for k in ("train", "val", "test"):
f = np.asarray(pq.read_table(f"{OUT}/splits_chemsys_dedup/{s}/{k}.parquet").column("ms_id"))
sad = f[f % 3 == 1]
if not (len(f) == 3 * len(sad) and np.array_equal(np.sort(f), np.sort(np.concatenate([sad - 1, sad, sad + 1])))): problems[f"{s}/{k}: frames not complete triplets"] += 1
for m in sad.tolist():
if m in fold_of: problems["triplet in two folds"] += 1
fold_of[m] = k
kept_all = cms[crep == cms]; rem_all = cms[crep != cms]
print(f"[4 split] kept {len(kept_all)}, in a fold {len(fold_of)}; kept but in no fold: {len(set(kept_all.tolist()) - set(fold_of))}; "
f"removed but in a fold: {len(set(rem_all.tolist()) & set(fold_of))}; problems: {dict(problems)}")
M = [np.load(f) for f in sorted(glob.glob(f"{OUT}/meta/*.npz"))]
mm = np.concatenate([m["ms"] for m in M]); mc = np.concatenate([m["chemsys"] for m in M])
cs_folds = defaultdict(set)
for m, c in zip(mm.tolist(), mc.tolist()):
if m in fold_of: cs_folds[c].add(fold_of[m])
print(f" chemical systems in more than one fold: {sum(len(v) > 1 for v in cs_folds.values())} of {len(cs_folds)}")
msub = np.concatenate([m["sub"] for m in M]); sub_map = dict(zip(mm.tolist(), msub.tolist()))
cross = Counter()
for m, r in zip(rem_all.tolist(), crep[crep != cms].tolist()):
if sub_map[m] != sub_map[r]: cross[(SUBS[sub_map[r]] + " kept", SUBS[sub_map[m]] + " removed")] += 1
print(" duplicate clusters spanning subsets:", dict(cross) if cross else "none")