File size: 11,446 Bytes
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""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()