"""Ontology/schema and global-representation experiments. Two questions are answered here, both at full scale (20 external tasks): 1. Does a role-aware chemical ontology add transferable information on top of the identity-free chemistry block? 2. Does a label-free *global* representation of chemical space (archetype codebook / spectral embedding) add anything a per-molecule description cannot? The script also runs the feature-level leakage audit: for every candidate block it measures how well the study of origin can be recovered from the features alone. A block that is cheap to classify by study is exactly the block that the external protocol should punish, so the audit is a screening test that can be run in minutes. Usage:: python scripts/schema_bench.py --build # cache all blocks python scripts/schema_bench.py --mode audit python scripts/schema_bench.py --mode bench --blocks base onto base+onto """ from __future__ import annotations import argparse import pickle from pathlib import Path import numpy as np import pandas as pd from scipy.stats import spearmanr from lnpbench.features import chemistry_block from lnpbench.ontology import schema_block STUDIES = ("LM_2019", "BL_2023", "SL_2020", "ZC_2023") CACHE = Path("cache") def _rows(store) -> np.ndarray: return np.arange(len(store)) def build_blocks(store, force: bool = False) -> dict: """Build and cache every candidate block as a dense matrix over all rows.""" path = CACHE / "schema_blocks.npz" if path.exists() and not force: z = np.load(path) return {k: z[k] for k in z.files} import time t0 = time.time() def tick(msg): print(f"[{time.time() - t0:7.1f}s] {msg}", flush=True) rows = _rows(store) base = chemistry_block(store, rows) tick(f"base {base.shape}") onto_all = schema_block(store, rows, "all") tick(f"onto {onto_all.shape}") onto_il = schema_block(store, rows, "il") onto_slots = schema_block(store, rows, "slots") onto_cross = schema_block(store, rows, "cross") tick("onto parts") from lnpbench.global_rep import codebook_embed, spectral_embed # label-free, transductive: the codebook sees the geometry of all rows cb = codebook_embed(base, np.arange(len(base)), k=64, pca_dim=48) tick(f"codebook {cb.shape}") spec = spectral_embed(base, None, k=50, pca_dim=48, n_components=24) tick(f"spectral {spec.shape}") np.savez(CACHE / "spectral_diagnostics.npz", spectrum=spectral_embed.last_spectrum) out = { "base": base, "onto": onto_all, "onto_il": onto_il, "onto_slots": onto_slots, "onto_cross": onto_cross, "cb": cb, "spec": spec, "base+onto": np.concatenate([base, onto_all], 1), "base+cb": np.concatenate([base, cb], 1), "base+spec": np.concatenate([base, spec], 1), "onto+cb": np.concatenate([onto_all, cb], 1), "base+onto+cb": np.concatenate([base, onto_all, cb], 1), "base+onto+cb+spec": np.concatenate([base, onto_all, cb, spec], 1), # sub-block decompositions of the ontology: the cross-slot ratios are # the most study-identifiable part of the block (see the audit), so the # 20-task run repeats without them "base+onto_nocross": np.concatenate([base, onto_il, onto_slots], 1), "base+onto_il": np.concatenate([base, onto_il], 1), "base+onto_slots": np.concatenate([base, onto_slots], 1), } np.savez_compressed(path, **{k: v.astype(np.float32) for k, v in out.items()}) print("cached blocks:", {k: v.shape for k, v in out.items()}) return out def run_audit(store, blocks: dict) -> pd.DataFrame: """How much of the study of origin is recoverable from each block?""" from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import StratifiedKFold, cross_val_predict from sklearn.metrics import balanced_accuracy_score, accuracy_score y = store.study_id cand = dict(blocks) cand["ctx_only"] = store.ctx.astype(np.float32) cand["base+ctx"] = np.concatenate([blocks["base"], store.ctx], 1).astype(np.float32) skf = StratifiedKFold(n_splits=3, shuffle=True, random_state=0) rows = [] for name, X in cand.items(): X = np.nan_to_num(np.asarray(X, dtype=np.float32), nan=0.0, posinf=0.0, neginf=0.0) X = np.clip(X, -1e5, 1e5) # A forest is used deliberately: it is the model class that actually # consumes these blocks, and it measures "can a flexible learner tell # the studies apart", not "is the block linearly separable". clf = RandomForestClassifier(n_estimators=200, min_samples_leaf=2, n_jobs=48, random_state=0) pred = cross_val_predict(clf, X, y, cv=skf, n_jobs=3) rows.append({ "block": name, "dim": X.shape[1], "balanced_acc": balanced_accuracy_score(y, pred), "accuracy": accuracy_score(y, pred), }) print(f"{name:22s} dim={X.shape[1]:5d} bal_acc={rows[-1]['balanced_acc']:.4f}", flush=True) df = pd.DataFrame(rows).sort_values("balanced_acc", ascending=False) df["chance"] = 1.0 / len(np.unique(y)) return df def _fit_rf(Xtr, ytr, seed: int, workers: int): from sklearn.ensemble import RandomForestRegressor m = RandomForestRegressor(n_estimators=400, min_samples_leaf=2, n_jobs=workers, random_state=seed) m.fit(Xtr, ytr) return m def run_bench(store, blocks: dict, names, out: Path, pred_dir: Path | None, workers: int, seeds=(0,)) -> pd.DataFrame: with open(Path(store.cache) / "tasks.pkl", "rb") as fh: tasks = pickle.load(fh) rows = [] for name in names: X = blocks[name] for t in tasks: tname = t["name"] if not tname.startswith(STUDIES): continue study = tname.rsplit("_fold", 1)[0] fold = int(tname.rsplit("fold", 1)[1]) for seed in seeds: m = _fit_rf(X[t["train_idx"]], store.y[t["train_idx"]], seed, workers) pred = m.predict(X[t["test_idx"]]) rho = spearmanr(store.y[t["test_idx"]], pred).statistic if pred_dir is not None: pred_dir.mkdir(parents=True, exist_ok=True) np.savez_compressed(pred_dir / f"{name.replace('+','_')}__{tname}__s{seed}.npz", idx=t["test_idx"], y=store.y[t["test_idx"]].astype(np.float32), pred=pred.astype(np.float32)) rows.append({"config": name, "task": tname, "study": study, "fold": fold, "seed": seed, "spearman": float(rho)}) print(f"{name:18s} {tname:16s} s{seed} rho={rho:.4f}", flush=True) out.parent.mkdir(parents=True, exist_ok=True) pd.DataFrame(rows).to_csv(out, index=False) df = pd.DataFrame(rows) if len(df): print("\n== mean over 20 tasks ==") print(df.groupby("config").spearman.agg(["size", "mean", "std"]).round(4).to_string()) return df def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--mode", default="bench", choices=["build", "audit", "bench"]) ap.add_argument("--blocks", nargs="+", default=["base", "onto", "base+onto"]) ap.add_argument("--seeds", nargs="+", type=int, default=[0]) ap.add_argument("--workers", type=int, default=48) ap.add_argument("--force", action="store_true") ap.add_argument("--out", default="results/schema_bench.csv") ap.add_argument("--audit-out", default="results/schema_audit.csv") ap.add_argument("--pred-dir", default="results/predictions") args = ap.parse_args() from lnpbench.store import FeatureStore store = FeatureStore() blocks = build_blocks(store, force=args.force) print({k: v.shape for k, v in blocks.items()}) if args.mode == "build": return if args.mode == "audit": df = run_audit(store, blocks) Path(args.audit_out).parent.mkdir(parents=True, exist_ok=True) df.to_csv(args.audit_out, index=False) print(df.to_string(index=False)) return pred_dir = Path(args.pred_dir) if args.pred_dir else None run_bench(store, blocks, args.blocks, Path(args.out), pred_dir, args.workers, tuple(args.seeds)) if __name__ == "__main__": main()