"""Extended chemistry blocks for the tree read-out. The reported 398-d block deliberately contains no fingerprint: it was built to be identity-free, and a Morgan fingerprint is the single most study-identifying feature in the database. Two extensions are tested here, both motivated by the observation that the tree read-out and the neural read-out see *different* information: * ``fp`` -- the 2048-bit Morgan fingerprint of the intact ionisable lipid. The neural models consume it; the trees never did. * ``maccs`` -- the 166-bit MACCS substructure keys, a different substructure vocabulary from the RDKit descriptor block. Both are appended to the 398-d block and evaluated with the same four learners over the 20 external tasks. The study-identifiability audit must be repeated for any block that is adopted. PYTHONPATH=src python scripts/block_v2.py --blocks base fp maccs base+fp """ from __future__ import annotations import argparse import time import numpy as np import pandas as pd from scipy import stats from lnpbench import data, metrics, paths from lnpbench.store import FeatureStore def maccs_keys(store: FeatureStore) -> np.ndarray: """166-bit MACCS keys for every unique ionisable lipid, row-aligned to il_id.""" from rdkit import Chem, RDLogger from rdkit.Chem import MACCSkeys RDLogger.DisableLog("rdApp.*") smiles = store.il_smiles out = np.zeros((len(smiles), 167), dtype=np.float32) for i, s in enumerate(smiles): mol = Chem.MolFromSmiles(s) if isinstance(s, str) and s.strip() else None if mol is None: continue out[i] = MACCSkeys.GenMACCSKeys(mol).ToList() return out def build_blocks(store: FeatureStore, idx: np.ndarray) -> dict: from lnpbench.features import chemistry_block base = chemistry_block(store, idx) il = store.il_id[idx] fp = store.il_fp[il].astype(np.float32) maccs = maccs_keys(store)[il] return { "base": base, "base+fp": np.concatenate([base, fp], axis=1), "base+maccs": np.concatenate([base, maccs], axis=1), "base+fp+maccs": np.concatenate([base, fp, maccs], axis=1), "fp": fp, } def make_rf(): from lnpbench.models.classical import make_random_forest return make_random_forest() def make_et(): from lnpbench.models.classical import make_extra_trees return make_extra_trees() def make_catboost(): from catboost import CatBoostRegressor return CatBoostRegressor(iterations=800, depth=6, learning_rate=0.05, l2_leaf_reg=6.0, random_seed=0, verbose=0) MAKERS = {"rf": make_rf, "et": make_et, "catboost": make_catboost} def main(): ap = argparse.ArgumentParser() ap.add_argument("--blocks", nargs="+", default=["base", "base+fp", "base+maccs"]) ap.add_argument("--models", nargs="+", default=["rf", "et"]) ap.add_argument("--out", default="results/block_v2.csv") args = ap.parse_args() store = FeatureStore() tasks = data.load_tasks(paths.CACHE_DIR / "tasks.pkl") tasks = [t for t in tasks if t.protocol == "external"] idx = np.arange(len(store)) blocks = build_blocks(store, idx) for k, v in blocks.items(): print(f"block {k:16s} {v.shape}", flush=True) rows = [] for bname in args.blocks: X = blocks[bname] for mname in args.models: for task in tasks: t0 = time.time() model = MAKERS[mname]() model.fit(X[task.train_idx], store.y[task.train_idx]) pred = model.predict(X[task.test_idx]) met = metrics.evaluate(store.y[task.test_idx], pred) rows.append({"block": bname, "model": mname, "task": task.name, "study": task.meta.get("study"), "spearman": met["spearman"], "runtime_s": round(time.time() - t0, 1)}) print(f"{bname:16s} {mname:8s} {task.name:20s} rho={met['spearman']:.4f} " f"({time.time() - t0:.0f}s)", flush=True) pd.DataFrame(rows).to_csv(args.out, index=False) df = pd.DataFrame(rows) ref = df[(df.block == "base") & (df.model == "rf")].set_index("task").spearman print("\n== 20-task mean and paired delta vs base/rf ==") for (b, m), g in df.groupby(["block", "model"]): s = g.set_index("task").spearman.reindex(ref.index).dropna() d = s - ref.reindex(s.index) p = stats.wilcoxon(d).pvalue if len(d) > 5 and np.any(d != 0) else float("nan") print(f"{b:16s} {m:8s} mean={s.mean():.4f} d={d.mean():+.4f} p={p:.3g}") if __name__ == "__main__": main()