Download code/scripts/mode_interpret.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 5.05 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/mode_interpret.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench/code/scripts/mode_interpret.py
-
curl -L -o mode_interpret.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/mode_interpret.py
5.05 kB
| """Interpret the discrete relation modes of RelMode-LNP. | |
| Trains one checkpoint, then reads the codebook assignment of every *contact* | |
| (node pair) of every held-out formulation and reports two tables. | |
| 1. **Mode usage by contact class.** Of the 45 contacts of a full formulation, | |
| how often does each mode win, split by contact class (intra-lipid fragment | |
| pairs, lipid-helper, lipid-cholesterol, lipid-PEG, helper-helper). A mode | |
| that is specific to the IL-PEG contact is doing something different from a | |
| mode that dominates intra-lipid contacts. | |
| 2. **Chemistry of each mode**, for the contacts that actually carry the lipid | |
| (every class except intra-lipid fragments): the mean cCPP of the ionisable | |
| lipid and the mean molar composition of the formulations in which the mode | |
| wins. If the modes are chemically meaningful the columns separate; if they | |
| are noise the columns are flat. | |
| PYTHONPATH=src python scripts/mode_interpret.py --model relmode_nr_w \ | |
| --study ZC_2023 --fold 0 --seed 0 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| from lnpbench import data, paths | |
| from lnpbench.registry import build_model | |
| from lnpbench.store import FeatureStore | |
| from lnpbench.trainer import TrainConfig, build_batch | |
| NODE_NAMES = ["head", "linker", "tail1", "tail2", "tail3", "tail4", "IL", "HL", "Chol", "PEG"] | |
| CLASSES = ["intra-IL", "IL-HL", "IL-Chol", "IL-PEG", "helper-helper"] | |
| def contact_class(u: int, v: int) -> str: | |
| lo, hi = min(u, v), max(u, v) | |
| if hi <= 6: | |
| return "intra-IL" | |
| if lo <= 6: | |
| return {7: "IL-HL", 8: "IL-Chol", 9: "IL-PEG"}[hi] | |
| return "helper-helper" | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--model", default="relmode_nr_w") | |
| ap.add_argument("--study", default="ZC_2023") | |
| ap.add_argument("--fold", type=int, default=0) | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--epochs", type=int, default=30) | |
| ap.add_argument("--batch-size", type=int, default=256) | |
| ap.add_argument("--out", default="results/relmode_interpret.csv") | |
| args = ap.parse_args() | |
| store = FeatureStore() | |
| tasks = data.load_tasks(paths.CACHE_DIR / "tasks.pkl") | |
| task = next(t for t in tasks if t.name == f"{args.study}_fold{args.fold}") | |
| model = build_model(args.model) | |
| cfg = TrainConfig(epochs=args.epochs, batch_size=args.batch_size, seed=args.seed, | |
| device="cuda", verbose=False) | |
| info = model.fit(store, task.train_idx, task.val_idx, cfg) | |
| mod = model.module.eval() | |
| print(f"trained {args.model} on {task.name}: val={info['best_val_spearman']:.4f}") | |
| rel = mod.enc.rel_mode | |
| K = rel.n_codes | |
| rows = [] # one row per winning contact | |
| for start in range(0, len(task.test_idx), 512): | |
| chunk = task.test_idx[start:start + 512] | |
| batch = build_batch(store, chunk, model.need(), model.device, model.norm) | |
| with torch.no_grad(): | |
| mod(batch) | |
| idx = rel.last["idx"].cpu().numpy() # [B, N, N] | |
| valid = rel.last["valid"].cpu().numpy() # [B, N, N] | |
| cpp = batch["cpp"].cpu().numpy() # [B, 16] standardised | |
| rat = batch["ratios"].cpu().numpy() # [B, 5] | |
| for u in range(10): | |
| for v in range(u + 1, 10): | |
| m = valid[:, u, v] | |
| if not m.any(): | |
| continue | |
| rows.append(pd.DataFrame({ | |
| "cls": contact_class(u, v), | |
| "mode": idx[m, u, v], | |
| "CPP_prot": cpp[m, 2], "CPP_neut": cpp[m, 1], | |
| "dCPP": cpp[m, 3], "stab": cpp[m, 4], | |
| "w_IL": rat[m, 0], "w_HL": rat[m, 1], | |
| "w_Chol": rat[m, 2], "w_PEG": rat[m, 3], | |
| })) | |
| df = pd.concat(rows, ignore_index=True) | |
| # ---- table 1: usage per contact class -------------------------------- | |
| usage = (df.groupby(["cls", "mode"]).size().unstack(fill_value=0) | |
| .reindex(CLASSES).reindex(columns=range(K), fill_value=0)) | |
| share = usage.div(usage.sum(1), axis=0) | |
| print("\n== mode usage by contact class (row = share of contacts) ==") | |
| print((share * 100).round(1).to_string()) | |
| # ---- table 2: chemistry of each mode -------------------------------- | |
| lipid = df[df.cls != "intra-IL"] | |
| chem = lipid.groupby("mode")[["CPP_prot", "CPP_neut", "dCPP", "stab", | |
| "w_IL", "w_HL", "w_Chol", "w_PEG"]].mean() | |
| chem["n"] = lipid.groupby("mode").size() | |
| chem["share"] = chem["n"] / len(lipid) | |
| chem = chem.reindex(range(K)) | |
| print("\n== chemistry of each mode (lipid-carrying contacts only) ==") | |
| print(chem.round(3).to_string()) | |
| df.groupby(["cls", "mode"]).size().rename("n").reset_index().to_csv( | |
| args.out.replace(".csv", "_usage.csv"), index=False) | |
| chem.to_csv(args.out, index=False) | |
| print("\nwrote", args.out, "and", args.out.replace(".csv", "_usage.csv")) | |
| if __name__ == "__main__": | |
| main() |