Download code/src/lnpbench/prepare.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/src/lnpbench/prepare.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench/code/src/lnpbench/prepare.py
-
curl -L -o prepare.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/src/lnpbench/prepare.py
11.4 kB
| """Build the on-disk feature cache used by every experiment. | |
| Run ``python -m lnpbench.prepare --stage all`` (or the individual stages) once. | |
| Every downstream script only reads the cache, so experiments are bit-for-bit | |
| reproducible given the same cache. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import pickle | |
| from concurrent.futures import ProcessPoolExecutor | |
| from pathlib import Path | |
| from typing import Dict, List | |
| import numpy as np | |
| import pandas as pd | |
| from rdkit import Chem, RDLogger | |
| from . import data, featurize, paths | |
| from .cpp import compute_cpp_features | |
| RDLogger.DisableLog("rdApp.*") | |
| MAX_TOKENS = 256 | |
| # --------------------------------------------------------------------------- | |
| # Stage 1: sample table | |
| # --------------------------------------------------------------------------- | |
| def build_table(force: bool = False) -> pd.DataFrame: | |
| out = paths.CACHE_DIR / "samples.parquet" | |
| if out.exists() and not force: | |
| return pd.read_parquet(out).reset_index(drop=True) | |
| df = data.load_samples() | |
| # drop formulations whose ionizable lipid cannot be parsed | |
| ok = df["il_smiles"].map(lambda s: Chem.MolFromSmiles(s) is not None if isinstance(s, str) else False) | |
| dropped = int((~ok).sum()) | |
| df = df[ok].reset_index(drop=True) | |
| df.to_parquet(out, index=False) | |
| print(f"[table] {len(df)} formulations ({dropped} unparsable SMILES dropped)") | |
| return df | |
| # --------------------------------------------------------------------------- | |
| # Stage 2: per-molecule features | |
| # --------------------------------------------------------------------------- | |
| def _mol_features(args): | |
| smiles, smiles_prot, head = args | |
| fp = featurize.morgan_fp(smiles) | |
| desc = featurize.rdkit_descriptors(smiles) | |
| return fp, desc | |
| def _cpp_features(args): | |
| smiles, smiles_prot, head = args | |
| return compute_cpp_features(smiles, smiles_prot, head) | |
| def build_molecule_cache(df: pd.DataFrame, force: bool = False, workers: int = 32) -> None: | |
| vocab_path = paths.CACHE_DIR / "il_vocab.json" | |
| smiles = sorted(df["il_smiles"].unique().tolist()) | |
| index = {s: i for i, s in enumerate(smiles)} | |
| with open(vocab_path, "w") as fh: | |
| json.dump(smiles, fh) | |
| # a representative row per unique ionizable lipid (for the protonated SMILES / head) | |
| rep = df.drop_duplicates("il_smiles").set_index("il_smiles") | |
| prot = [rep.loc[s, "il_prot_smiles"] if isinstance(rep.loc[s, "il_prot_smiles"], str) else None for s in smiles] | |
| head = [rep.loc[s, "head"] if isinstance(rep.loc[s, "head"], str) else None for s in smiles] | |
| if not (paths.CACHE_DIR / "il_fp.npy").exists() or force: | |
| fp = np.zeros((len(smiles), featurize.MORGAN_BITS), dtype=np.uint8) | |
| for i, s in enumerate(smiles): | |
| fp[i] = featurize.morgan_fp(s) | |
| np.save(paths.CACHE_DIR / "il_fp.npy", fp) | |
| print(f"[mol] fingerprints {fp.shape}") | |
| if not (paths.CACHE_DIR / "il_desc.npy").exists() or force: | |
| desc = np.zeros((len(smiles), len(featurize.descriptor_names())), dtype=np.float32) | |
| for i, s in enumerate(smiles): | |
| desc[i] = featurize.rdkit_descriptors(s) | |
| desc = np.nan_to_num(desc, nan=0.0, posinf=0.0, neginf=0.0) | |
| np.save(paths.CACHE_DIR / "il_desc.npy", desc) | |
| with open(paths.CACHE_DIR / "il_desc_names.json", "w") as fh: | |
| json.dump(featurize.descriptor_names(), fh) | |
| print(f"[mol] descriptors {desc.shape}") | |
| if not (paths.CACHE_DIR / "il_graphs.pkl").exists() or force: | |
| graphs = [featurize.mol_to_graph(s) for s in smiles] | |
| with open(paths.CACHE_DIR / "il_graphs.pkl", "wb") as fh: | |
| pickle.dump(graphs, fh) | |
| print(f"[mol] graphs {len(graphs)}") | |
| if not (paths.CACHE_DIR / "il_tokens.npz").exists() or force: | |
| vocab = featurize.build_vocab(smiles) | |
| tokens = np.zeros((len(smiles), MAX_TOKENS), dtype=np.int64) | |
| lengths = np.zeros(len(smiles), dtype=np.int64) | |
| for i, s in enumerate(smiles): | |
| tokens[i], lengths[i] = featurize.encode_tokens(s, vocab, MAX_TOKENS) | |
| np.savez_compressed(paths.CACHE_DIR / "il_tokens.npz", tokens=tokens, lengths=lengths) | |
| with open(paths.CACHE_DIR / "token_vocab.json", "w") as fh: | |
| json.dump(vocab, fh) | |
| print(f"[mol] tokens {tokens.shape} vocab={len(vocab)}") | |
| cpp_path = paths.CACHE_DIR / "il_cpp.npy" | |
| if not cpp_path.exists() or force: | |
| tasks = list(zip(smiles, prot, head)) | |
| block = 1000 | |
| part_dir = paths.CACHE_DIR / "cpp_parts" | |
| part_dir.mkdir(exist_ok=True) | |
| n_blocks = (len(tasks) + block - 1) // block | |
| for b in range(n_blocks): | |
| part = part_dir / f"part_{b:03d}.npy" | |
| if part.exists(): | |
| continue | |
| lo, hi = b * block, min((b + 1) * block, len(tasks)) | |
| arr = np.zeros((hi - lo, 16), dtype=np.float32) | |
| with ProcessPoolExecutor(max_workers=workers) as ex: | |
| for i, vec in enumerate(ex.map(_cpp_features, tasks[lo:hi], chunksize=8)): | |
| arr[i] = vec | |
| np.save(part, arr) | |
| print(f"[cpp] block {b + 1}/{n_blocks} done ({hi}/{len(tasks)})", flush=True) | |
| parts = [np.load(part_dir / f"part_{b:03d}.npy") for b in range(n_blocks)] | |
| cpp = np.concatenate(parts, axis=0) | |
| np.save(cpp_path, cpp) | |
| print(f"[mol] cCPP {cpp.shape}") | |
| def build_fragment_cache(df: pd.DataFrame, force: bool = False) -> None: | |
| """Fingerprint + physchem cache for each hierarchy slot and the helper lipids.""" | |
| slots = list(data.FRAGMENT_SLOTS) + ["HL", "CHL", "PEG"] | |
| for slot in slots: | |
| out = paths.CACHE_DIR / f"frag_{slot}.npz" | |
| if out.exists() and not force: | |
| continue | |
| col = "hl_smiles" if slot == "HL" else "chl_smiles" if slot == "CHL" else "peg_smiles" if slot == "PEG" else slot | |
| values = sorted({v for v in df[col].tolist() if isinstance(v, str) and v}) | |
| fp = np.zeros((len(values), featurize.MORGAN_BITS), dtype=np.uint8) | |
| phys = np.zeros((len(values), 12), dtype=np.float32) | |
| for i, s in enumerate(values): | |
| fp[i] = featurize.morgan_fp(s) | |
| phys[i] = featurize.fragment_physchem(s) | |
| np.savez_compressed(out, smiles=np.array(values, dtype=object), fp=fp, phys=phys, allow_pickle=True) | |
| print(f"[frag] {slot}: {len(values)} unique") | |
| # --------------------------------------------------------------------------- | |
| # Stage 3: per-sample index + context tensors | |
| # --------------------------------------------------------------------------- | |
| def build_sample_features(df: pd.DataFrame, force: bool = False) -> None: | |
| out = paths.CACHE_DIR / "sample_features.npz" | |
| if out.exists() and not force: | |
| return | |
| il_vocab = json.load(open(paths.CACHE_DIR / "il_vocab.json")) | |
| il_index = {s: i for i, s in enumerate(il_vocab)} | |
| def frag_index(slot: str, col: str): | |
| vals = np.load(paths.CACHE_DIR / f"frag_{slot}.npz", allow_pickle=True)["smiles"].tolist() | |
| m = {v: i for i, v in enumerate(vals)} | |
| return np.array([m.get(v, -1) if isinstance(v, str) else -1 for v in df[col]], dtype=np.int64) | |
| il_id = np.array([il_index[s] for s in df["il_smiles"]], dtype=np.int64) | |
| frag_ids = np.stack( | |
| [frag_index(slot, slot) for slot in data.FRAGMENT_SLOTS] + [np.full(len(df), -1, dtype=np.int64)], axis=1 | |
| ) # [N, 7] slot 6 reserved for the whole-molecule node | |
| hl_id = frag_index("HL", "hl_smiles") | |
| chl_id = frag_index("CHL", "chl_smiles") | |
| peg_id = frag_index("PEG", "peg_smiles") | |
| # context: one-hot categoricals + standardised numerics | |
| ctx_parts: List[np.ndarray] = [] | |
| vocab_meta: Dict[str, List[str]] = {} | |
| for name in data.CATEGORICAL_COLS: | |
| cats = sorted(df[name].astype(str).unique().tolist()) | |
| vocab_meta[name] = cats | |
| m = {c: i for i, c in enumerate(cats)} | |
| onehot = np.zeros((len(df), len(cats)), dtype=np.float32) | |
| onehot[np.arange(len(df)), df[name].map(m).to_numpy()] = 1.0 | |
| ctx_parts.append(onehot) | |
| numeric = np.stack( | |
| [ | |
| df["w_il"].to_numpy(), | |
| df["w_hl"].to_numpy(), | |
| df["w_chl"].to_numpy(), | |
| df["w_peg"].to_numpy(), | |
| df["log_il_na_ratio"].to_numpy(), | |
| df["log_dose"].to_numpy(), | |
| df["has_ester"].to_numpy(), | |
| df["has_carbonate"].to_numpy(), | |
| df["has_disulfide"].to_numpy(), | |
| ], | |
| axis=1, | |
| ).astype(np.float32) | |
| numeric = (numeric - numeric.mean(0)) / (numeric.std(0) + 1e-6) | |
| ctx_parts.append(numeric) | |
| ratios = np.stack( | |
| [df["w_il"], df["w_hl"], df["w_chl"], df["w_peg"], df["log_il_na_ratio"] / 5.0], axis=1 | |
| ).astype(np.float32) | |
| np.savez_compressed( | |
| out, | |
| y=df["y"].to_numpy(np.float32), | |
| study_id=df["study_id"].to_numpy(np.int64), | |
| il_id=il_id, | |
| frag_ids=frag_ids, | |
| frag_mask=(frag_ids >= 0).astype(np.float32), | |
| helper_ids=np.stack([hl_id, chl_id, peg_id], axis=1), | |
| helper_mask=(np.stack([hl_id, chl_id, peg_id], axis=1) >= 0).astype(np.float32), | |
| ratios=ratios, | |
| ctx=np.concatenate(ctx_parts, axis=1).astype(np.float32), | |
| ctx_dim=np.array([sum(p.shape[1] for p in ctx_parts)], dtype=np.int64), | |
| vocab_json=np.array([json.dumps(vocab_meta)], dtype=object), | |
| allow_pickle=True, | |
| ) | |
| print(f"[sample] {len(df)} rows, ctx dim {sum(p.shape[1] for p in ctx_parts)}") | |
| def build_tasks(df: pd.DataFrame, force: bool = False) -> None: | |
| out = paths.CACHE_DIR / "tasks.pkl" | |
| if out.exists() and not force: | |
| return | |
| df = df.reset_index(drop=True) | |
| tasks = data.build_tasks(df, ["external", "amine", "cv5"]) | |
| data.save_tasks(tasks, out) | |
| print(f"[tasks] {len(tasks)} tasks") | |
| for t in tasks: | |
| print(f" {t.signature():32s} train={len(t.train_idx):6d} val={len(t.val_idx):5d} test={len(t.test_idx):5d}") | |
| def build_md_labels(df: pd.DataFrame) -> None: | |
| """Stability labels for the 54 LM_2019 bilayer simulations (Method B aux head).""" | |
| md = pd.read_csv(paths.MD_STABILITY_CSV) | |
| id_to_row = {v: i for i, v in enumerate(df["LNP_ID"])} | |
| rows, labels = [], [] | |
| for _, r in md.iterrows(): | |
| if r.LNP_ID in id_to_row: | |
| rows.append(id_to_row[r.LNP_ID]) | |
| labels.append(float(r["stable"])) | |
| np.savez(paths.CACHE_DIR / "md_labels.npz", rows=np.asarray(rows, dtype=np.int64), stable=np.asarray(labels, dtype=np.float32)) | |
| print(f"[md] {len(rows)} labelled bilayers ({int(np.sum(labels))} stable)") | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--stage", default="all", choices=["table", "mol", "frag", "sample", "tasks", "md", "all"]) | |
| ap.add_argument("--force", action="store_true") | |
| ap.add_argument("--workers", type=int, default=32) | |
| args = ap.parse_args() | |
| df = build_table(force=args.force) | |
| if args.stage in ("frag", "all"): | |
| build_fragment_cache(df, force=args.force) | |
| if args.stage in ("mol", "all"): | |
| build_molecule_cache(df, force=args.force, workers=args.workers) | |
| if args.stage in ("sample", "all"): | |
| build_sample_features(df, force=args.force) | |
| if args.stage in ("tasks", "all"): | |
| build_tasks(df, force=args.force) | |
| if args.stage in ("md", "all"): | |
| build_md_labels(df) | |
| if __name__ == "__main__": | |
| main() |