"""Family-rule ensemble: one member per model family, selected without the held-out study. The published four-member stack (PhysChem-Tree + PhysSet-LNP + RF + ET) was fixed a priori. This script formalises a cleaner rule - one member per *family* present in the benchmark (identity-free tree, physics-informed neural, neural baseline, discrete-relation kernel) - and prices it with the same leave-one-study-out protocol as `stack_loso.py`: within each family the representative is chosen on the three training studies only, then the ensemble is evaluated on the held-out study. PYTHONPATH=src python scripts/stack_family.py """ from __future__ import annotations import argparse import re from collections import defaultdict from pathlib import Path import numpy as np import pandas as pd from scipy import stats from scipy.stats import spearmanr PATTERN = re.compile(r"(?P.+?)__(?P.+?)__s(?P\d+)\.npz$") EXTERNAL = re.compile(r"^(LM_2019|BL_2023|SL_2020|ZC_2023)_fold\d+$") STUDIES = ("LM_2019", "BL_2023", "SL_2020", "ZC_2023") FAMILIES = { "tree": ["physchem_tree", "randomforest", "extratrees", "xgboost"], "neural_phys": ["physset_phys", "phcausal_phys", "probe_flat_rank"], "neural_base": ["lion", "agile"], "relation": ["relmode_nr_w", "physmode_chem"], } # fixed sets reported alongside the LOSO estimate FIXED = { "family4": ["physchem_tree", "physset_phys", "lion", "relmode_nr_w"], "family5": ["physchem_tree", "physset_phys", "lion", "relmode_nr_w", "extratrees"], "published_4": ["physchem_tree", "physset_phys", "randomforest", "extratrees"], "published_5": ["physchem_tree", "physset_phys", "randomforest", "extratrees", "relmode_nr_w"], } def rank_norm(x: np.ndarray) -> np.ndarray: return stats.rankdata(x, method="average") / len(x) - 0.5 def load(pred_dir: Path) -> dict: table: dict = defaultdict(dict) for f in sorted(Path(pred_dir).glob("*.npz")): m = PATTERN.match(f.name) if not m or not EXTERNAL.match(m["task"]): continue z = np.load(f) table[(m["model"], m["task"])][int(m["seed"])] = (z["y"], z["pred"]) return table def ens_pred(table, members, task): cols, y = [], None for mem in members: seeds = table.get((mem, task)) if not seeds: continue cols.append(np.mean([rank_norm(p) for _, p in seeds.values()], axis=0)) if y is None: y = seeds[0][0] if len(cols) < 2: return None, None return y, np.mean(cols, axis=0) def rho(table, members, task): y, p = ens_pred(table, members, task) return float("nan") if y is None else spearmanr(y, p).statistic def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--pred-dir", default="results/predictions") ap.add_argument("--out", default="results/stack_family.csv") args = ap.parse_args() table = load(Path(args.pred_dir)) tasks = sorted({t for (_, t) in table}) rows = [] for name, members in FIXED.items(): per = {t: rho(table, members, t) for t in tasks} s = pd.Series(per).dropna() by = s.groupby(s.index.to_series().str.rsplit("_fold", n=1).str[0]).mean() rows.append({"stack": name, "n": len(s), "mean": s.mean(), "selection": "fixed", **{f"s_{k}": v for k, v in by.items()}}) for held in STUDIES: tr_tasks = [t for t in tasks if not t.startswith(held)] he_tasks = [t for t in tasks if t.startswith(held)] sel = [max(cands, key=lambda m: np.nanmean([rho(table, [m], t) for t in tr_tasks])) for cands in FAMILIES.values()] h = np.nanmean([rho(table, sel, t) for t in he_tasks]) tr = np.nanmean([rho(table, sel, t) for t in tr_tasks]) rows.append({"stack": "family4_loso", "n": len(he_tasks), "mean": h, "selection": f"held-out {held}; members {'/'.join(sel)}", "train_mean": tr}) df = pd.DataFrame(rows) df.to_csv(args.out, index=False) loso = df.loc[df["stack"] == "family4_loso", "mean"].mean() print(df.round(4).to_string(index=False)) print(f"\nhonest family-LOSO estimate: {loso:.4f}") print("wrote", args.out) if __name__ == "__main__": main()