File size: 10,083 Bytes
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f87a628
 
 
 
 
 
 
 
 
 
 
 
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dedf737
 
 
 
 
 
 
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
f87a628
 
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
"""Feature store: single access point for cached tensors + graph batching."""

from __future__ import annotations

import json
import pickle
from pathlib import Path
from typing import Dict, List, Sequence

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

from . import data, featurize, paths

RDLogger.DisableLog("rdApp.*")


# unified 16-dim physical descriptor layout
PHYS_NAMES = [
    "logp", "charge", "hbd", "hba", "ccpp", "dccpp", "asphericity", "pmi1",
    "inertial", "tpsa", "mw", "rot", "nn", "frac_csp3", "tail_carbons", "heavy",
]


def _frag_phys16(phys12: np.ndarray) -> np.ndarray:
    out = np.zeros((len(phys12), 16), dtype=np.float32)
    out[:, 0] = phys12[:, 1] * 5.0     # logP
    out[:, 1] = phys12[:, 8]           # nitrogen count (charge proxy)
    out[:, 2] = phys12[:, 3]           # HBD
    out[:, 3] = phys12[:, 4]           # HBA
    out[:, 9] = phys12[:, 2]           # TPSA
    out[:, 10] = phys12[:, 0]          # MW
    out[:, 11] = phys12[:, 5]          # rotatable bonds
    out[:, 12] = phys12[:, 8]          # N count
    out[:, 13] = phys12[:, 10]         # fraction sp3
    out[:, 15] = phys12[:, 11]         # heavy atoms
    return out


class FeatureStore:
    def __init__(self, cache_dir: Path | None = None):
        self.cache = Path(cache_dir or paths.CACHE_DIR)
        self.samples = pd.read_parquet(self.cache / "samples.parquet").reset_index(drop=True)
        f = np.load(self.cache / "sample_features.npz", allow_pickle=True)
        self.y = f["y"].astype(np.float32)
        self.study_id = f["study_id"].astype(np.int64)
        self.il_id = f["il_id"].astype(np.int64)
        self.frag_ids = f["frag_ids"].astype(np.int64)
        self.frag_mask = f["frag_mask"].astype(np.float32)
        self.helper_ids = f["helper_ids"].astype(np.int64)
        self.helper_mask = f["helper_mask"].astype(np.float32)
        self.ratios = f["ratios"].astype(np.float32)
        self.ctx = f["ctx"].astype(np.float32)
        self.ctx_dim = int(f["ctx_dim"][0])
        self.ctx_vocab = json.loads(str(f["vocab_json"][0]))

        self.il_fp = np.load(self.cache / "il_fp.npy")
        self.il_desc = np.clip(np.load(self.cache / "il_desc.npy"), -1e6, 1e6)
        self.il_cpp = np.load(self.cache / "il_cpp.npy")
        self.il_desc_names: List[str] = json.load(open(self.cache / "il_desc_names.json"))
        self.il_smiles: List[str] = json.load(open(self.cache / "il_vocab.json"))
        with open(self.cache / "il_graphs.pkl", "rb") as fh:
            self.il_graphs = pickle.load(fh)
        tok = np.load(self.cache / "il_tokens.npz")
        self.il_tokens = tok["tokens"]
        self.il_token_len = tok["lengths"]
        self.token_vocab: Dict[str, int] = json.load(open(self.cache / "token_vocab.json"))

        self.frag: Dict[str, dict] = {}
        for slot in list(data.FRAGMENT_SLOTS) + ["HL", "CHL", "PEG"]:
            z = np.load(self.cache / f"frag_{slot}.npz", allow_pickle=True)
            self.frag[slot] = {"fp": z["fp"], "phys": z["phys"], "smiles": z["smiles"].tolist()}

        self.studies: List[str] = sorted(self.samples["study"].unique().tolist())
        self.n_studies = len(self.studies)

        # optional external multi-task targets (one column per property)
        aux_path = self.cache / "aux_targets.npz"
        if aux_path.exists():
            z = np.load(aux_path, allow_pickle=True)
            self.aux = z["aux"].astype(np.float32)
            self.aux_mask = z["mask"].astype(np.float32)
            self.aux_names = [str(v) for v in z["names"]]
        else:
            self.aux = np.zeros((len(self.samples), 0), dtype=np.float32)
            self.aux_mask = np.zeros((len(self.samples), 0), dtype=np.float32)
            self.aux_names = []

        md = np.load(self.cache / "md_labels.npz")
        self.md_rows = md["rows"]
        self.md_stable = md["stable"]
        self.md_flag = np.zeros(len(self.samples), dtype=np.float32)
        self.md_flag[self.md_rows] = 1.0

        self._build_unified_physics()

    # ------------------------------------------------------------------
    def _build_unified_physics(self) -> None:
        path = self.cache / "unified_phys.npz"
        if path.exists():
            z = np.load(path)
            self.il_phys = z["il_phys"]
            self.frag_phys = {k: z[f"frag_{k}"] for k in self.frag}
            return

        il_phys = np.zeros((len(self.il_smiles), 16), dtype=np.float32)
        il_phys[:, 0] = self.il_cpp[:, 9]
        il_phys[:, 1] = self.il_cpp[:, 13]
        il_phys[:, 4] = self.il_cpp[:, 2]
        il_phys[:, 5] = self.il_cpp[:, 4]
        il_phys[:, 6] = self.il_cpp[:, 6]
        il_phys[:, 7] = np.log1p(np.clip(self.il_cpp[:, 7], 0, None))
        il_phys[:, 8] = self.il_cpp[:, 8]
        il_phys[:, 9] = self.il_cpp[:, 10]
        il_phys[:, 10] = self.il_cpp[:, 11]
        il_phys[:, 11] = self.il_cpp[:, 12]
        il_phys[:, 12] = self.il_cpp[:, 13]
        il_phys[:, 13] = self.il_cpp[:, 15]
        il_phys[:, 14] = self.il_cpp[:, 14]
        for i, smi in enumerate(self.il_smiles):
            mol = Chem.MolFromSmiles(smi)
            if mol is None:
                continue
            try:
                from rdkit.Chem import rdMolDescriptors

                il_phys[i, 2] = rdMolDescriptors.CalcNumHBD(mol) / 5.0
                il_phys[i, 3] = rdMolDescriptors.CalcNumHBA(mol) / 10.0
                il_phys[i, 15] = mol.GetNumHeavyAtoms() / 100.0
            except Exception:
                pass
        frag_phys = {k: _frag_phys16(v["phys"]) for k, v in self.frag.items()}
        np.savez_compressed(path, il_phys=il_phys, **{f"frag_{k}": v for k, v in frag_phys.items()})
        self.il_phys = il_phys
        self.frag_phys = frag_phys

    # ------------------------------------------------------------------
    def __len__(self) -> int:
        return len(self.samples)

    def frag_fp32(self, slot: str) -> np.ndarray:
        """Float32 copy of a fragment fingerprint table, built once per process.

        Converting the whole table on every mini-batch dominated the runtime of
        the set-based models (the tables hold up to tens of thousands of rows),
        so the conversion is memoised on the store instance.
        """
        memo = getattr(self, "_frag_fp32_memo", None)
        if memo is None:
            memo = self._frag_fp32_memo = {}
        if slot not in memo:
            memo[slot] = np.ascontiguousarray(self.frag[slot]["fp"], dtype=np.float32)
        return memo[slot]

    def protonated_fp(self) -> np.ndarray:
        """Morgan fingerprints of the +1e protonated ionizable lipids (Method B)."""
        memo = getattr(self, "_fp_prot_memo", None)
        if memo is not None:
            return memo
        path = self.cache / "il_fp_prot.npy"
        if path.exists():
            self._fp_prot_memo = np.load(path)
            return self._fp_prot_memo
        rep = self.samples.drop_duplicates("il_smiles").set_index("il_smiles")
        out = np.zeros_like(self.il_fp)
        for i, smi in enumerate(self.il_smiles):
            if smi in rep.index:
                ps = rep.loc[smi, "il_prot_smiles"]
                if isinstance(ps, str):
                    out[i] = featurize.morgan_fp(ps)
        np.save(path, out)
        self._fp_prot_memo = out
        return out

    # ------------------------------------------------------------------
    def il_fp_float(self) -> np.ndarray:
        if not hasattr(self, "_il_fp_float"):
            self._il_fp_float = self.il_fp.astype(np.float32)
        return self._il_fp_float

    # ------------------------------------------------------------------
    def collate_graphs(self, il_ids: Sequence[int], device: torch.device) -> dict:
        xs, eis, eas, batches = [], [], [], []
        offset = 0
        for b, gid in enumerate(il_ids):
            g = self.il_graphs[gid]
            x = g["x"]
            xs.append(x)
            ei = g["edge_index"]
            if ei.shape[1]:
                eis.append(ei + offset)
                eas.append(g["edge_attr"])
            offset += x.shape[0]
            batches.append(np.full(x.shape[0], b, dtype=np.int64))
        x = torch.from_numpy(np.concatenate(xs, axis=0)).to(device)
        batch = torch.from_numpy(np.concatenate(batches, axis=0)).to(device)
        if eis:
            edge_index = torch.from_numpy(np.concatenate(eis, axis=1)).to(device)
            edge_attr = torch.from_numpy(np.concatenate(eas, axis=0)).to(device)
        else:
            edge_index = torch.zeros((2, 0), dtype=torch.long, device=device)
            edge_attr = torch.zeros((0, featurize.BOND_DIM), dtype=torch.float32, device=device)
        return {"x": x, "edge_index": edge_index, "edge_attr": edge_attr, "batch": batch, "n_graphs": len(il_ids)}

    # ------------------------------------------------------------------
    def _md_stable_lookup(self, idx: np.ndarray) -> np.ndarray:
        mapping = {int(r): float(s) for r, s in zip(self.md_rows, self.md_stable)}
        return np.asarray([mapping.get(int(i), 0.0) for i in idx], dtype=np.float32)

    def global_codebook(self) -> np.ndarray:
        """Label-free archetype coordinates for every row (see global_rep)."""
        if not hasattr(self, "_glob_cb"):
            z = np.load(self.cache / "schema_blocks.npz")
            self._glob_cb = z["cb"].astype(np.float32)
        return self._glob_cb

    def subset(self, idx: np.ndarray) -> dict:
        idx = np.asarray(idx)
        return {
            "idx": idx,
            "y": self.y[idx],
            "il_id": self.il_id[idx],
            "frag_ids": self.frag_ids[idx],
            "helper_ids": self.helper_ids[idx],
            "ratios": self.ratios[idx],
            "ctx": self.ctx[idx],
            "study_id": self.study_id[idx],
            "md_flag": self.md_flag[idx],
            "md_stable": np.where(self.md_flag[idx] > 0, self._md_stable_lookup(idx), 0.0),
            "aux": self.aux[idx],
            "aux_mask": self.aux_mask[idx],
        }