/
molecule_feature_utils.py
632 lines (534 loc) · 18.8 KB
/
molecule_feature_utils.py
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
"""
Utilities for constructing node features or bond features.
Some functions are based on chainer-chemistry or dgl-lifesci.
Repositories:
- https://github.com/chainer/chainer-chemistry
- https://github.com/awslabs/dgl-lifesci
"""
import os
import logging
from typing import List, Union, Tuple
import numpy as np
from deepchem.utils.typing import RDKitAtom, RDKitBond, RDKitMol
logger = logging.getLogger(__name__)
DEFAULT_ATOM_TYPE_SET = [
"C",
"N",
"O",
"F",
"P",
"S",
"Cl",
"Br",
"I",
]
DEFAULT_HYBRIDIZATION_SET = ["SP", "SP2", "SP3"]
DEFAULT_TOTAL_NUM_Hs_SET = [0, 1, 2, 3, 4]
DEFAULT_FORMAL_CHARGE_SET = [-2, -1, 0, 1, 2]
DEFAULT_TOTAL_DEGREE_SET = [0, 1, 2, 3, 4, 5]
DEFAULT_RING_SIZE_SET = [3, 4, 5, 6, 7, 8]
DEFAULT_BOND_TYPE_SET = ["SINGLE", "DOUBLE", "TRIPLE", "AROMATIC"]
DEFAULT_BOND_STEREO_SET = ["STEREONONE", "STEREOANY", "STEREOZ", "STEREOE"]
DEFAULT_GRAPH_DISTANCE_SET = [1, 2, 3, 4, 5, 6, 7]
DEFAULT_ATOM_IMPLICIT_VALENCE_SET = [0, 1, 2, 3, 4, 5, 6]
DEFAULT_ATOM_EXPLICIT_VALENCE_SET = [1, 2, 3, 4, 5, 6]
ALLEN_ELECTRONEGATIVTY = { # Allen scale electronegativity
'H': 2.3,
'He': 4.160,
'Li': 0.912,
'Be': 1.576,
'B': 2.051,
'C': 2.544,
'N': 3.066,
'O': 3.610,
'F': 4.193,
'Ne': 4.787,
'Na': 0.869,
'Mg': 1.293,
'Al': 1.613,
'Si': 1.916,
'P': 2.253,
'S': 2.589,
'Cl': 2.869,
'Ar': 3.242,
'K': 0.734,
'Ca': 1.034,
'Sc': 1.19,
'Ti': 1.38,
'V': 1.53,
'Cr': 1.65,
'Mn': 1.75,
'Fe': 1.80,
'Co': 1.84,
'Ni': 1.88,
'Cu': 1.85,
'Zn': 1.588,
'Ga': 1.756,
'Ge': 1.994,
'As': 2.211,
'Se': 2.424,
'Br': 2.685,
'Kr': 2.966,
'Rb': 0.706,
'Sr': 0.963,
'Y': 1.12,
'Zr': 1.32,
'Nb': 1.41,
'Mo': 1.47,
'Tc': 1.51,
'Ru': 1.54,
'Rh': 1.56,
'Pd': 1.58,
'Ag': 1.87,
'Cd': 1.521,
'In': 1.656,
'Sn': 1.824,
'Sb': 1.984,
'Te': 2.158,
'I': 2.359,
'Xe': 2.582,
'Cs': 0.659,
'Ba': 0.881,
'Lu': 1.09,
'Hf': 1.16,
'Ta': 1.34,
'W': 1.47,
'Re': 1.60,
'Os': 1.65,
'Ir': 1.68,
'Pt': 1.72,
'Au': 1.92,
'Hg': 1.765,
'Tl': 1.789,
'Pb': 1.854,
'Bi': 2.01,
'Po': 2.19,
'At': 2.39,
'Rn': 2.60,
'Fr': 0.67,
'Ra': 0.89
}
class _ChemicalFeaturesFactory:
"""This is a singleton class for RDKit base features."""
_instance = None
@classmethod
def get_instance(cls):
try:
from rdkit import RDConfig
from rdkit.Chem import ChemicalFeatures
except ModuleNotFoundError:
raise ImportError("This class requires RDKit to be installed.")
if not cls._instance:
fdefName = os.path.join(RDConfig.RDDataDir, 'BaseFeatures.fdef')
cls._instance = ChemicalFeatures.BuildFeatureFactory(fdefName)
return cls._instance
def one_hot_encode(val: Union[int, str],
allowable_set: Union[List[str], List[int]],
include_unknown_set: bool = False) -> List[float]:
"""One hot encoder for elements of a provided set.
Examples
--------
>>> one_hot_encode("a", ["a", "b", "c"])
[1.0, 0.0, 0.0]
>>> one_hot_encode(2, [0, 1, 2])
[0.0, 0.0, 1.0]
>>> one_hot_encode(3, [0, 1, 2])
[0.0, 0.0, 0.0]
>>> one_hot_encode(3, [0, 1, 2], True)
[0.0, 0.0, 0.0, 1.0]
Parameters
----------
val: int or str
The value must be present in `allowable_set`.
allowable_set: List[int] or List[str]
List of allowable quantities.
include_unknown_set: bool, default False
If true, the index of all values not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
An one-hot vector of val.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
Raises
------
ValueError
If include_unknown_set is False and `val` is not in `allowable_set`.
"""
if include_unknown_set is False:
if val not in allowable_set:
logger.info("input {0} not in allowable set {1}:".format(
val, allowable_set))
# init an one-hot vector
if include_unknown_set is False:
one_hot_legnth = len(allowable_set)
else:
one_hot_legnth = len(allowable_set) + 1
one_hot = [0.0 for _ in range(one_hot_legnth)]
try:
one_hot[allowable_set.index(val)] = 1.0 # type: ignore
except:
if include_unknown_set:
# If include_unknown_set is True, set the last index is 1.
one_hot[-1] = 1.0
else:
pass
return one_hot
#################################################################
# atom (node) featurization
#################################################################
def get_atom_type_one_hot(atom: RDKitAtom,
allowable_set: List[str] = DEFAULT_ATOM_TYPE_SET,
include_unknown_set: bool = True) -> List[float]:
"""Get an one-hot feature of an atom type.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
allowable_set: List[str]
The atom types to consider. The default set is
`["C", "N", "O", "F", "P", "S", "Cl", "Br", "I"]`.
include_unknown_set: bool, default True
If true, the index of all atom not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
An one-hot vector of atom types.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
"""
return one_hot_encode(atom.GetSymbol(), allowable_set, include_unknown_set)
def construct_hydrogen_bonding_info(mol: RDKitMol) -> List[Tuple[int, str]]:
"""Construct hydrogen bonding infos about a molecule.
Parameters
---------
mol: rdkit.Chem.rdchem.Mol
RDKit mol object
Returns
-------
List[Tuple[int, str]]
A list of tuple `(atom_index, hydrogen_bonding_type)`.
The `hydrogen_bonding_type` value is "Acceptor" or "Donor".
"""
factory = _ChemicalFeaturesFactory.get_instance()
feats = factory.GetFeaturesForMol(mol)
hydrogen_bonding = []
for f in feats:
hydrogen_bonding.append((f.GetAtomIds()[0], f.GetFamily()))
return hydrogen_bonding
def get_atom_hydrogen_bonding_one_hot(
atom: RDKitAtom, hydrogen_bonding: List[Tuple[int,
str]]) -> List[float]:
"""Get an one-hot feat about whether an atom accepts electrons or donates electrons.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
hydrogen_bonding: List[Tuple[int, str]]
The return value of `construct_hydrogen_bonding_info`.
The value is a list of tuple `(atom_index, hydrogen_bonding)` like (1, "Acceptor").
Returns
-------
List[float]
A one-hot vector of the ring size type. The first element
indicates "Donor", and the second element indicates "Acceptor".
"""
one_hot = [0.0, 0.0]
atom_idx = atom.GetIdx()
for hydrogen_bonding_tuple in hydrogen_bonding:
if hydrogen_bonding_tuple[0] == atom_idx:
if hydrogen_bonding_tuple[1] == "Donor":
one_hot[0] = 1.0
elif hydrogen_bonding_tuple[1] == "Acceptor":
one_hot[1] = 1.0
return one_hot
def get_atom_is_in_aromatic_one_hot(atom: RDKitAtom) -> List[float]:
"""Get ans one-hot feature about whether an atom is in aromatic system or not.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
Returns
-------
List[float]
A vector of whether an atom is in aromatic system or not.
"""
return [float(atom.GetIsAromatic())]
def get_atom_hybridization_one_hot(
atom: RDKitAtom,
allowable_set: List[str] = DEFAULT_HYBRIDIZATION_SET,
include_unknown_set: bool = False) -> List[float]:
"""Get an one-hot feature of hybridization type.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
allowable_set: List[str]
The hybridization types to consider. The default set is `["SP", "SP2", "SP3"]`
include_unknown_set: bool, default False
If true, the index of all types not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
An one-hot vector of the hybridization type.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
"""
return one_hot_encode(str(atom.GetHybridization()), allowable_set,
include_unknown_set)
def get_atom_total_num_Hs_one_hot(
atom: RDKitAtom,
allowable_set: List[int] = DEFAULT_TOTAL_NUM_Hs_SET,
include_unknown_set: bool = True) -> List[float]:
"""Get an one-hot feature of the number of hydrogens which an atom has.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
allowable_set: List[int]
The number of hydrogens to consider. The default set is `[0, 1, ..., 4]`
include_unknown_set: bool, default True
If true, the index of all types not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
A one-hot vector of the number of hydrogens which an atom has.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
"""
return one_hot_encode(atom.GetTotalNumHs(), allowable_set,
include_unknown_set)
def get_atom_chirality_one_hot(atom: RDKitAtom) -> List[float]:
"""Get an one-hot feature about an atom chirality type.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
Returns
-------
List[float]
A one-hot vector of the chirality type. The first element
indicates "R", and the second element indicates "S".
"""
one_hot = [0.0, 0.0]
try:
chiral_type = atom.GetProp('_CIPCode')
if chiral_type == "R":
one_hot[0] = 1.0
elif chiral_type == "S":
one_hot[1] = 1.0
except:
pass
return one_hot
def get_atom_formal_charge(atom: RDKitAtom) -> List[float]:
"""Get a formal charge of an atom.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
Returns
-------
List[float]
A vector of the formal charge.
"""
return [float(atom.GetFormalCharge())]
def get_atom_formal_charge_one_hot(
atom: RDKitAtom,
allowable_set: List[int] = DEFAULT_FORMAL_CHARGE_SET,
include_unknown_set: bool = True) -> List[float]:
"""Get one hot encoding of formal charge of an atom.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
allowable_set: List[int]
The degree to consider. The default set is `[-2, -1, ..., 2]`
include_unknown_set: bool, default True
If true, the index of all types not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
A vector of the formal charge.
"""
return one_hot_encode(atom.GetFormalCharge(), allowable_set,
include_unknown_set)
def get_atom_partial_charge(atom: RDKitAtom) -> List[float]:
"""Get a partial charge of an atom.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
Returns
-------
List[float]
A vector of the parital charge.
Notes
-----
Before using this function, you must calculate `GasteigerCharge`
like `AllChem.ComputeGasteigerCharges(mol)`.
"""
gasteiger_charge = atom.GetProp('_GasteigerCharge')
if gasteiger_charge in ['-nan', 'nan', '-inf', 'inf']:
gasteiger_charge = 0.0
return [float(gasteiger_charge)]
def get_atom_total_degree_one_hot(
atom: RDKitAtom,
allowable_set: List[int] = DEFAULT_TOTAL_DEGREE_SET,
include_unknown_set: bool = True) -> List[float]:
"""Get an one-hot feature of the degree which an atom has.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
allowable_set: List[int]
The degree to consider. The default set is `[0, 1, ..., 5]`
include_unknown_set: bool, default True
If true, the index of all types not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
A one-hot vector of the degree which an atom has.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
"""
return one_hot_encode(atom.GetTotalDegree(), allowable_set,
include_unknown_set)
def get_atom_implicit_valence_one_hot(
atom: RDKitAtom,
allowable_set: List[int] = DEFAULT_ATOM_IMPLICIT_VALENCE_SET,
include_unknown_set: bool = True) -> List[float]:
"""Get an one-hot feature of implicit valence of an atom.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
allowable_set: List[int]
Atom implicit valence to consider. The default set is `[0, 1, ..., 6]`
include_unknown_set: bool, default True
If true, the index of all types not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
A one-hot vector of implicit valence an atom has.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
"""
return one_hot_encode(atom.GetImplicitValence(), allowable_set,
include_unknown_set)
def get_atom_explicit_valence_one_hot(
atom: RDKitAtom,
allowable_set: List[int] = DEFAULT_ATOM_EXPLICIT_VALENCE_SET,
include_unknown_set: bool = True) -> List[float]:
"""Get an one-hot feature of explicit valence of an atom.
Parameters
---------
atom: rdkit.Chem.rdchem.Atom
RDKit atom object
allowable_set: List[int]
Atom explicit valence to consider. The default set is `[1, ..., 6]`
include_unknown_set: bool, default True
If true, the index of all types not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
A one-hot vector of explicit valence an atom has.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
"""
return one_hot_encode(atom.GetExplicitValence(), allowable_set,
include_unknown_set)
#################################################################
# bond (edge) featurization
#################################################################
def get_bond_type_one_hot(bond: RDKitBond,
allowable_set: List[str] = DEFAULT_BOND_TYPE_SET,
include_unknown_set: bool = False) -> List[float]:
"""Get an one-hot feature of bond type.
Parameters
---------
bond: rdkit.Chem.rdchem.Bond
RDKit bond object
allowable_set: List[str]
The bond types to consider. The default set is `["SINGLE", "DOUBLE", "TRIPLE", "AROMATIC"]`.
include_unknown_set: bool, default False
If true, the index of all types not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
A one-hot vector of the bond type.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
"""
return one_hot_encode(str(bond.GetBondType()), allowable_set,
include_unknown_set)
def get_bond_is_in_same_ring_one_hot(bond: RDKitBond) -> List[float]:
"""Get an one-hot feature about whether atoms of a bond is in the same ring or not.
Parameters
---------
bond: rdkit.Chem.rdchem.Bond
RDKit bond object
Returns
-------
List[float]
A one-hot vector of whether a bond is in the same ring or not.
"""
return [int(bond.IsInRing())]
def get_bond_is_conjugated_one_hot(bond: RDKitBond) -> List[float]:
"""Get an one-hot feature about whether a bond is conjugated or not.
Parameters
---------
bond: rdkit.Chem.rdchem.Bond
RDKit bond object
Returns
-------
List[float]
A one-hot vector of whether a bond is conjugated or not.
"""
return [int(bond.GetIsConjugated())]
def get_bond_stereo_one_hot(bond: RDKitBond,
allowable_set: List[str] = DEFAULT_BOND_STEREO_SET,
include_unknown_set: bool = True) -> List[float]:
"""Get an one-hot feature of the stereo configuration of a bond.
Parameters
---------
bond: rdkit.Chem.rdchem.Bond
RDKit bond object
allowable_set: List[str]
The stereo configuration types to consider.
The default set is `["STEREONONE", "STEREOANY", "STEREOZ", "STEREOE"]`.
include_unknown_set: bool, default True
If true, the index of all types not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
A one-hot vector of the stereo configuration of a bond.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
"""
return one_hot_encode(str(bond.GetStereo()), allowable_set,
include_unknown_set)
def get_bond_graph_distance_one_hot(
bond: RDKitBond,
graph_dist_matrix: np.ndarray,
allowable_set: List[int] = DEFAULT_GRAPH_DISTANCE_SET,
include_unknown_set: bool = True) -> List[float]:
"""Get an one-hot feature of graph distance.
Parameters
---------
bond: rdkit.Chem.rdchem.Bond
RDKit bond object
graph_dist_matrix: np.ndarray
The return value of `Chem.GetDistanceMatrix(mol)`. The shape is `(num_atoms, num_atoms)`.
allowable_set: List[int]
The graph distance types to consider. The default set is `[1, 2, ..., 7]`.
include_unknown_set: bool, default False
If true, the index of all types not in `allowable_set` is `len(allowable_set)`.
Returns
-------
List[float]
A one-hot vector of the graph distance.
If `include_unknown_set` is False, the length is `len(allowable_set)`.
If `include_unknown_set` is True, the length is `len(allowable_set) + 1`.
"""
graph_dist = graph_dist_matrix[bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()]
return one_hot_encode(graph_dist, allowable_set, include_unknown_set)