File size: 10,734 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""LNPDB loading, canonicalisation and benchmark split reconstruction.

The unit of analysis is *one LNP formulation*.  The prediction target is the
per-study standardised delivery readout shipped with LNPDB (``Experiment_value``).
Because the primary metric used throughout the field is Spearman rank
correlation, the per-study standardisation does not leak information into the
ranking metric.
"""

from __future__ import annotations

import pickle
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Iterable, List, Sequence, Tuple

import numpy as np
import pandas as pd

from . import paths

# ---------------------------------------------------------------------------
# Column contract
# ---------------------------------------------------------------------------

FRAGMENT_SLOTS = ("head", "linker", "tail1", "tail2", "tail3", "tail4")

FRAGMENT_COLS = {
    "head": "IL_head_SMILES",
    "linker": "IL_linker_SMILES",
    "tail1": "IL_tail1_SMILES",
    "tail2": "IL_tail2_SMILES",
    "tail3": "IL_tail3_SMILES",
    "tail4": "IL_tail4_SMILES",
}

CATEGORICAL_COLS = {
    "cargo": "Cargo",
    "cargo_type": "Cargo_type",
    "model_type": "Model_type",
    "model_target": "Model_target",
    "model": "Model",
    "route": "Route_of_administration",
    "mixing": "Mixing_method",
    "buffer_aq": "Aqueous_buffer",
    "buffer_dial": "Dialysis_buffer",
    "batching": "Experiment_batching",
    "readout": "Experiment_method",
    "hl_name": "HL_name",
    "chl_name": "CHL_name",
    "peg_name": "PEG_name",
}


def _clean_smiles(series: pd.Series) -> pd.Series:
    out = series.astype("object").where(series.notna(), None)
    return out.map(lambda v: None if not isinstance(v, str) or v.strip() in {"", "NA", "nan"} else v.strip())


def load_samples(lnpdb_csv: Path | None = None, all_csv: Path | None = None) -> pd.DataFrame:
    """Load the 18,858 evaluable LNPDB formulations with all modelling fields."""
    lnpdb_csv = Path(lnpdb_csv or paths.LNPDB_CSV)
    all_csv = Path(all_csv or paths.ALL_DATA_CSV)

    base = pd.read_csv(all_csv)
    extra = pd.read_csv(lnpdb_csv, low_memory=False)
    keep = [
        "LNP_ID",
        "IL_protonated_SMILES",
        "IL_head_SMILES",
        "IL_linker_SMILES",
        "IL_tail1_SMILES",
        "IL_tail2_SMILES",
        "IL_tail3_SMILES",
        "IL_tail4_SMILES",
        "HL_SMILES",
        "CHL_SMILES",
        "PEG_SMILES",
        "Aqueous_buffer",
        "Dialysis_buffer",
        "Model",
        "Route_of_administration",
        "Experiment_method",
        "Dose_ug_nucleicacid",
        "fifthcomponent_name",
        "fifthcomponent_molratio",
        "has_ester",
        "has_carbonate",
        "has_disulfide",
        "LogP",
        "Molecular.Weight",
        "Hydrogen.Bond.Donors",
        "Hydrogen.Bond.Acceptors",
        "Topological.Polar.Surface.Area",
        "Rotatable.Bonds",
        "Fraction.sp3.Carbons",
        "Nitrogen.Count",
    ]
    shared = [c for c in keep if c in base.columns and c != "LNP_ID"]
    extra = extra[[c for c in keep if c not in shared]].drop_duplicates("LNP_ID")
    df = base.merge(extra, on="LNP_ID", how="left", validate="one_to_one")
    assert len(df) == len(base), "merge changed the number of formulations"

    df = df.rename(
        columns={
            "IL_SMILES": "il_smiles",
            "IL_protonated_SMILES": "il_prot_smiles",
            "HL_SMILES": "hl_smiles",
            "CHL_SMILES": "chl_smiles",
            "PEG_SMILES": "peg_smiles",
            "Experiment_value": "y",
            "Experiment_ID": "study",
            "IL_molratio": "w_il_raw",
            "HL_molratio": "w_hl_raw",
            "CHL_molratio": "w_chl_raw",
            "PEG_molratio": "w_peg_raw",
            "IL_to_nucleicacid_massratio": "il_na_ratio",
            "Dose_ug_nucleicacid": "dose",
        }
    )
    for slot, col in FRAGMENT_COLS.items():
        df[slot] = _clean_smiles(df[col])
    for name, col in CATEGORICAL_COLS.items():
        df[name] = df[col].astype("object").where(df[col].notna(), "NA").astype(str)

    # molar fractions (row-wise normalised over the four canonical components)
    w = df[["w_il_raw", "w_hl_raw", "w_chl_raw", "w_peg_raw"]].fillna(0.0).clip(lower=0.0)
    total = w.sum(axis=1).replace(0.0, np.nan)
    w = w.div(total, axis=0).fillna(0.0)
    df[["w_il", "w_hl", "w_chl", "w_peg"]] = w.to_numpy()

    df["il_na_ratio"] = pd.to_numeric(df["il_na_ratio"], errors="coerce")
    df["dose"] = pd.to_numeric(df["dose"], errors="coerce")
    df["log_il_na_ratio"] = np.log1p(df["il_na_ratio"].clip(lower=0.0)).fillna(0.0)
    df["log_dose"] = np.log1p(df["dose"].clip(lower=0.0)).fillna(0.0)

    for flag in ("has_ester", "has_carbonate", "has_disulfide"):
        df[flag] = df[flag].astype(str).str.upper().isin({"TRUE", "1", "1.0"}).astype(np.float32)

    # index of the study, used for domain-adversarial / GroupDRO objectives
    studies = sorted(df["study"].unique().tolist())
    df["study_id"] = df["study"].map({s: i for i, s in enumerate(studies)}).astype(np.int64)
    df = df.reset_index(drop=True)
    df.attrs["studies"] = studies
    return df


# ---------------------------------------------------------------------------
# Split reconstruction
# ---------------------------------------------------------------------------


def _match_rows(pool: pd.DataFrame, split: pd.DataFrame) -> np.ndarray:
    """Map a (SMILES, value) split file onto positional row ids of ``pool``.

    LNPDB ships split files that only contain the SMILES string and the target
    value.  Duplicate (SMILES, value) pairs are interchangeable for training, so
    a multiset assignment recovers the exact membership.
    """
    buckets: Dict[Tuple[str, float], List[int]] = {}
    for idx, smi, val in zip(pool.index.to_numpy(), pool["il_smiles"], pool["y"]):
        buckets.setdefault((smi, round(float(val), 6)), []).append(int(idx))
    out: List[int] = []
    missing = 0
    for smi, val in zip(split["IL_SMILES"], split["Experiment_value"]):
        key = (smi, round(float(val), 6))
        bucket = buckets.get(key)
        if not bucket:
            missing += 1
            continue
        out.append(bucket.pop())
    if missing:
        raise ValueError(f"{missing} rows of the split file could not be matched")
    return np.asarray(out, dtype=np.int64)


@dataclass
class Task:
    """One train/val/test problem instance."""

    name: str
    protocol: str
    train_idx: np.ndarray
    val_idx: np.ndarray
    test_idx: np.ndarray
    meta: dict = field(default_factory=dict)

    def signature(self) -> str:
        return f"{self.protocol}::{self.name}"


def external_tasks(df: pd.DataFrame, studies: Iterable[str] = paths.EXTERNAL_STUDIES) -> List[Task]:
    """Fully held-out study x 5-fold CV on the remaining database (LNPDB Fig. 3b)."""
    tasks: List[Task] = []
    for study in studies:
        pool = df[df["study"] != study]
        held = df[df["study"] == study]
        for fold in range(5):
            cv_dir = paths.HELDOUT_DIR / f"heldout_{study}" / "cv_splits" / f"cv_{fold}"
            if not cv_dir.exists():
                raise FileNotFoundError(cv_dir)
            tr = pd.read_csv(cv_dir / "train.csv")
            te = pd.read_csv(cv_dir / "test.csv")
            train_idx = _match_rows(pool, tr)
            val_idx = _match_rows(pool, te)
            tasks.append(
                Task(
                    name=f"{study}_fold{fold}",
                    protocol="external",
                    train_idx=np.sort(train_idx),
                    val_idx=np.sort(val_idx),
                    test_idx=held.index.to_numpy(),
                    meta={"study": study, "fold": fold, "n_train": int(len(train_idx))},
                )
            )
    return tasks


def single_split_task(df: pd.DataFrame) -> Task:
    """70/15/15 amine-disjoint split used for the LNPDB Fig. 3a comparison."""
    tr = pd.read_csv(paths.SINGLE_SPLIT_DIR / "train.csv")
    va = pd.read_csv(paths.SINGLE_SPLIT_DIR / "val.csv")
    te = pd.read_csv(paths.SINGLE_SPLIT_DIR / "test.csv")
    return Task(
        name="amine_70_15_15",
        protocol="amine",
        train_idx=np.sort(_match_rows(df, tr)),
        val_idx=np.sort(_match_rows(df, va)),
        test_idx=np.sort(_match_rows(df, te)),
        meta={"n_train": int(len(tr))},
    )


def cv5_tasks(df: pd.DataFrame, n_folds: int = 5, seed: int = 2026) -> List[Task]:
    """Study-stratified 5-fold cross-validation over the full database."""
    rng = np.random.default_rng(seed)
    fold_of = np.zeros(len(df), dtype=np.int64)
    for study, idx in df.groupby("study").indices.items():
        idx = np.asarray(idx)
        perm = rng.permutation(len(idx))
        fold_of[idx[perm]] = np.arange(len(idx)) % n_folds
    tasks = []
    for k in range(n_folds):
        test_idx = np.where(fold_of == k)[0]
        rest = np.where(fold_of != k)[0]
        # inner validation split (10% of the remaining data), stratified by study
        rng2 = np.random.default_rng(seed + 101 * (k + 1))
        val_mask = np.zeros(len(rest), dtype=bool)
        rest_studies = df.iloc[rest]["study"].to_numpy()
        for study in np.unique(rest_studies):
            sel = np.where(rest_studies == study)[0]
            n_val = max(1, int(round(0.1 * len(sel))))
            val_mask[rng2.permutation(sel)[:n_val]] = True
        tasks.append(
            Task(
                name=f"cv5_fold{k}",
                protocol="cv5",
                train_idx=np.sort(rest[~val_mask]),
                val_idx=np.sort(rest[val_mask]),
                test_idx=np.sort(test_idx),
            )
        )
    return tasks


def build_tasks(df: pd.DataFrame, protocols: Sequence[str]) -> List[Task]:
    tasks: List[Task] = []
    for p in protocols:
        if p == "external":
            tasks.extend(external_tasks(df))
        elif p == "amine":
            tasks.append(single_split_task(df))
        elif p == "cv5":
            tasks.extend(cv5_tasks(df))
        else:  # pragma: no cover - defensive
            raise ValueError(f"unknown protocol {p!r}")
    return tasks


def save_tasks(tasks: Sequence[Task], path: Path) -> None:
    with open(path, "wb") as fh:
        pickle.dump([
            {
                "name": t.name,
                "protocol": t.protocol,
                "train_idx": t.train_idx,
                "val_idx": t.val_idx,
                "test_idx": t.test_idx,
                "meta": t.meta,
            }
            for t in tasks
        ], fh)


def load_tasks(path: Path) -> List[Task]:
    with open(path, "rb") as fh:
        raw = pickle.load(fh)
    return [Task(**r) for r in raw]