-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfingerprints.py
More file actions
459 lines (379 loc) · 16.9 KB
/
fingerprints.py
File metadata and controls
459 lines (379 loc) · 16.9 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
from typing import Union, List, Callable, Optional
from functools import partial
import inspect
import abc
import numpy as np
import numpy.typing as npt
from tqdm import tqdm
from rdkit.Avalon import pyAvalonTools
from rdkit.Chem import AllChem, rdMolDescriptors, RDKFingerprint
from rdkit.Chem.AtomPairs import Pairs
from rdkit import Chem
from utils import to_mol, catch_boost_argument_error
def _wrap_handle_none(fp_func: Callable, *args, fail_size: Optional[int] = None, **kwargs) -> List:
"""
Wraps an FP function and handles RDKit chemical exceptions by returning a list of NaN values.
Parameters
----------
fp_func (Callable):
The function to be wrapped.
*args:
Variable length argument list to be passed to the function.
**kwargs:
Arbitrary keyword arguments to be passed to the function.
fail_size (int or None, optional):
The size of the list to be returned in case of failure.
If None, the fail_size is determined by calling the function with a default argument.
Defaults to None.
Returns
-------
list:
A list of NaN values with length equal to fail_size.
Notes:
-----
If not `fail_size` is passed, will try and assume it by calling the FP function on "CCC" to get the FP length
This can cause major overhead if lost of SMILES fail inside RDKit (what this wrapper is built to catch),
so if you expect to see high failure rates preseting the fail length will minimize this overhead
The `FPFunc` Class has a `_dimension` attribute that hold the FP length, thus any defined FPFunc should not
suffer from this overhead. Any newly added FPFunc should follow this convention as well
Raises
------
Any Exception:
If the exception thrown is not a boost C++ exception, will still raise that exception.
Examples
________
>>> _wrap_handle_none(AllChem.GetMorganFingerprintAsBitVect, Chem.MolFromSmiles("CCC"), 2)
[nan, nan]
>>> _wrap_handle_none(AllChem.GetMorganFingerprintAsBitVect, Chem.MolFromSmiles("CCC"), fail_size=3)
[nan, nan, nan]
"""
assert isinstance(fp_func, Callable), "fp_func must be a callable"
try:
return list(fp_func(*args, **kwargs))
except Exception as e: # throws boost C++ exception, which python cannot catch
if catch_boost_argument_error(e):
if fail_size is None:
# attempt to get fail_size from the func if it is not passed
fail_size = len(list(fp_func(AllChem.MolFromSmiles("CCC"))))
return [np.nan] * fail_size
else:
raise
class BaseFPFunc(abc.ABC):
"""
Base class for all FP functions used in any AIRCHECK pipeline
Parameters
----------
kwargs : dict
dictionary of keyword arguments to pass to the fingerprint function in from {`argument`: `value`}
Attributes
----------
_func : functools.partial object
The callable FP function instance as a partial with static setting arguments (e.g., 'radius') pre-set
_binary : bool
Whether the FP function returns binary fingerprints
_dimension : int
the dimensionality of the fingerprints that will be generated
Notes
-----
When declaring a child of the `BaseFPFunc` class, the `_func`, `_dimension` and `_binary` attributes must be set
during instantiation of the child.
FP Funcs operate on rdkit.ROMol objects, not smiles and will fail if SMILES are passed
"""
def __init__(self, **kwargs):
self._kwargs = kwargs
self._func: Callable = lambda: None
self._binary: bool = False
self._dimension: int = -1
def __call__(self, smis, *args, use_tqdm: bool = False, **kwargs) -> npt.NDArray[np.int32]:
return np.array(
[
_wrap_handle_none(self._func, to_mol(c), fail_size=self._dimension)
for c in tqdm(np.atleast_1d(smis), disable=not use_tqdm)
]
)
def __eq__(self, other) -> bool:
if isinstance(other, BaseFPFunc):
if (
inspect.signature(self._func).parameters
== inspect.signature(other).parameters
):
return True
return False
def generate_fps(
self,
smis: Union[str, Chem.rdchem.Mol, List[Union[str, Chem.rdchem.Mol]]],
use_tqdm: bool = False,
) -> np.ndarray:
"""
Generate Fingerprints for a set of smiles
Parameters
----------
smis : str, rdkit Mol or list of rdkit Mol or str
the SMILES or Mol objects (or multiple SMILES/Mol objects) you want to generate a fingerprint(s) for
use_tqdm : bool, default: False
have a tqdm task to track progress
Returns
-------
ndarray
an array of size (M, d), where M is number of Mols passes and d is the dimension of fingerprint
Notes
-----
The passed list can be a mix of SMILES and Mol objects.
If the SMILES are invalid or the Mol object(s) are None, then that molecules row of the output fingerprint
array will be `np.nan` (e.i., the fingerprint for that molecule will be 1-d array of `np.nan` of dimension d)
This function just wraps the __call__ method of the class
"""
return self.__call__(smis, use_tqdm)
def to_dict(self) -> dict:
"""
Returns the name and settings of the FP function as a dict
Returns
-------
dict
name and settings of FP function
"""
_signature = inspect.signature(self._func)
args = {
k: v.default
for k, v in _signature.parameters.items()
if v.default is not inspect.Parameter.empty
}
args['name'] = self.func_name()
return args
def is_binary(self) -> bool:
"""
Determines if the FP function is binary
Returns
-------
bool:
True if the FP function is binary, otherwise False
Notes
-----
This function just returns the `_binary` attribute set during instantiation
"""
return self._binary
def func_name(self) -> str:
"""
Returns the name of the RDKit python function used to calculate the fingerprint
Returns
-------
str
name of python FP function
Notes
-----
This function meant to support reproducibility of FP calculations
"""
if isinstance(self._func, partial):
return self._func.func.__name__
else:
return self._func.__name__
class HitGenECFP4(BaseFPFunc):
"""
The FP calculation used by HitGen when generating ECFP4 fingerprints
Notes
-----
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 2, "nBits": 2048, "useFeatures": False})
self._func = partial(AllChem.GetHashedMorganFingerprint, **self._kwargs)
self._dimension = 2048
class HitGenECFP6(BaseFPFunc):
"""
The FP calculation used by HitGen when generating ECFP6 fingerprints
Notes
-----
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 3, "nBits": 2048, "useFeatures": False})
self._func = partial(AllChem.GetHashedMorganFingerprint, **self._kwargs)
self._dimension = 2048
class HitGenFCFP4(BaseFPFunc):
"""
The FP calculation used by HitGen when generating FCFP4 fingerprints
Notes
-----
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 2, "nBits": 2048, "useFeatures": True})
self._func = partial(AllChem.GetHashedMorganFingerprint, **self._kwargs)
self._dimension = 2048
class HitGenFCFP6(BaseFPFunc):
"""
The FP calculation used by HitGen when generating FCFP6 fingerprints
Notes
-----
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 3, "nBits": 2048, "useFeatures": True})
self._func = partial(AllChem.GetHashedMorganFingerprint, **self._kwargs)
self._dimension = 2048
class HitGenBinaryECFP4(BaseFPFunc):
"""
The FP calculation used to match the binary ECFP4 fingerprints generated from HitGen's ECFP4 fingerprints
Notes
-----
This FP is not directly given by HitGen, but can be calculated by just 'binarizing' the hashed FP they provide
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 2, "nBits": 2048, "useFeatures": False})
self._func = partial(AllChem.GetMorganFingerprintAsBitVect, **self._kwargs)
self._binary = True
self._dimension = 2048
class HitGenBinaryECFP6(BaseFPFunc):
"""
The FP calculation used to match the binary ECFP6 fingerprints generated from HitGen's ECFP6 fingerprints
Notes
-----
This FP is not directly given by HitGen, but can be calculated by just 'binarizing' the hashed FP they provide
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 3, "nBits": 2048, "useFeatures": False})
self._func = partial(AllChem.GetMorganFingerprintAsBitVect, **self._kwargs)
self._binary = True
self._dimension = 2048
class HitGenBinaryFCFP4(BaseFPFunc):
"""
The FP calculation used to match the binary FCFP4 fingerprints generated from HitGen's FCFP4 fingerprints
Notes
-----
This FP is not directly given by HitGen, but can be calculated by just 'binarizing' the hashed FP they provide
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 2, "nBits": 2048, "useFeatures": True})
self._func = partial(AllChem.GetMorganFingerprintAsBitVect, **self._kwargs)
self._binary = True
self._dimension = 2048
class HitGenBinaryFCFP6(BaseFPFunc):
"""
The FP calculation used to match the binary FCFP6 fingerprints generated from HitGen's FCFP6 fingerprints
Notes
-----
This FP is not directly given by HitGen, but can be calculated by just 'binarizing' the hashed FP they provide
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 3, "nBits": 2048, "useFeatures": True})
self._func = partial(AllChem.GetMorganFingerprintAsBitVect, **self._kwargs)
self._binary = True
self._dimension = 2048
class HitGenMACCS(BaseFPFunc):
"""
The FP calculation used by HitGen when generating MACCS fingerprints
Notes
-----
Unlike other HitGen FPs, MACCS is only generated in a binary fashion by HitGen, thus no hashed/count version exists
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__()
self._func = partial(rdMolDescriptors.GetMACCSKeysFingerprint, **self._kwargs)
self._binary = True
self._dimension = 167
class HitGenRDK(BaseFPFunc):
"""
The FP calculation used by HitGen when generating RDK fingerprints
Notes
-----
Unlike other HitGen FPs, RDK is only generated in a binary fashion by HitGen, thus no hashed/count version exists
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"fpSize": 2048})
self._func = partial(RDKFingerprint, **self._kwargs)
self._binary = True
self._dimension = 2048
class HitGenAvalon(BaseFPFunc):
"""
The FP calculation used by HitGen when generating Avalon fingerprints
Notes
-----
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"nBits": 2048})
self._func = partial(pyAvalonTools.GetAvalonCountFP, **self._kwargs)
self._dimension = 2048
class HitGenBinaryAvalon(BaseFPFunc):
"""
The FP calculation used to match the binary Avalon fingerprints generated from HitGen's Avalon fingerprints
Notes
-----
This FP is not directly given by HitGen, but can be calculated by just 'binarizing' the hashed FP they provide.
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 3, "nBits": 2048, "useFeatures": True})
self._func = partial(pyAvalonTools.GetAvalonFP, **self._kwargs)
self._binary = True
self._dimension = 2048
class HitGenAtomPair(BaseFPFunc):
"""
The FP calculation used by HitGen when generating AtomPair fingerprints
Notes
-----
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"nBits": 2048})
self._func = partial(rdMolDescriptors.GetHashedAtomPairFingerprint, **self._kwargs)
self._dimension = 2048
class HitGenBinaryAtomPair(BaseFPFunc):
"""
The FP calculation used to match the binary AtomPair fingerprints generated from HitGen's AtomPair fingerprints
Notes
-----
This FP is not directly given by HitGen, but can be calculated by just 'binarizing' the hashed FP they provide.
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 3, "nBits": 2048, "useFeatures": True})
self._func = partial(Pairs.GetAtomPairFingerprintAsBitVect, **self._kwargs)
self._binary = True
self._dimension = 2048
class HitGenTopTor(BaseFPFunc):
"""
The FP calculation used by HitGen when generating Topological Torsion (TopTor) fingerprints
Notes
-----
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"nBits": 2048})
self._func = partial(AllChem.GetHashedTopologicalTorsionFingerprint, **self._kwargs)
self._dimension = 2048
class HitGenBinaryTopTor(BaseFPFunc):
"""
The FP calculation used to match the binary TopTor fingerprints generated from HitGen's TopTor fingerprints
Notes
-----
This FP is not directly given by HitGen, but can be calculated by just 'binarizing' the hashed FP they provide.
All settings and attributes are preset during the instantiation of the object.
Tweaks to FP settings should not be made, as the FP function will not match HitGen anymore
"""
def __init__(self):
super().__init__(**{"radius": 3, "nBits": 2048, "useFeatures": True})
self._func = partial(AllChem.GetHashedTopologicalTorsionFingerprintAsBitVect, **self._kwargs)
self._binary = True
self._dimension = 2048