File size: 11,672 Bytes
42f26af
 
 
 
 
2c0063e
42f26af
 
 
 
 
fb764d2
 
42f26af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1aa639
42f26af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1aa639
42f26af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
299
300
import numpy as np
import torch
import matchms
from typing import Optional
from rdkit.Chem import AllChem as Chem
from flare.definitions import CHEM_ELEMS_SMALL
from massspecgym.data.transforms import MolTransform, SpecTransform, default_matchms_transforms
from massspecgym.data.transforms import SpecBinner
import dgllife.utils as chemutils
import re



class SpecBinnerLog(SpecTransform):
    def __init__(
        self,
        max_mz: float = 1005,
        bin_width: float = 1,
    ) -> None:
        self.max_mz = max_mz
        self.bin_width = bin_width
        if not (max_mz / bin_width).is_integer():
            raise ValueError("`max_mz` must be divisible by `bin_width`.")
        
    def matchms_transforms(self, spec: matchms.Spectrum) -> matchms.Spectrum:
        return default_matchms_transforms(spec, mz_to=self.max_mz, n_max_peaks=None)
    
    def matchms_to_torch(self, spec: matchms.Spectrum) -> torch.Tensor:
        """
        Bin the spectrum into a fixed number of bins.
        """
        binned_spec = self._bin_mass_spectrum(
            mzs=spec.peaks.mz,
            intensities=spec.peaks.intensities,
            max_mz=self.max_mz,
            bin_width=self.bin_width,
        )
        return torch.from_numpy(binned_spec).to(dtype=torch.float32)

    def _bin_mass_spectrum(
        self, mzs, intensities, max_mz, bin_width
    ):

        # Calculate the number of bins
        num_bins = int(np.ceil(max_mz / bin_width))

        # Calculate the bin indices for each mass
        bin_indices = np.floor(mzs -1 / bin_width).astype(int)

        # Filter out mzs that exceed max_mz
        valid_indices = bin_indices[mzs <= max_mz]
        valid_intensities = intensities[mzs <= max_mz]

        # Clip bin indices to ensure they are within the valid range
        valid_indices = np.clip(valid_indices, 0, num_bins - 1)

        # Initialize an array to store the binned intensities
        binned_intensities = np.zeros(num_bins)

        # Use np.add.at to sum intensities in the appropriate bins
        np.add.at(binned_intensities, valid_indices, valid_intensities)

        binned_intensities = binned_intensities/np.max(binned_intensities) * 999

        binned_intensities = np.log10(binned_intensities + 1) / 3

        return binned_intensities 

class SpecMzIntTokenizer(SpecTransform):
    def __init__(self, max_mz, mz_mean_std=None, mask_precursor=None):
        self.max_mz = max_mz
        self.mz_mean_std = mz_mean_std
    def matchms_transforms(self, spec: matchms.Spectrum):
        return default_matchms_transforms(spec, mz_to=self.max_mz, n_max_peaks=None)
    
    def matchms_to_torch(self, spec: matchms.Spectrum):
        mzs = spec.peaks.mz
        intensities = spec.peaks.intensities
        spec = np.zeros((len(mzs), 2))

        if self.mz_mean_std:
            mz = (mzs-self.mz_mean_std['mz_mean'])/self.mz_mean_std['mz_std']
        else:
            mz = mzs/self.max_mz
        
        spec[:, 0] = mz
        spec[:, 1] = intensities

        return torch.from_numpy(spec.astype(np.float32))

class SpecFormulaMzFeaturizer(SpecTransform):
    ''' Uses raw mz and intensities '''

    def __init__(
            self,
            add_intensities: bool,
            max_mz: float = 1005,
            element_list: list = CHEM_ELEMS_SMALL,
            formula_normalize_vector: Optional[np.array] = None,
            mz_mean_std: dict[str, float] = None,
            mask_precursor: bool = False,
    ) -> None:
        self.max_mz = max_mz
        self.elem_to_pos = {e: i for i, e in enumerate(element_list)}
        if formula_normalize_vector is None:
            formula_normalize_vector = np.ones(len(element_list))
        self.formula_normalize_vector = formula_normalize_vector
        self.CHEM_FORMULA_SIZE = "([A-Z][a-z]*)([0-9]*)"
        self.mz_mean_std = mz_mean_std
        self.add_intensities = add_intensities
        self.mask_precursor = mask_precursor
        
    def matchms_transforms(self, spec: matchms.Spectrum):
        return spec
    
    def matchms_to_torch(self, spec: matchms.Spectrum) -> torch.Tensor:
        mzs = spec.peaks.mz
        intensities = spec.peaks.intensities
        formulas = spec.metadata['formulas'] # mz to formula dict

        peak_idx = np.where(mzs <= self.max_mz)[0]
        mzs = mzs[peak_idx]
        intensities = intensities[peak_idx]
        formulas = [formulas.get(mz, "NA") for mz in mzs[peak_idx]]

        if self.mask_precursor:
            try:
                precursor_i = formulas.index(spec.metadata['precursor_formula'])
                formulas[precursor_i] = 'NA'
            except:
                pass

        formulas = self._featurize_formula(formulas)
        formulas = formulas/self.formula_normalize_vector
        
        if self.mz_mean_std:
            mz = (mzs-self.mz_mean_std['mz_mean'])/self.mz_mean_std['mz_std']
        else:
            mz = mzs/self.max_mz
        
        if self.add_intensities:
            spec = np.concatenate((mz.reshape(-1,1), intensities.reshape(-1,1), formulas), axis=1)
        else:
            spec = np.concatenate((mz.reshape(-1,1), formulas), axis=1)

        return torch.from_numpy(spec)
    
    def _featurize_formula(self, formulas):
        formula_vector = np.zeros((len(formulas), len(self.elem_to_pos)))
        for i, f in enumerate(formulas):
            if f == "NA":
                # formula_vector[i] = np.zeros((1, len(self.elem_to_pos)))
                formula_vector[i] = np.ones((1, len(self.elem_to_pos))) * -1

            else:
                for (e, ct) in re.findall(self.CHEM_FORMULA_SIZE, f):
                    ct = 1 if ct == "" else int(ct)
                    try:
                        formula_vector[i][self.elem_to_pos[e]]+=ct
                    except:
                        # print(f"Couldn't vectorize {f}, element {e} not supported")
                        continue
        return formula_vector

class SpecFormulaFeaturizer(SpecTransform):
    ''' Uses processed mz and intensities, excludes mz values, keep peaks with formulas only'''
    def __init__(
            self,
            add_intensities: bool,
            max_mz: float = 1005,
            element_list: list = CHEM_ELEMS_SMALL,
            formula_normalize_vector: Optional[np.array] = None
    ) -> None:
        self.max_mz = max_mz
        self.elem_to_pos = {e: i for i, e in enumerate(element_list)}
        self.add_intensities = add_intensities
        if formula_normalize_vector is None:
            formula_normalize_vector = np.ones(len(element_list))
        self.formula_normalize_vector = formula_normalize_vector
        self.CHEM_FORMULA_SIZE = "([A-Z][a-z]*)([0-9]*)"
        
    def matchms_transforms(self, spec: matchms.Spectrum):
        return spec
    
    def matchms_to_torch(self, spec: matchms.Spectrum) -> torch.Tensor:
        mzs = spec.peaks.mz
        intensities = spec.peaks.intensities
        formulas = spec.metadata['formulas'] # list of formulas

        peak_idx = np.where(mzs <= self.max_mz)[0]
        intensities = intensities[peak_idx]
        formulas = formulas[peak_idx]

        spec = self._featurize_formula(formulas)
        spec = spec/self.formula_normalize_vector

        if self.add_intensities:
            spec = np.concatenate((spec, intensities.reshape(-1,1)), axis=1)
        spec = spec.astype(np.float32)

        return torch.from_numpy(spec)
    
    def _featurize_formula(self, formulas):
        formula_vector = np.zeros((len(formulas), len(self.elem_to_pos)))
        for i, f in enumerate(formulas):
            try:
                for (e, ct) in re.findall(self.CHEM_FORMULA_SIZE, f):
                    ct = 1 if ct == "" else int(ct)
                    try:
                        formula_vector[i][self.elem_to_pos[e]]+=ct
                    except:
                            # print(f"Couldn't vectorize {f}, element {e} not supported")
                            continue
            except:
                print(f"Couldn't vectorize {f}, formula not supported")
                continue
        return formula_vector

class MolToGraph(MolTransform):
    def __init__ (self, atom_feature: str = "full", bond_feature: str = "full", element_list: list = CHEM_ELEMS_SMALL):
        self.atom_feature = atom_feature
        self.bond_feature = bond_feature
        self.node_featurizer = self._get_atom_featurizer(element_list=element_list) 
        self.edge_featurizer = self._get_bond_featurizer()
    
    def from_smiles(self, mol:str):
        mol = Chem.MolFromSmiles(mol)
        g = chemutils.mol_to_bigraph(mol, node_featurizer=self.node_featurizer, edge_featurizer=self.edge_featurizer, add_self_loop = True,
                             num_virtual_nodes = 0, canonical_atom_order=False)

        # atom_ids = [atom.GetIdx() for atom in mol.GetAtoms()] # added for visualization
        # g.ndata['atom_id'] = torch.tensor(atom_ids, dtype=torch.long)

        return g

    def _get_atom_featurizer(self, element_list) -> dict:
        feature_mode = self.atom_feature
        atom_mass_fun = chemutils.ConcatFeaturizer(
            [chemutils.atom_mass]
        )
        def atom_bond_type_one_hot(atom):
            bs = atom.GetBonds()
            bt = np.array([chemutils.bond_type_one_hot(b) for b in bs])
            return [any(bt[:, i]) for i in range(bt.shape[1])]

        def atom_type_one_hot(atom):
            return chemutils.atom_type_one_hot(
                atom, allowable_set = element_list, encode_unknown = True
            )
        
        if feature_mode == 'light':
            atom_featurizer_funs = chemutils.ConcatFeaturizer([
                chemutils.atom_mass,
                atom_type_one_hot
            ])
        elif feature_mode == 'full':
            atom_featurizer_funs = chemutils.ConcatFeaturizer([
                chemutils.atom_mass,
                atom_type_one_hot, 
                atom_bond_type_one_hot,
                chemutils.atom_degree_one_hot, 
                chemutils.atom_total_degree_one_hot,
                chemutils.atom_explicit_valence_one_hot,
                chemutils.atom_implicit_valence_one_hot,
                chemutils.atom_hybridization_one_hot,
                chemutils.atom_total_num_H_one_hot,
                chemutils.atom_formal_charge_one_hot,
                chemutils.atom_num_radical_electrons_one_hot,
                chemutils.atom_is_aromatic_one_hot,
                chemutils.atom_is_in_ring_one_hot,
                chemutils.atom_chiral_tag_one_hot
            ])
        elif feature_mode == 'medium':
            atom_featurizer_funs = chemutils.ConcatFeaturizer([
                chemutils.atom_mass,
                atom_type_one_hot, 
                atom_bond_type_one_hot,
                chemutils.atom_total_degree_one_hot,
                chemutils.atom_total_num_H_one_hot,
                chemutils.atom_is_aromatic_one_hot,
                chemutils.atom_is_in_ring_one_hot,
            ])
        return chemutils.BaseAtomFeaturizer(
        {"h": atom_featurizer_funs, 
        "m": atom_mass_fun}
    )

    def _get_bond_featurizer(self, self_loop=True) -> dict:
        feature_mode = self.bond_feature
        if feature_mode == 'light':
            return chemutils.BaseBondFeaturizer(
                featurizer_funcs = {'e': chemutils.ConcatFeaturizer([
                    chemutils.bond_type_one_hot
                ])}, self_loop = self_loop
            )
        elif feature_mode == 'full':
            return chemutils.CanonicalBondFeaturizer(
                bond_data_field='e', self_loop = self_loop
            )