File size: 7,111 Bytes
f87a628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build a FeatureStore-compatible cache for the LNP Atlas corpus.

LNP Atlas (Zenodo 17243732) is an *independent* compilation of 1,092 LNP
formulations from 62 papers, with measured particle size, PDI, zeta potential
and encapsulation efficiency.  Only 19 of its 259 ionisable lipids occur in
LNPDB, and only 3 papers overlap, so it is a genuinely external supervision
source.

The script writes a second cache directory (`cache/atlas/`) with exactly the
same file layout as the LNPDB cache, so `FeatureStore(cache_dir=...)` and every
model can be reused unchanged, plus `aux_targets.npz` holding the four
standardised property targets and their availability mask.

    python scripts/build_atlas.py --workers 16
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np
import pandas as pd
from rdkit import Chem, RDLogger

RDLogger.DisableLog("rdApp.*")

from lnpbench import paths, prepare  # noqa: E402

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "data" / "external" / "LNP_Atlas.csv"
ATLAS_CACHE = ROOT / "cache" / "atlas"

SMARTS = {
    "has_ester": "[CX3](=O)[OX2H0][#6]",
    "has_carbonate": "[OX2][CX3](=O)[OX2]",
    "has_disulfide": "[#16X2][#16X2]",
}
AUX_NAMES = ["log_size", "pdi", "zeta", "ee"]


def _flag(smi: str, patt: str) -> float:
    mol = Chem.MolFromSmiles(smi) if isinstance(smi, str) else None
    if mol is None:
        return 0.0
    return float(mol.HasSubstructMatch(Chem.MolFromSmarts(patt)))


def _ratio(s: str):
    """'50:10:38.5:1.5' -> (il, hl, chol, peg); missing entries become 0."""
    if not isinstance(s, str):
        return (np.nan, np.nan, np.nan, np.nan)
    parts = [p.strip() for p in s.replace(",", ":").split(":") if p.strip()]
    vals = []
    for p in parts:
        try:
            vals.append(float(p))
        except ValueError:
            return (np.nan, np.nan, np.nan, np.nan)
    if len(vals) != 4:
        return (np.nan, np.nan, np.nan, np.nan)
    return tuple(vals)


def build_table() -> pd.DataFrame:
    a = pd.read_csv(SRC, encoding="latin-1", low_memory=False)
    a = a[a.ionizable_lipid_smiles.notna()].reset_index(drop=True)

    ok = a.ionizable_lipid_smiles.map(lambda s: Chem.MolFromSmiles(str(s)) is not None)
    a = a[ok].reset_index(drop=True)

    ratios = np.asarray([_ratio(v) for v in a.lipid_molar_ratio], dtype=np.float64)
    df = pd.DataFrame({
        "il_smiles": a.ionizable_lipid_smiles.astype(str),
        "il_prot_smiles": a.ionizable_lipid_smiles.astype(str),
        "hl_smiles": a.helper_lipid_smiles,
        "chl_smiles": a.sterol_lipid_smiles,
        "peg_smiles": a.peg_lipid_smiles,
        "w_il_raw": ratios[:, 0],
        "w_hl_raw": ratios[:, 1],
        "w_chl_raw": ratios[:, 2],
        "w_peg_raw": ratios[:, 3],
        "il_na_ratio": np.nan,
        "dose": np.nan,
        "y": 0.0,
        "study": "ATLAS",
    })
    for slot in ("head", "linker", "tail1", "tail2", "tail3", "tail4"):
        df[slot] = None
    for c in ("has_ester", "has_carbonate", "has_disulfide"):
        df[c] = [ _flag(s, SMARTS[c]) for s in df.il_smiles ]

    # every categorical field is a single "unknown" level; the categorical
    # context path therefore contributes nothing during pretraining, which is
    # what we want -- the model can only learn from chemistry and composition.
    for col in ("Cargo", "Cargo_type", "Model_type", "Model_target", "Model",
                "Route_of_administration", "Mixing_method", "Aqueous_buffer",
                "Dialysis_buffer", "Experiment_batching", "Experiment_method"):
        df[col] = "unknown"
    df["HL_name"] = "unknown"
    df["CHL_name"] = "unknown"
    df["PEG_name"] = "unknown"
    # build_sample_features() consumes the *renamed* (lower-case) columns
    from lnpbench import data as _data

    for name, col in _data.CATEGORICAL_COLS.items():
        df[name] = df[col].astype(str)

    # data.load_samples() normalises the molar ratios and builds log features;
    # reproduce exactly the same transformations here.
    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["log_il_na_ratio"] = np.log1p(pd.to_numeric(df["il_na_ratio"], errors="coerce").clip(lower=0).fillna(0.0))
    df["log_dose"] = np.log1p(pd.to_numeric(df["dose"], errors="coerce").clip(lower=0).fillna(0.0))
    df["study_id"] = 0
    df["lnp_id"] = a.lnp_id.astype(str).to_numpy()

    # ---- auxiliary targets -------------------------------------------------
    size = pd.to_numeric(a.particle_size_nm_std, errors="coerce").to_numpy(dtype=np.float64)
    pdi = pd.to_numeric(a.pdi_std, errors="coerce").to_numpy(dtype=np.float64)
    zeta = pd.to_numeric(a.zeta_potential_mv_std, errors="coerce").to_numpy(dtype=np.float64)
    ee = pd.to_numeric(a.encapsulation_efficiency_percent_std, errors="coerce").to_numpy(dtype=np.float64)

    raw = np.stack([
        np.log10(np.clip(size, 1.0, None)),
        pdi,
        zeta,
        ee / 100.0,
    ], axis=1)
    mask = np.isfinite(raw).astype(np.float32)
    # standardise each target over the rows where it is observed
    z = np.zeros_like(raw)
    for j in range(raw.shape[1]):
        m = mask[:, j] > 0
        mu, sd = raw[m, j].mean(), raw[m, j].std() + 1e-6
        z[m, j] = (raw[m, j] - mu) / sd
    z = np.nan_to_num(z).astype(np.float32)
    return df, z, mask


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--workers", type=int, default=16)
    ap.add_argument("--force", action="store_true")
    args = ap.parse_args()

    ATLAS_CACHE.mkdir(parents=True, exist_ok=True)
    df, aux, mask = build_table()
    df = df.reset_index(drop=True)
    print(f"[atlas] {len(df)} formulations, {df.il_smiles.nunique()} unique IL")
    print("[atlas] target coverage:", {n: int(mask[:, j].sum()) for j, n in enumerate(AUX_NAMES)})

    df.to_parquet(ATLAS_CACHE / "samples.parquet", index=False)
    np.savez_compressed(ATLAS_CACHE / "aux_targets.npz",
                        aux=aux, mask=mask, names=np.array(AUX_NAMES, dtype=object))
    np.savez_compressed(ATLAS_CACHE / "md_labels.npz",
                        rows=np.array([], dtype=np.int64),
                        stable=np.array([], dtype=np.float32))

    # point the shared preparation code at the atlas cache
    paths.CACHE_DIR = ATLAS_CACHE
    prepare.build_molecule_cache(df, force=args.force, workers=args.workers)
    prepare.build_fragment_cache(df, force=args.force)
    prepare.build_sample_features(df, force=args.force)

    meta = {
        "source": "LNP Atlas v202509 (Zenodo 17243732)",
        "n_formulations": int(len(df)),
        "n_il": int(df.il_smiles.nunique()),
        "targets": AUX_NAMES,
        "coverage": {n: int(mask[:, j].sum()) for j, n in enumerate(AUX_NAMES)},
    }
    (ATLAS_CACHE / "meta.json").write_text(json.dumps(meta, indent=2))
    print("[atlas] done ->", ATLAS_CACHE)


if __name__ == "__main__":
    main()