File size: 8,912 Bytes
db32e07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import ctypes
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, List

import numpy as np
from numpy.lib.format import open_memmap
from tqdm import tqdm

from .embeddings import l2_normalize


@dataclass
class FLAREMolEmbedder:
    flare_repo: str
    hparams_pth: str
    checkpoint_pth: str
    device: str = "cpu"
    batch_size: int = 256
    normalize: bool = True

    def _load(self):
        libstdcpp = Path(sys.executable).resolve().parent.parent / "lib" / "libstdc++.so.6"
        if libstdcpp.exists():
            ctypes.CDLL(str(libstdcpp), mode=ctypes.RTLD_GLOBAL)

        import dgl
        import torch
        import yaml

        flare_repo = Path(self.flare_repo).resolve()
        if str(flare_repo) not in sys.path:
            sys.path.insert(0, str(flare_repo))

        from flare.data.transforms import MolToGraph
        from flare.utils.models import get_model

        with open(self.hparams_pth) as f:
            params = yaml.load(f, Loader=yaml.FullLoader)
        params["checkpoint_pth"] = str(self.checkpoint_pth)
        params["df_test_path"] = ""
        params["accelerator"] = "cpu"
        params["devices"] = 1

        device = self.device
        if device == "cuda":
            if not torch.cuda.is_available():
                device = "cpu"
            else:
                try:
                    dgl.graph(([0], [0])).to("cuda")
                except Exception:
                    device = "cpu"

        model = get_model(params["model"], params)
        model = model.to(device)
        model.eval()

        mol_transform = MolToGraph(
            atom_feature=params["atom_feature"],
            bond_feature=params["bond_feature"],
            element_list=params["element_list"],
        )
        return model.mol_enc_model, mol_transform, device

    def encode(self, smiles: Iterable[str]) -> np.ndarray:
        import dgl
        import torch

        smiles_list = list(smiles)
        if not smiles_list:
            return np.zeros((0, 0), dtype=np.float32)

        mol_encoder, mol_transform, device = self._load()
        outputs: List[np.ndarray] = []
        total_batches = (len(smiles_list) + self.batch_size - 1) // self.batch_size

        with torch.no_grad():
            for start in tqdm(range(0, len(smiles_list), self.batch_size), total=total_batches, desc="Encoding FLARE", unit="batch"):
                batch_smiles = smiles_list[start:start + self.batch_size]
                graphs = [mol_transform(smi) for smi in batch_smiles]
                batched = dgl.batch(graphs)
                if device != "cpu":
                    batched = batched.to(device)
                node_embeddings = mol_encoder(batched)
                pooled = mol_encoder.pool(batched, node_embeddings)
                outputs.append(pooled.detach().cpu().numpy().astype(np.float32))

        arr = np.concatenate(outputs, axis=0).astype(np.float32)
        if self.normalize:
            arr = l2_normalize(arr)
        return arr

    def encode_to_npy(self, smiles: Iterable[str], out_path: str | Path) -> Path:
        import dgl
        import torch

        smiles_list = list(smiles)
        out_path = Path(out_path)
        if not smiles_list:
            np.save(out_path, np.zeros((0, 0), dtype=np.float32))
            return out_path

        mol_encoder, mol_transform, device = self._load()
        total_batches = (len(smiles_list) + self.batch_size - 1) // self.batch_size
        mm = None
        offset = 0

        with torch.no_grad():
            for start in tqdm(range(0, len(smiles_list), self.batch_size), total=total_batches, desc="Encoding FLARE", unit="batch"):
                batch_smiles = smiles_list[start:start + self.batch_size]
                graphs = [mol_transform(smi) for smi in batch_smiles]
                batched = dgl.batch(graphs)
                if device != "cpu":
                    batched = batched.to(device)
                node_embeddings = mol_encoder(batched)
                pooled = mol_encoder.pool(batched, node_embeddings)
                chunk = pooled.detach().cpu().numpy().astype(np.float32)
                if mm is None:
                    mm = open_memmap(out_path, mode="w+", dtype=np.float32, shape=(len(smiles_list), chunk.shape[1]))
                mm[offset:offset + chunk.shape[0]] = chunk
                offset += chunk.shape[0]

        if mm is None:
            np.save(out_path, np.zeros((0, 0), dtype=np.float32))
            return out_path
        del mm

        if self.normalize:
            arr = np.load(out_path, mmap_mode="r+")
            norms = np.linalg.norm(arr, axis=1, keepdims=True)
            arr[:] = arr[:] / np.clip(norms, 1e-8, None)
            del arr
        return out_path


@dataclass
class FLARESpecEmbedder:
    flare_repo: str
    hparams_pth: str
    checkpoint_pth: str
    dataset_pth: str
    subformula_dir_pth: str
    fold: str = "test"
    device: str = "cpu"
    batch_size: int = 128
    normalize: bool = True

    def _load(self):
        libstdcpp = Path(sys.executable).resolve().parent.parent / "lib" / "libstdc++.so.6"
        if libstdcpp.exists():
            ctypes.CDLL(str(libstdcpp), mode=ctypes.RTLD_GLOBAL)

        import dgl
        import torch
        import yaml

        flare_repo = Path(self.flare_repo).resolve()
        if str(flare_repo) not in sys.path:
            sys.path.insert(0, str(flare_repo))

        from massspecgym.models.base import Stage
        from flare.data.datasets import MassSpecDataset_PeakFormulas
        from flare.utils.data import get_spec_featurizer
        from flare.utils.models import get_model

        with open(self.hparams_pth) as f:
            params = yaml.load(f, Loader=yaml.FullLoader)
        params["checkpoint_pth"] = str(self.checkpoint_pth)
        params["df_test_path"] = ""
        params["accelerator"] = "cpu"
        params["devices"] = 1

        device = self.device
        if device == "cuda":
            if not torch.cuda.is_available():
                device = "cpu"
            else:
                try:
                    dgl.graph(([0], [0])).to("cuda")
                except Exception:
                    device = "cpu"

        model = get_model(params["model"], params)
        model = model.to(device)
        model.eval()

        spec_transform = get_spec_featurizer(params["spectra_view"], params)
        dataset = MassSpecDataset_PeakFormulas(
            spectra_view=params["spectra_view"],
            spec_transform=spec_transform,
            mol_transform=None,
            pth=self.dataset_pth,
            subformula_dir_pth=self.subformula_dir_pth,
            formula_source=params.get("formula_source", "default"),
            return_mol_freq=False,
            return_identifier=True,
            stage=Stage.TEST,
        )
        return model.spec_enc_model, params["spectra_view"], dataset, device

    def encode(self):
        import torch

        spec_encoder, spectra_view, dataset, device = self._load()
        metadata = dataset.metadata
        if "fold" in metadata.columns and self.fold:
            metadata = metadata[metadata["fold"].astype(str) == str(self.fold)]
        indices = metadata.index.to_list()

        if not indices:
            return np.zeros((0, 0), dtype=np.float32), [], []

        outputs: List[np.ndarray] = []
        out_smiles: List[str] = []
        out_ids: List[str] = []

        with torch.no_grad():
            for start in tqdm(range(0, len(indices), self.batch_size), desc="Encoding FLARE spectra", unit="batch"):
                batch_idx = indices[start:start + self.batch_size]
                specs = []
                n_peaks = []
                for idx in batch_idx:
                    item = dataset.__getitem__(idx, transform_mol=False)
                    spec = item[spectra_view]
                    specs.append(spec)
                    n_peaks.append(int(spec.shape[0]))
                    row = dataset.metadata.loc[idx]
                    out_smiles.append(str(row["smiles"]))
                    out_ids.append(str(row["identifier"]))
                batch = torch.nn.utils.rnn.pad_sequence(specs, batch_first=True, padding_value=-5)
                batch = batch.to(device)
                enc = spec_encoder(batch, n_peaks)
                if enc.ndim == 3:
                    mask = (batch != -5).any(dim=-1).float()
                    pooled = (enc * mask.unsqueeze(-1)).sum(dim=1) / mask.sum(dim=1, keepdim=True).clamp(min=1.0)
                else:
                    pooled = enc
                outputs.append(pooled.detach().cpu().numpy().astype(np.float32))

        arr = np.concatenate(outputs, axis=0).astype(np.float32)
        if self.normalize:
            arr = l2_normalize(arr)
        return arr, out_smiles, out_ids