-
Notifications
You must be signed in to change notification settings - Fork 174
/
oracle.py
1880 lines (1503 loc) · 59.7 KB
/
oracle.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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Author: TDC Team
# License: MIT
import pickle
import numpy as np
import os.path as op
from abc import abstractmethod
from functools import partial
from typing import List
import time, os, math, re
from packaging import version
import pkg_resources
try:
import rdkit
from rdkit import Chem, DataStructs
from rdkit.Chem import AllChem, Descriptors
import rdkit.Chem.QED as QED
from rdkit import rdBase
rdBase.DisableLog("rdApp.error")
from rdkit.Chem import rdMolDescriptors
from rdkit.six import iteritems
except:
raise ImportError(
"Please install rdkit by 'conda install -c conda-forge rdkit'! ")
try:
from scipy.stats.mstats import gmean
except:
raise ImportError("Please install rdkit by 'pip install scipy'! ")
try:
import networkx as nx
except:
raise ImportError("Please install networkx by 'pip install networkx'! ")
from ...utils import oracle_load
from ...utils import print_sys, install
mean2func = {
"geometric": gmean,
"arithmetic": np.mean,
}
SKLEARN_VERSION = version.parse(
pkg_resources.get_distribution("scikit-learn").version)
def smiles_to_rdkit_mol(smiles):
"""Convert smiles into rdkit's mol (molecule) format.
Args:
smiles: str, SMILES string.
Returns:
mol: rdkit.Chem.rdchem.Mol
"""
mol = Chem.MolFromSmiles(smiles)
# Sanitization check (detects invalid valence)
if mol is not None:
try:
Chem.SanitizeMol(mol)
except ValueError:
return None
return mol
def smiles_2_fingerprint_ECFP4(smiles):
"""Convert smiles into ECFP4 Morgan Fingerprint.
Args:
smiles: str, SMILES string.
Returns:
fp: rdkit.DataStructs.cDataStructs.UIntSparseIntVect
"""
molecule = smiles_to_rdkit_mol(smiles)
fp = AllChem.GetMorganFingerprint(molecule, 2)
return fp
def smiles_2_fingerprint_FCFP4(smiles):
"""Convert smiles into FCFP4 Morgan Fingerprint.
Args:
smiles: str, SMILES string.
Returns:
fp: rdkit.DataStructs.cDataStructs.UIntSparseIntVect
"""
molecule = smiles_to_rdkit_mol(smiles)
fp = AllChem.GetMorganFingerprint(molecule, 2, useFeatures=True)
return fp
def smiles_2_fingerprint_AP(smiles):
"""Convert smiles into Atom Pair Fingerprint.
Args:
smiles: str, SMILES string.
Returns:
fp: rdkit.DataStructs.cDataStructs.IntSparseIntVect
"""
molecule = smiles_to_rdkit_mol(smiles)
fp = AllChem.GetAtomPairFingerprint(molecule, maxLength=10)
return fp
def smiles_2_fingerprint_ECFP6(smiles):
"""Convert smiles into ECFP6 Fingerprint.
Args:
smiles: str, SMILES string.
Returns:
fp: rdkit.DataStructs.cDataStructs.UIntSparseIntVect
"""
molecule = smiles_to_rdkit_mol(smiles)
fp = AllChem.GetMorganFingerprint(molecule, 3)
return fp
fp2fpfunc = {
"ECFP4": smiles_2_fingerprint_ECFP4,
"FCFP4": smiles_2_fingerprint_FCFP4,
"AP": smiles_2_fingerprint_AP,
"ECFP6": smiles_2_fingerprint_ECFP6,
}
class ScoreModifier:
"""
Interface for score modifiers.
"""
@abstractmethod
def __call__(self, x):
"""
Apply the modifier on x.
Args:
x: float or np.array to modify
Returns:
float or np.array (depending on the type of x) after application of the distance function.
"""
class ChainedModifier(ScoreModifier):
"""
Calls several modifiers one after the other, for instance:
score = modifier3(modifier2(modifier1(raw_score)))
"""
def __init__(self, modifiers: List[ScoreModifier]) -> None:
"""
Args:
modifiers: modifiers to call in sequence.
The modifier applied last (and delivering the final score) is the last one in the list.
"""
self.modifiers = modifiers
def __call__(self, x):
score = x
for modifier in self.modifiers:
score = modifier(score)
return score
class LinearModifier(ScoreModifier):
"""
Score modifier that multiplies the score by a scalar (default: 1, i.e. do nothing).
"""
def __init__(self, slope=1.0):
self.slope = slope
def __call__(self, x):
return self.slope * x
class SquaredModifier(ScoreModifier):
"""
Score modifier that has a maximum at a given target value, and decreases
quadratically with increasing distance from the target value.
"""
def __init__(self, target_value: float, coefficient=1.0) -> None:
self.target_value = target_value
self.coefficient = coefficient
def __call__(self, x):
return 1.0 - self.coefficient * np.square(self.target_value - x)
class AbsoluteScoreModifier(ScoreModifier):
"""
Score modifier that has a maximum at a given target value, and decreases
linearly with increasing distance from the target value.
"""
def __init__(self, target_value: float) -> None:
self.target_value = target_value
def __call__(self, x):
return 1.0 - np.abs(self.target_value - x)
class GaussianModifier(ScoreModifier):
"""
Score modifier that reproduces a Gaussian bell shape.
"""
def __init__(self, mu: float, sigma: float) -> None:
self.mu = mu
self.sigma = sigma
def __call__(self, x):
return np.exp(-0.5 * np.power((x - self.mu) / self.sigma, 2.0))
class MinMaxGaussianModifier(ScoreModifier):
"""
Score modifier that reproduces a half Gaussian bell shape.
For minimize==True, the function is 1.0 for x <= mu and decreases to zero for x > mu.
For minimize==False, the function is 1.0 for x >= mu and decreases to zero for x < mu.
"""
def __init__(self, mu: float, sigma: float, minimize=False) -> None:
self.mu = mu
self.sigma = sigma
self.minimize = minimize
self._full_gaussian = GaussianModifier(mu=mu, sigma=sigma)
def __call__(self, x):
if self.minimize:
mod_x = np.maximum(x, self.mu)
else:
mod_x = np.minimum(x, self.mu)
return self._full_gaussian(mod_x)
MinGaussianModifier = partial(MinMaxGaussianModifier, minimize=True)
MaxGaussianModifier = partial(MinMaxGaussianModifier, minimize=False)
class ClippedScoreModifier(ScoreModifier):
r"""
Clips a score between specified low and high scores, and does a linear interpolation in between.
This class works as follows:
First the input is mapped onto a linear interpolation between both specified points.
Then the generated values are clipped between low and high scores.
"""
def __init__(self,
upper_x: float,
lower_x=0.0,
high_score=1.0,
low_score=0.0) -> None:
"""
Args:
upper_x: x-value from which (or until which if smaller than lower_x) the score is maximal
lower_x: x-value until which (or from which if larger than upper_x) the score is minimal
high_score: maximal score to clip to
low_score: minimal score to clip to
"""
assert low_score < high_score
self.upper_x = upper_x
self.lower_x = lower_x
self.high_score = high_score
self.low_score = low_score
self.slope = (high_score - low_score) / (upper_x - lower_x)
self.intercept = high_score - self.slope * upper_x
def __call__(self, x):
y = self.slope * x + self.intercept
return np.clip(y, self.low_score, self.high_score)
class SmoothClippedScoreModifier(ScoreModifier):
"""
Smooth variant of ClippedScoreModifier.
Implemented as a logistic function that has the same steepness as ClippedScoreModifier in the
center of the logistic function.
"""
def __init__(self,
upper_x: float,
lower_x=0.0,
high_score=1.0,
low_score=0.0) -> None:
"""
Args:
upper_x: x-value from which (or until which if smaller than lower_x) the score approaches high_score
lower_x: x-value until which (or from which if larger than upper_x) the score approaches low_score
high_score: maximal score (reached at +/- infinity)
low_score: minimal score (reached at -/+ infinity)
"""
assert low_score < high_score
self.upper_x = upper_x
self.lower_x = lower_x
self.high_score = high_score
self.low_score = low_score
# Slope of a standard logistic function in the middle is 0.25 -> rescale k accordingly
self.k = 4.0 / (upper_x - lower_x)
self.middle_x = (upper_x + lower_x) / 2
self.L = high_score - low_score
def __call__(self, x):
return self.low_score + self.L / (1 + np.exp(-self.k *
(x - self.middle_x)))
class ThresholdedLinearModifier(ScoreModifier):
"""
Returns a value of min(input, threshold)/threshold.
"""
def __init__(self, threshold: float) -> None:
self.threshold = threshold
def __call__(self, x):
return np.minimum(x, self.threshold) / self.threshold
# check the license for the code from readFragmentScores to CalculateScore here: https://github.com/EricTing/SAscore/blob/89d7689a85efed3cc918fb8ba6fe5cedf60b4a5a/src/sascorer.py#L134
_fscores = None
def readFragmentScores(name="fpscores"):
import gzip
global _fscores
# generate the full path filename:
# if name == "fpscores":
# name = op.join(previous_directory(op.dirname(__file__)), name)
name = oracle_load("fpscores")
try:
with open("oracle/fpscores.pkl", "rb") as f:
_fscores = pickle.load(f)
except EOFError:
import sys
sys.exit(
"TDC is hosted in Harvard Dataverse and it is currently under maintenance, please check back in a few hours or checkout https://dataverse.harvard.edu/."
)
outDict = {}
for i in _fscores:
for j in range(1, len(i)):
outDict[i[j]] = float(i[0])
_fscores = outDict
def numBridgeheadsAndSpiro(mol, ri=None):
nSpiro = rdMolDescriptors.CalcNumSpiroAtoms(mol)
nBridgehead = rdMolDescriptors.CalcNumBridgeheadAtoms(mol)
return nBridgehead, nSpiro
def calculateScore(m):
if _fscores is None:
readFragmentScores()
# fragment score
fp = rdMolDescriptors.GetMorganFingerprint(
m, 2) # <- 2 is the *radius* of the circular fingerprint
fps = fp.GetNonzeroElements()
score1 = 0.0
nf = 0
for bitId, v in iteritems(fps):
nf += v
sfp = bitId
score1 += _fscores.get(sfp, -4) * v
score1 /= nf
# features score
nAtoms = m.GetNumAtoms()
nChiralCenters = len(Chem.FindMolChiralCenters(m, includeUnassigned=True))
ri = m.GetRingInfo()
nBridgeheads, nSpiro = numBridgeheadsAndSpiro(m, ri)
nMacrocycles = 0
for x in ri.AtomRings():
if len(x) > 8:
nMacrocycles += 1
sizePenalty = nAtoms**1.005 - nAtoms
stereoPenalty = math.log10(nChiralCenters + 1)
spiroPenalty = math.log10(nSpiro + 1)
bridgePenalty = math.log10(nBridgeheads + 1)
macrocyclePenalty = 0.0
# ---------------------------------------
# This differs from the paper, which defines:
# macrocyclePenalty = math.log10(nMacrocycles+1)
# This form generates better results when 2 or more macrocycles are present
if nMacrocycles > 0:
macrocyclePenalty = math.log10(2)
score2 = (0.0 - sizePenalty - stereoPenalty - spiroPenalty - bridgePenalty -
macrocyclePenalty)
# correction for the fingerprint density
# not in the original publication, added in version 1.1
# to make highly symmetrical molecules easier to synthetise
score3 = 0.0
if nAtoms > len(fps):
score3 = math.log(float(nAtoms) / len(fps)) * 0.5
sascore = score1 + score2 + score3
# need to transform "raw" value into scale between 1 and 10
min = -4.0
max = 2.5
sascore = 11.0 - (sascore - min + 1) / (max - min) * 9.0
# smooth the 10-end
if sascore > 8.0:
sascore = 8.0 + math.log(sascore + 1.0 - 9.0)
if sascore > 10.0:
sascore = 10.0
elif sascore < 1.0:
sascore = 1.0
return sascore
"""Scores based on an ECFP classifier for activity."""
def load_pickled_model(name: str):
"""
Loading a pretrained model serialized with pickle.
Usually for sklearn models.
Args:
name: Name of the model to load.
Returns:
The model.
"""
try:
with open(name, "rb") as f:
model = pickle.load(f)
except EOFError:
import sys
sys.exit(
"TDC is hosted in Harvard Dataverse and it is currently under maintenance, please check back in a few hours or checkout https://dataverse.harvard.edu/."
)
return model
# clf_model = None
def load_drd2_model():
name = "oracle/drd2.pkl"
if SKLEARN_VERSION >= version.parse("0.24.0"):
name = "oracle/drd2_current.pkl"
else:
name = "oracle/drd2.pkl"
return load_pickled_model(name)
def fingerprints_from_mol(mol):
fp = AllChem.GetMorganFingerprint(mol, 3, useCounts=True, useFeatures=True)
size = 2048
nfp = np.zeros((1, size), np.int32)
for idx, v in fp.GetNonzeroElements().items():
nidx = idx % size
nfp[0, nidx] += int(v)
return nfp
def drd2(smile):
"""Evaluate DRD2 score of a SMILES string
Args:
smiles: str
Returns:
drd_score: float
"""
if "drd2_model" not in globals().keys():
global drd2_model
drd2_model = load_drd2_model()
mol = Chem.MolFromSmiles(smile)
if mol:
fp = fingerprints_from_mol(mol)
score = drd2_model.predict_proba(fp)[:, 1]
drd_score = float(score)
return drd_score
return 0.0
def load_cyp3a4_veith():
oracle_file = "oracle/cyp3a4_veith.pkl"
return load_pickled_model(oracle_file)
def cyp3a4_veith(smiles):
try:
from DeepPurpose import utils
except:
raise ImportError(
"Please install DeepPurpose by 'pip install DeepPurpose'")
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
if "cyp3a4_veith_model" not in globals().keys():
global cyp3a4_veith_model
cyp3a4_veith_model = load_cyp3a4_veith()
import warnings, os
warnings.filterwarnings("ignore")
X_drug = [smiles]
drug_encoding = "CNN"
y = [1]
X_pred = utils.data_process(X_drug=X_drug,
y=y,
drug_encoding=drug_encoding,
split_method="no_split")
# cyp3a4_veith_model = cyp3a4_veith_model.to("cuda:0")
y_pred = cyp3a4_veith_model.predict(X_pred)
return y_pred[0]
## from https://github.com/wengong-jin/iclr19-graph2graph/blob/master/props/properties.py
## from https://github.com/wengong-jin/multiobj-rationale/blob/master/properties.py
def similarity(smiles_a, smiles_b):
"""Evaluate Tanimoto similarity between 2 SMILES strings
Args:
smiles_a: str, SMILES string
smiles_b: str, SMILES string
Returns:
similarity score: float, between 0 and 1.
"""
if smiles_a is None or smiles_b is None:
return 0.0
amol = Chem.MolFromSmiles(smiles_a)
bmol = Chem.MolFromSmiles(smiles_b)
if amol is None or bmol is None:
return 0.0
fp1 = AllChem.GetMorganFingerprintAsBitVect(amol,
2,
nBits=2048,
useChirality=False)
fp2 = AllChem.GetMorganFingerprintAsBitVect(bmol,
2,
nBits=2048,
useChirality=False)
return DataStructs.TanimotoSimilarity(fp1, fp2)
def qed(smiles):
"""Evaluate QED score of a SMILES string
Args:
smiles: str
Returns:
qed_score: float, between 0 and 1.
"""
if smiles is None:
return 0.0
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return 0.0
return QED.qed(mol)
def penalized_logp(s):
"""Evaluate LogP score of a SMILES string
Args:
smiles: str
Returns:
logp_score: float, between - infinity and + infinity
"""
if s is None:
return -100.0
mol = Chem.MolFromSmiles(s)
if mol is None:
return -100.0
logP_mean = 2.4570953396190123
logP_std = 1.434324401111988
SA_mean = -3.0525811293166134
SA_std = 0.8335207024513095
cycle_mean = -0.0485696876403053
cycle_std = 0.2860212110245455
log_p = Descriptors.MolLogP(mol)
# SA = -sascorer.calculateScore(mol)
SA = -calculateScore(mol)
# cycle score
cycle_list = nx.cycle_basis(nx.Graph(Chem.rdmolops.GetAdjacencyMatrix(mol)))
if len(cycle_list) == 0:
cycle_length = 0
else:
cycle_length = max([len(j) for j in cycle_list])
if cycle_length <= 6:
cycle_length = 0
else:
cycle_length = cycle_length - 6
cycle_score = -cycle_length
normalized_log_p = (log_p - logP_mean) / logP_std
normalized_SA = (SA - SA_mean) / SA_std
normalized_cycle = (cycle_score - cycle_mean) / cycle_std
return normalized_log_p + normalized_SA + normalized_cycle
def SA(s):
"""Evaluate SA score of a SMILES string
Args:
smiles: str
Returns:
SAscore: float
"""
if s is None:
return 100
mol = Chem.MolFromSmiles(s)
if mol is None:
return 100
SAscore = calculateScore(mol)
return SAscore
def load_gsk3b_model():
gsk3_model_path = "oracle/gsk3b.pkl"
if SKLEARN_VERSION >= version.parse("0.24.0"):
gsk3_model_path = "oracle/gsk3b_current.pkl"
return load_pickled_model(gsk3_model_path)
def gsk3b(smiles):
"""Evaluate GSK3B score of a SMILES string
Args:
smiles: str
Returns:
gsk3_score: float, between 0 and 1.
"""
if "gsk3_model" not in globals().keys():
global gsk3_model
gsk3_model = load_gsk3b_model()
molecule = smiles_to_rdkit_mol(smiles)
fp = AllChem.GetMorganFingerprintAsBitVect(molecule, 2, nBits=2048)
features = np.zeros((1,))
DataStructs.ConvertToNumpyArray(fp, features)
fp = features.reshape(1, -1)
gsk3_score = gsk3_model.predict_proba(fp)[0, 1]
return gsk3_score
class jnk3:
"""Evaluate JSK3 score of a SMILES string
Args:
smiles: str
Returns:
jnk3_score: float , between 0 and 1.
"""
def __init__(self):
jnk3_model_path = "oracle/jnk3.pkl"
if SKLEARN_VERSION >= version.parse("0.24.0"):
jnk3_model_path = "oracle/jnk3_current.pkl"
self.jnk3_model = load_pickled_model(jnk3_model_path)
def __call__(self, smiles):
molecule = smiles_to_rdkit_mol(smiles)
fp = AllChem.GetMorganFingerprintAsBitVect(molecule, 2, nBits=2048)
features = np.zeros((1,))
DataStructs.ConvertToNumpyArray(fp, features)
fp = features.reshape(1, -1)
jnk3_score = self.jnk3_model.predict_proba(fp)[0, 1]
return jnk3_score
class AtomCounter:
def __init__(self, element):
"""
Args:
element: element to count within a molecule
"""
self.element = element
def __call__(self, mol):
"""
Count the number of atoms of a given type.
Args:
mol: molecule
Returns:
The number of atoms of the given type.
"""
# if the molecule contains H atoms, they may be implicit, so add them
if self.element == "H":
mol = Chem.AddHs(mol)
return sum(1 for a in mol.GetAtoms() if a.GetSymbol() == self.element)
def parse_molecular_formula(formula):
"""
Parse a molecular formulat to get the element types and counts.
Args:
formula: molecular formula, f.i. "C8H3F3Br"
Returns:
A list of tuples containing element types and number of occurrences.
"""
import re
matches = re.findall(r"([A-Z][a-z]*)(\d*)", formula)
# Convert matches to the required format
results = []
for match in matches:
# convert count to an integer, and set it to 1 if the count is not visible in the molecular formula
count = 1 if not match[1] else int(match[1])
results.append((match[0], count))
return results
def smiles2formula(smiles):
from rdkit.Chem.rdMolDescriptors import CalcMolFormula
mol = Chem.MolFromSmiles(smiles)
formula = CalcMolFormula(mol)
return formula
def canonicalize(smiles: str, include_stereocenters=True):
"""
Canonicalize the SMILES strings with RDKit.
The algorithm is detailed under https://pubs.acs.org/doi/full/10.1021/acs.jcim.5b00543
Args:
smiles: SMILES string to canonicalize
include_stereocenters: whether to keep the stereochemical information in the canonical SMILES string
Returns:
Canonicalized SMILES string, None if the molecule is invalid.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is not None:
return Chem.MolToSmiles(mol, isomericSmiles=include_stereocenters)
else:
return None
class Isomer_scoring_prev:
def __init__(self, target_smiles, means="geometric"):
assert means in ["geometric", "arithmetic"]
if means == "geometric":
self.mean_func = gmean
else:
self.mean_func = np.mean
atom2cnt_lst = parse_molecular_formula(target_smiles)
total_atom_num = sum([cnt for atom, cnt in atom2cnt_lst])
self.total_atom_modifier = GaussianModifier(mu=total_atom_num,
sigma=2.0)
self.AtomCounter_Modifier_lst = [((AtomCounter(atom)),
GaussianModifier(mu=cnt, sigma=1.0))
for atom, cnt in atom2cnt_lst]
def __call__(self, test_smiles):
molecule = smiles_to_rdkit_mol(test_smiles)
all_scores = []
for atom_counter, modifier_func in self.AtomCounter_Modifier_lst:
all_scores.append(modifier_func(atom_counter(molecule)))
### total atom number
atom2cnt_lst = parse_molecular_formula(test_smiles)
# ## todo add Hs
total_atom_num = sum([cnt for atom, cnt in atom2cnt_lst])
all_scores.append(self.total_atom_modifier(total_atom_num))
return self.mean_func(all_scores)
class Isomer_scoring:
def __init__(self, target_smiles, means="geometric"):
assert means in ["geometric", "arithmetic"]
if means == "geometric":
self.mean_func = gmean
else:
self.mean_func = np.mean
atom2cnt_lst = parse_molecular_formula(target_smiles)
total_atom_num = sum([cnt for atom, cnt in atom2cnt_lst])
self.total_atom_modifier = GaussianModifier(mu=total_atom_num,
sigma=2.0)
self.AtomCounter_Modifier_lst = [((AtomCounter(atom)),
GaussianModifier(mu=cnt, sigma=1.0))
for atom, cnt in atom2cnt_lst]
def __call__(self, test_smiles):
#### difference 1
#### add hydrogen atoms
test_smiles = canonicalize(test_smiles)
test_mol = Chem.MolFromSmiles(test_smiles)
test_mol2 = Chem.AddHs(test_mol)
test_smiles = Chem.MolToSmiles(test_mol2)
molecule = smiles_to_rdkit_mol(test_smiles)
all_scores = []
for atom_counter, modifier_func in self.AtomCounter_Modifier_lst:
all_scores.append(modifier_func(atom_counter(molecule)))
#### difference 2
### total atom number
test_formula = smiles2formula(test_smiles)
atom2cnt_lst = parse_molecular_formula(test_formula)
# atom2cnt_lst = parse_molecular_formula(test_smiles)
# ## todo add Hs
total_atom_num = sum([cnt for atom, cnt in atom2cnt_lst])
all_scores.append(self.total_atom_modifier(total_atom_num))
return self.mean_func(all_scores)
def isomer_meta_prev(target_smiles, means="geometric"):
return Isomer_scoring_prev(target_smiles, means=means)
def isomer_meta(target_smiles, means="geometric"):
return Isomer_scoring(target_smiles, means=means)
isomers_c7h8n2o2_prev = isomer_meta_prev(target_smiles="C7H8N2O2",
means="geometric")
isomers_c9h10n2o2pf2cl_prev = isomer_meta_prev(target_smiles="C9H10N2O2PF2Cl",
means="geometric")
isomers_c11h24_prev = isomer_meta_prev(target_smiles="C11H24",
means="geometric")
isomers_c7h8n2o2 = isomer_meta(target_smiles="C7H8N2O2", means="geometric")
isomers_c9h10n2o2pf2cl = isomer_meta(target_smiles="C9H10N2O2PF2Cl",
means="geometric")
isomers_c11h24 = isomer_meta(target_smiles="C11H24", means="geometric")
class rediscovery_meta:
def __init__(self, target_smiles, fp="ECFP4"):
self.similarity_func = fp2fpfunc[fp]
self.target_fp = self.similarity_func(target_smiles)
def __call__(self, test_smiles):
test_fp = self.similarity_func(test_smiles)
similarity_value = DataStructs.TanimotoSimilarity(
self.target_fp, test_fp)
return similarity_value
class similarity_meta:
def __init__(self, target_smiles, fp="FCFP4", modifier_func=None):
self.similarity_func = fp2fpfunc[fp]
self.target_fp = self.similarity_func(target_smiles)
self.modifier_func = modifier_func
def __call__(self, test_smiles):
test_fp = self.similarity_func(test_smiles)
similarity_value = DataStructs.TanimotoSimilarity(
self.target_fp, test_fp)
if self.modifier_func is None:
modifier_score = similarity_value
else:
modifier_score = self.modifier_func(similarity_value)
return modifier_score
celecoxib_rediscovery = rediscovery_meta(
target_smiles="CC1=CC=C(C=C1)C1=CC(=NN1C1=CC=C(C=C1)S(N)(=O)=O)C(F)(F)F",
fp="ECFP4")
troglitazone_rediscovery = rediscovery_meta(
target_smiles="Cc1c(C)c2OC(C)(COc3ccc(CC4SC(=O)NC4=O)cc3)CCc2c(C)c1O",
fp="ECFP4")
thiothixene_rediscovery = rediscovery_meta(
target_smiles="CN(C)S(=O)(=O)c1ccc2Sc3ccccc3C(=CCCN4CCN(C)CC4)c2c1",
fp="ECFP4")
similarity_modifier = ClippedScoreModifier(upper_x=0.75)
aripiprazole_similarity = similarity_meta(
target_smiles="Clc4cccc(N3CCN(CCCCOc2ccc1c(NC(=O)CC1)c2)CC3)c4Cl",
fp="FCFP4",
modifier_func=similarity_modifier,
)
albuterol_similarity = similarity_meta(
target_smiles="CC(C)(C)NCC(O)c1ccc(O)c(CO)c1",
fp="FCFP4",
modifier_func=similarity_modifier,
)
mestranol_similarity = similarity_meta(
target_smiles="COc1ccc2[C@H]3CC[C@@]4(C)[C@@H](CC[C@@]4(O)C#C)[C@@H]3CCc2c1",
fp="AP",
modifier_func=similarity_modifier,
)
class median_meta:
def __init__(
self,
target_smiles_1,
target_smiles_2,
fp1="ECFP6",
fp2="ECFP6",
modifier_func1=None,
modifier_func2=None,
means="geometric",
):
self.similarity_func1 = fp2fpfunc[fp1]
self.similarity_func2 = fp2fpfunc[fp2]
self.target_fp1 = self.similarity_func1(target_smiles_1)
self.target_fp2 = self.similarity_func2(target_smiles_2)
self.modifier_func1 = modifier_func1
self.modifier_func2 = modifier_func2
assert means in ["geometric", "arithmetic"]
self.mean_func = mean2func[means]
def __call__(self, test_smiles):
test_fp1 = self.similarity_func1(test_smiles)
test_fp2 = (test_fp1 if self.similarity_func2 == self.similarity_func1
else self.similarity_func2(test_smiles))
similarity_value1 = DataStructs.TanimotoSimilarity(
self.target_fp1, test_fp1)
similarity_value2 = DataStructs.TanimotoSimilarity(
self.target_fp2, test_fp2)
if self.modifier_func1 is None:
modifier_score1 = similarity_value1
else:
modifier_score1 = self.modifier_func1(similarity_value1)
if self.modifier_func2 is None:
modifier_score2 = similarity_value2
else:
modifier_score2 = self.modifier_func2(similarity_value2)
final_score = self.mean_func([modifier_score1, modifier_score2])
return final_score
camphor_smiles = "CC1(C)C2CCC1(C)C(=O)C2"
menthol_smiles = "CC(C)C1CCC(C)CC1O"
median1 = median_meta(
target_smiles_1=camphor_smiles,
target_smiles_2=menthol_smiles,
fp1="ECFP4",
fp2="ECFP4",
modifier_func1=None,