forked from cosconatilab/PyRMD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PyRMD_v1.02.py
2063 lines (1552 loc) · 73.2 KB
/
PyRMD_v1.02.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
#!/usr/bin/env python
# coding: utf-8
# PyRMD: AI-powered Virtual Screening
# Copyright (C) 2021 Dr. Giorgio Amendola, Prof. Sandro Cosconati
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# If you used PyRMD in your work, please cite the article:
# <https://pubs.acs.org/doi/10.1021/acs.jcim.1c00653>
#
# Please check our GitHub page for more information
# <https://github.com/cosconatilab/PyRMD>
#
# In[1]:
#Imports
import os
import re
import time
from pathlib import Path
import subprocess
import rdkit
from rdkit import Chem
from rdkit.Chem import PandasTools
from rdkit.Chem import Descriptors
from rdkit.Chem.SaltRemover import SaltRemover
from rdkit import rdBase
from rdkit.Chem import rdMHFPFingerprint
from rdkit.ML.Scoring import Scoring
from rdkit.Chem.AtomPairs import Torsions
from rdkit import DataStructs
import numpy as np, scipy.stats as st
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
import sklearn
from sklearn.model_selection import StratifiedKFold, KFold, RepeatedStratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import average_precision_score
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import plot_precision_recall_curve
from sklearn.metrics import average_precision_score
import statsmodels.stats.api as sms
import openbabel as ob
from openbabel import pybel
import warnings
warnings.filterwarnings('ignore')
from configparser import ConfigParser
import argparse
import sys
import gc
# In[2]:
default_config='''[MODE]
#Indicate if the program is to run in "benchmark" or "screening" mode -- Default: benchmark
mode=benchmark
#Indicate the database file(s) to screen for the screening mode, otherwise leave the entry blank
db_to_screen =
#Specify the output file for the screening mode
screening_output = database_predictions.csv
#Indicate if in screening mode the active compounds should also be converted in a SDF file -- True or False -- Default: False
sdf_results= False
# For benchmark mode, indicate the file where to output the benchmark results
benchmark_file = benchmark_results.csv
[TRAINING_DATASETS]
# Indicate if one or more ChEMBL databases will be used as training sets -- True or False -- Default: True
use_chembl = True
#Indicate the CHEMBL database(s) file path, otherwise leave the entry blank
chembl_file =
# Set to True if one or more non-CHEMBL databases of active compounds are to be used for training the algorithm, otherwise set to False -- Default: False
use_actives = False
#Indicate the non-CHEMBL active compounds database(s) (SMILES file) path, otherwise leave the entry blank
actives_file =
# Set to True if one or more non-CHEMBL databases(s) of inactive compounds are to be used for training the algorithm, otherwise set to False
use_inactives = False
#Indicate the non-CHEMBL inactive compounds database(s) (SMILES file) file path, otherwise leave the entry blank
inactives_file =
[FINGERPRINTS]
#Fingerprint type - supported formats: rdkit, tt, mhfp, avalon, and ecfp -- Default: mhfp
#For fcfp set fp_type = ecfp and features = True
fp_type = mhfp
# lenght of the fingerprint - typical lenghts are 1024, 2048, and 4096 - longer fingerprints require more memory and are slower to process -- Default: 2048
nbits = 2048
# Include explicit hydrogens in the fingerprint: True or False -- Default: True
explicit_hydrogens = True
#ecfp/mhfp specific parameters
iterations = 3
chirality = False
#ecfp specific parameters
redundancy = True
features = False
[DECOYS]
#Set to True if external decoys are to be added to the test set for benchmarking the algorithm, otherwise set to False -- Default: False
use_decoys = False
#In case external decoy compounds are to be added to the test set for the benchmark, indicate the decoy database file path, otherwise leave the entry blank
decoys_file =
# Particularly large decoy databases may severely slow down the benchmark process, setting a sample number of decoys to employ can help speed it up -- Default: 1000000
sample_number = 1000000
[CHEMBL_THRESHOLDS]
# Compounds will be considered active if they are reported to have a value of IC50, EC50, Ki, Kd, or potency, inferior to the "activity_threshold" expressed in nM. They will be classified as inactive if their IC50, EC50, Ki, Kd, or potency will be greater than the "inactivity_threshold" expressed in nM, or if their inhibition rate is lower than the "inhibition_threshold" rate -- Default values: activity_threshold = 1001; inactivity_threshold = 39999; inhibition_threshold = 11
activity_threshold = 1001
inactivity_threshold = 39999
inhibition_threshold = 11
[KFOLD_PARAMETERS]
#For statical benchmarking purposes, indicate the number of splits for the benchmark mode -- Default: 5
n_splits = 5
#For statical benchmarking purposes, indicate how many times the benchmarking calculation should be run -- Default: 3
n_repeats = 3
[TRAINING_PARAMETERS]
# Cutoff values that set the percentile of the distance between the compounds in the training set and their projections in the training linear subspace. The resulting maximum projection distance, the epsilon parameter, will be used to classify unknown compounds. Insert a float ranging from 0 to 1 -- Default: 0.95
epsilon_cutoff_actives=0.95
epsilon_cutoff_inactives=0.95
[STAT_PARAMETERS]
# F-Score beta value. Beta > 1 gives more weight to TPR, while beta < 1 favors precision.
beta= 1
# Bedroc alpha value.
alpha = 0.20
[FILTER]
#Filter from the SCREENED DATABASE compounds that are not within the specified ranges set below: True or False
filter_properties = False
# If the properties of a compound are not within the specified ranges (specified as integers), the compound will be discarded
molwt_min = 200
logp_min = -5
hdonors_min = 0
haccept_min =0
rotabonds_min =0
heavat_min = 15
molwt_max = 600
logp_max = 5
hdonors_max = 6
haccept_max = 11
rotabonds_max = 9
heavat_max = 51
'''
p = Path('temp_conf_8761.ini')
p.write_text(default_config)
# In[3]:
ap = argparse.ArgumentParser()
argv = sys.argv[1:]
if len(argv) ==0:
p = Path('default_config.ini')
p.write_text(default_config)
print('Configuration file path missing, a default_config.ini file has been generated to use as template')
os.remove('temp_conf_8761.ini')
sys.exit()
ap.add_argument('config', nargs=1, help='configuration file path')
config_file = vars(ap.parse_args())['config']
# In[4]:
def string_or_list(prog_input):
input_list=prog_input.split()
if len(input_list) ==1:
return input_list[0]
elif len(input_list) >1:
return input_list
else:
return prog_input
# In[5]:
config = ConfigParser()
config.read('temp_conf_8761.ini')
config.read(config_file)
default_keys = ['default','standard','']
os.remove('temp_conf_8761.ini')
#MODE
mode=config.get('MODE','mode')
verbose=False
score=True
sdf_results=config.getboolean('MODE','sdf_results')
db_to_screen= string_or_list(config.get('MODE','db_to_screen'))
benchmark_file= config.get('MODE','benchmark_file')
gray = False
inactives_similarity = False
inactives_similarity_file = None
screening_output = config.get('MODE','screening_output')
temporal = False
temporal_file = None
#TRAINING DATASETS
use_chembl=config.getboolean('TRAINING_DATASETS','use_chembl')
chembl_file = string_or_list(config.get('TRAINING_DATASETS','chembl_file'))
use_external_actives=config.getboolean('TRAINING_DATASETS','use_actives')
use_external_inactives= config.getboolean('TRAINING_DATASETS','use_inactives')
actives_file= string_or_list(config.get('TRAINING_DATASETS','actives_file'))
inactives_file= string_or_list(config.get('TRAINING_DATASETS','inactives_file'))
#Fingerprints Parameters
fp_type = config.get('FINGERPRINTS','fp_type')
explicit_hydrogens = config.getboolean('FINGERPRINTS','explicit_hydrogens')
iterations = config.getint('FINGERPRINTS','iterations')
nbits = config.getint('FINGERPRINTS','nbits')
chirality = config.getboolean('FINGERPRINTS','chirality')
redundancy = config.getboolean('FINGERPRINTS','redundancy')
features = config.getboolean('FINGERPRINTS','features')
#DECOYS
use_external_decoys=config.getboolean('DECOYS','use_decoys')
decoys_file = string_or_list(config.get('DECOYS','decoys_file'))
sample_number=config.getint('DECOYS','sample_number')
#CHEMBL THRESHOLDS
activity_threshold = config.getint('CHEMBL_THRESHOLDS','activity_threshold')
inactivity_threshold = config.getint('CHEMBL_THRESHOLDS','inactivity_threshold')
inhibition_threshold = config.getint('CHEMBL_THRESHOLDS','inhibition_threshold')
#KFOLD PARAMETERS
n_splits = config.getint('KFOLD_PARAMETERS','n_splits')
n_repeats = config.getint('KFOLD_PARAMETERS','n_repeats')
#TRAINING PARAMETERS
threshold = config.getfloat('TRAINING_PARAMETERS','epsilon_cutoff_actives')
threshold_i = config.getfloat('TRAINING_PARAMETERS','epsilon_cutoff_inactives')
discard_inactives= False
similarity_thres= None
#STAT PARAMETERS
beta = config.getfloat('STAT_PARAMETERS','beta')
alpha = config.getfloat('STAT_PARAMETERS','alpha')
#FILTER
filter_pains = True
filter_properties = config.getboolean('FILTER','filter_properties')
molwt_min = config.getint('FILTER','molwt_min')
logp_min = config.getint('FILTER','logp_min')
hdonors_min = config.getint('FILTER','hdonors_min')
haccept_min = config.getint('FILTER','haccept_min')
rotabonds_min = config.getint('FILTER','rotabonds_min')
heavat_min = config.getint('FILTER','heavat_min')
molwt_max = config.getint('FILTER','molwt_max')
logp_max = config.getint('FILTER','logp_max')
hdonors_max = config.getint('FILTER','hdonors_max')
haccept_max = config.getint('FILTER','haccept_max')
rotabonds_max = config.getint('FILTER','rotabonds_max')
heavat_max = config.getint('FILTER','heavat_max')
# In[6]:
#CONFIG CHECKS
if use_chembl:
if type(chembl_file) == list:
for i in chembl_file:
if not os.path.isfile(i):
print(f'ERROR: The indicated ChEMBL csv file {i} does not exist')
sys.exit()
elif type(chembl_file) == str:
if not os.path.isfile(chembl_file):
print(f'ERROR: The indicated ChEMBL csv file {chembl_file} does not exist')
sys.exit()
if use_external_actives:
if type(actives_file) == list:
for i in actives_file:
if not os.path.isfile(i):
print(f'ERROR: The indicated active database file {i} does not exist')
sys.exit()
elif type(actives_file) == str:
if not os.path.isfile(actives_file):
print(f'ERROR: The indicated active database file {actives_file} does not exist')
sys.exit()
if use_external_inactives:
if type(inactives_file) == list:
for i in inactives_file:
if not os.path.isfile(i):
print(f'ERROR: The indicated inactive database file {i} does not exist')
sys.exit()
elif type(inactives_file) == str:
if not os.path.isfile(inactives_file):
print(f'ERROR: The indicated inactive database file {inactives_file} does not exist')
sys.exit()
if mode=='screening':
if type(db_to_screen) == list:
for i in db_to_screen:
if not os.path.isfile(i):
print(f'ERROR: The indicated database to screen file {i} does not exist')
sys.exit()
elif type(db_to_screen) == str:
if not os.path.isfile(db_to_screen):
print(f'ERROR: The indicated database file screen file {db_to_screen} does not exist')
sys.exit()
if type(screening_output) != str:
screening_output = 'database_predictions.csv'
elif len(screening_output) < 2:
screening_output = 'database_predictions.csv'
else:
if use_external_decoys:
if type(decoys_file) == list:
for i in decoys_file:
if not os.path.isfile(i):
print(f'ERROR: The indicated decoys database file {i} does not exist')
sys.exit()
elif type(decoys_file) == str:
if not os.path.isfile(decoys_file):
print(f'ERROR: The indicated decoys database file {decoys_file} does not exist')
sys.exit()
if fp_type == 'mhfp':
mhfp_encoder = Chem.rdMHFPFingerprint.MHFPEncoder(nbits)
elif fp_type == 'avalon':
from rdkit.Avalon import pyAvalonTools
# # DB preparation functions
# In[7]:
def bitjoiner(fp):
strfp= []
for i in (list(fp)):
strfp.append(str(i))
return "".join(strfp)
###############################################
def get_fingerprints_ecfp(df,string=True,keep_old=False,verbose=verbose,drop_zeros=True,fp_sim=False):
#print('Preparing database...')
start_time=time.time()
counter= 0
fps=[]
fp_string=[]
ligprepped_smiles=[]
fps_sim=[]
percentages=[20,40,60,80,100]
smiles = df['Smiles']
zero_fp=np.zeros(nbits)
zero_fp = np.array([int(x) for x in list(zero_fp)])
zero_fp_str = bitjoiner(zero_fp)
l=len(df)
print('Database Preparation: Stripping salts...')
print('Database Preparation: Calculating tautomeric and protonation states for physiological pH...')
if fp_type =='ecfp':
print(f'Database Preparation: Converting in {fp_type.upper()} fingerprints, vectors of {nbits} bits with a radius of {iterations}...')
elif (fp_type =='rdkit') or (fp_type == 'avalon'):
print(f'Database Preparation: Converting in {fp_type.upper()} fingerprints, vectors of {nbits} bits...')
elif fp_type =='tt':
print(f'Database Preparation: Converting in Topological Torsions fingerprints, vectors of {nbits} bits...')
else:
print(f'Database Preparation: Converting in {fp_type.upper()} fingerprints, with {nbits} permutations and a radius of {iterations}...')
def calculator(smile):
nonlocal counter
nonlocal percentages
if verbose == False:
rdBase.DisableLog('rdApp.error')
df_title_column=df['Title']
title_name=df_title_column.iloc[counter]
#print(title_name)
try:
try:
mol = pybel.readstring("smi",smile)
mol.OBMol.StripSalts()
mol.OBMol.AddHydrogens(False,True)
mol.OBMol.ConvertDativeBonds()
new_smile= mol.write().rstrip()
mol_rd = Chem.MolFromSmiles(new_smile)
if explicit_hydrogens:
mol_rd=Chem.RemoveHs(mol_rd)
mol_rd=Chem.AddHs(mol_rd)
if fp_type == 'ecfp':
fp = Chem.AllChem.GetMorganFingerprintAsBitVect(mol_rd, iterations, nBits = nbits, useChirality=chirality, useFeatures=features, includeRedundantEnvironments=redundancy )
fp1 = fp.ToBitString()
fp1 = np.array([int(x) for x in list(fp1)])
elif fp_type == 'rdkit':
fp = Chem.RDKFingerprint(mol_rd, fpSize=nbits)
fp1 = fp.ToBitString()
fp1 = np.array([int(x) for x in list(fp1)])
elif fp_type == 'mhfp':
fp = mhfp_encoder.EncodeMol(mol_rd, radius= iterations, isomeric=chirality)
fp1 = np.array(fp)
elif fp_type == 'tt':
fp=Torsions.GetHashedTopologicalTorsionFingerprint(mol_rd,nbits,includeChirality=chirality)
fp1 = np.array([int(x) for x in list(fp)])
elif fp_type == 'avalon':
fp = pyAvalonTools.GetAvalonFP(mol_rd,nBits=nbits)
fp1 = np.array([int(x) for x in list(fp)])
except:
if verbose:
print(f'Database Preparation: Trying to fix {title_name}')
print(f'-- {title_name} SMILES string: {smile}')
mol = pybel.readstring("smi",smile)
mol.OBMol.StripSalts()
if "[C-]#[N+]" in smile:
mol.OBMol.AddHydrogens(False,True)
else:
mol.OBMol.AddHydrogens(False,False)
mol.OBMol.ConvertDativeBonds()
new_smile= mol.write().rstrip()
mol_rd = Chem.MolFromSmiles(new_smile)
if explicit_hydrogens:
mol_rd=Chem.RemoveHs(mol_rd)
mol_rd=Chem.AddHs(mol_rd)
if fp_type == 'ecfp':
fp = Chem.AllChem.GetMorganFingerprintAsBitVect(mol_rd, iterations, nBits = nbits, useChirality=chirality, useFeatures=features, includeRedundantEnvironments=redundancy )
fp1 = fp.ToBitString()
fp1 = np.array([int(x) for x in list(fp1)])
elif fp_type == 'rdkit':
fp = Chem.RDKFingerprint(mol_rd, fpSize=nbits)
fp1 = fp.ToBitString()
fp1 = np.array([int(x) for x in list(fp1)])
elif fp_type == 'mhfp':
fp = mhfp_encoder.EncodeMol(mol_rd, radius= iterations, isomeric=chirality)
fp1 = np.array(fp)
elif fp_type == 'tt':
fp=Torsions.GetHashedTopologicalTorsionFingerprint(mol_rd,nbits,includeChirality=chirality)
fp1 = np.array([int(x) for x in list(fp)])
elif fp_type == 'avalon':
fp = pyAvalonTools.GetAvalonFP(mol_rd,nBits=nbits)
fp1 = np.array([int(x) for x in list(fp)])
if verbose:
print(f'-- {title_name} fixed with the following SMILES string {new_smile}')
except:
if verbose:
print(f'WARNING: {title_name} COULD NOT be fixed and converted in fingerprints.')
else:
print(f'WARNING: {title_name} COULD NOT be converted in fingerprints.')
new_smile= smile
fp=np.zeros(nbits)
fp1 = zero_fp
fp_string.append(bitjoiner(fp1))
fps.append(fp1)
ligprepped_smiles.append(new_smile)
fps_sim.append(fp)
percentage = int(100*(counter/l))
if percentage in percentages:
if verbose:
print(f'{(percentage):.0f}% done')
percentages.remove(percentage)
counter = counter +1
return None
smiles.apply(calculator)
if fp_sim:
df['fp_sim'] = fps_sim
df['fp_string'] = fp_string
df['fp'] = fps
if keep_old==True:
df['Old Smiles']=df['Smiles']
df['Smiles'] = ligprepped_smiles
if drop_zeros:
df=df[df['fp_string']!=zero_fp_str]
df.reset_index(inplace = True)
df = df.drop(['index'], axis = 1)
if not string:
df = df.drop(['fp_string'], axis = 1)
if verbose:
print(f'Database loaded in {(time.time() - start_time):.2f} seconds')
#print('Preparation complete')
del fps
del fp_string
del ligprepped_smiles
del fps_sim
return df
######################################
def file_reader(filename):
cols = 2
def index_namer(name):
new_name = (f'cmp_{str(name)}')
return new_name
def is_smile(items):
if type(items) != list:
if type(items) == str:
temp=[]
temp.append(items)
items=temp
else:
items =list(items)
for i in items:
try:
mol = pybel.readstring("smi",i)
return True
except:
pass
return False
def column_title_smiles(row):
for i in row:
if 'smile' in i.lower():
return i
return False
def recognizer(item):
nonlocal cols
if type(item)==pd.core.frame.DataFrame:
df=item
elif type(item)==str:
try:
df = pd.read_csv(item, sep=None)
cols = len(df.columns)
except Exception as mye:
if 'fields' in str(mye):
df= pd.read_csv(item,header=None)
cols=1
else:
print('ERROR: Could not recognize file format')
sys.exit()
if cols==1:
df.rename(columns={0:'Smiles'}, inplace=True)
if not (is_smile(df.iloc[0][0])):
df.drop(0,inplace=True)
df.reset_index(inplace=True, drop=True)
df['Title']=df.index
df['Title']= df['Title'].apply(index_namer)
else:
if 'Molecule ChEMBL ID' in (list(df.columns)):
df.rename(columns={'Molecule ChEMBL ID':'Title'}, inplace=True)
elif column_title_smiles(df.columns):
if column_title_smiles(df.columns) != 'Smiles':
df.rename(columns={column_title_smiles(df.columns):'Smiles'}, inplace=True)
for i in df.columns:
if 'title' in i.lower():
if i != 'Title':
df.rename(columns={i:'Title'}, inplace=True)
break
if 'Title' not in (list(df.columns)):
for i in df.columns:
if i != 'Smiles':
df.rename(columns={i:'Title'}, inplace=True)
break
else:
df = pd.read_csv(item,header=None,sep=None)
exit=0
for i in range(len(df)):
for j in range(len(df.columns)):
if is_smile(df.iloc[i][j]):
if j !=0:
df.rename(columns={j:'Smiles', 0:'Title'}, inplace=True)
exit=1
else:
df.rename(columns={0:'Smiles', 1:'Title'}, inplace=True)
exit=1
break
if exit==1:
break
return df
try:
if type(filename) == list:
print('Database preparation: Merging multiple entries in a single dataset...')
for i in range(len(filename)):
if i == 0:
df = recognizer(filename[i])
else:
df_2 = recognizer(filename[i])
df = pd.concat([df,df_2],ignore_index=True)
filename=df
else:
df=recognizer(filename)
return df
except UnboundLocalError:
raise ValueError('Could not recognize file format')
#################################################
def load_decoys(filename,force_sample=True,sample_number=sample_number):
df=file_reader(filename)
original_decoy_num = len(df.iloc[:,0])
df = df.sort_values(by=['Title'])
df = df.drop_duplicates(subset = 'Title', keep = 'first')
df = df.dropna(subset = ['Smiles'])
if force_sample==True:
if len(df['Title']) > sample_number:
df = df.sample(n=sample_number)
df.reset_index(inplace = True)
df = df.drop('index', axis = 1)
df = get_fingerprints_ecfp(df)
df = df.drop_duplicates(subset = 'fp_string', keep = 'first')
df.reset_index(inplace = True)
df = df.drop(['index','fp_string'], axis = 1)
return original_decoy_num, df
#######################################################
#RETURNS INTER-SIMILARITY BETWEEN DATAFRAMES
def calculate_similarity(df_1,df_2,del_ones=False):
df=df_1.copy()
df2=df_2.copy()
fp_2 = df2['fp_sim']
fp1 = df['fp_sim']
#print(fp1)
def calc(fp):
#print(fp)
#to_delete.append(rdkit.DataStructs.FingerprintSimilarity(fp,fp_2))
if fp_type == 'mhfp':
similarity = fp_2.apply(mhfp_encoder.Distance, args=(fp,))
elif (fp_type == 'tt') or (fp_type == 'avalon'):
similarity = fp_2.apply(DataStructs.TanimotoSimilarity, args=(fp,))
else:
similarity = fp_2.apply(rdkit.DataStructs.FingerprintSimilarity, args=(fp,))
#fp_2.drop(0,inplace=True)
#fp_2.reset_index(inplace = True,drop= True)
return similarity
matrix = fp1.apply(calc)
df.rename(columns={'Title':'Inactives'}, inplace=True)
df2.rename(columns={'Title':'Actives'}, inplace=True)
matrix.index= df['Inactives']
matrix.columns= df2['Actives']
similarity= matrix.max(axis=1)
similarity.reset_index(inplace=True,drop=True)
most_similar= matrix.idxmax(axis=1)
most_similar.reset_index(inplace=True,drop=True)
df['similarity']=similarity
df['most similar compound']=most_similar
if del_ones==True:
df=df[df['similarity']!=1]
df.reset_index(inplace = True)
df.drop(['similarity','most similar compound','index'], axis = 1, inplace=True)
df.rename(columns={'Inactives':'Title'}, inplace=True)
return df
############################################
######## PROPERTIES FILTER ###################
def prop_filter(df_1):
df=df_1.copy()
smiles = df['Smiles']
def calc(smile):
m = Chem.MolFromSmiles(smile)
molwt = int(Descriptors.MolWt(m)) in range(molwt_min, molwt_max +1)
logp = int(Descriptors.MolLogP(m)) in range(logp_min, logp_max +1)
hdonors = Descriptors.NumHDonors(m) in range(hdonors_min,hdonors_max + 1)
haccept = Descriptors.NumHAcceptors(m) in range(haccept_min,haccept_max +1)
heavat = Descriptors.HeavyAtomCount(m) in range(heavat_min,heavat_max+1)
rotabonds = Descriptors.NumRotatableBonds(m) in range(rotabonds_min,rotabonds_max+1)
if molwt and logp and hdonors and haccept and haccept and heavat and rotabonds == True:
return 0
else:
return 1
df['to_filter'] = smiles.apply(calc)
df=df[df['to_filter'] == 0]
df.reset_index(inplace=True,drop=True)
df.drop(['to_filter'], axis = 1, inplace=True)
return df
######## PAINS FILTER ###################
def pains_filter(df_1):
from rdkit.Chem import FilterCatalog
params = FilterCatalog.FilterCatalogParams()
params.AddCatalog(FilterCatalog.FilterCatalogParams.FilterCatalogs.PAINS_A)
params.AddCatalog(FilterCatalog.FilterCatalogParams.FilterCatalogs.PAINS_B)
params.AddCatalog(FilterCatalog.FilterCatalogParams.FilterCatalogs.PAINS_C)
catalog = FilterCatalog.FilterCatalog(params)
df=df_1.copy()
smiles = df['Smiles']
def calc(smile):
m = Chem.MolFromSmiles(smile)
is_a_pain = (catalog.HasMatch(m))
if is_a_pain:
return 'Yes'
else:
return 'No'
df['potential_pain'] = smiles.apply(calc)
#df=df[df['potential_pain'] == 0]
#df.reset_index(inplace=True,drop=True)
#df.drop(['potential_pain'], axis = 1, inplace=True)
return df
# In[8]:
#This function allows to load a CHEMBL csv, clean it and split it in active set (class 0), inactive set (class 1), and discarded compounds (class 2) for that we have either no data or an activity that is in the so-called grey area
def load_chembl_dataset(file_name, comment=False, gray= False):
comment_uncertain_keywords = ['not determined','no data','nd(insoluble)','not evaluated','dose-dependent effect','uncertain','tde','inconclusive','active-partial']
comment_inactive_keywords = ['not active','inactive']
df=file_reader(file_name)
print(f'''\nTraining: Compounds will be considered active if they are reported to have a value of
IC50, EC50, Ki, Kd, or potency, inferior to {activity_threshold} nM.
They will be classified as inactive if their IC50, EC50, Ki, Kd, or potency will be greater
than {inactivity_threshold} nM, or if their inhibition rate is lower than {inhibition_threshold}%.
For duplicate entries, only the most active one will be considered.\n''')
inactive_types = ['inhibition']
active_types = ['ec50','ic50','ki','kd','potency', 'kd apparent']
class_list = []
df = df.dropna(subset = ['Smiles','Standard Type'])
df['Standard Value'] = pd.to_numeric(df['Standard Value'],errors = 'coerce')
df['Standard Value'].fillna('NA', inplace = True)
df.reset_index(inplace = True)
df = df.drop('index', axis = 1)
assays_list =[]
if comment:
comment_list=[]
for i in range(len(df['Standard Type'])):
c = df.loc[i, 'Comment']
if type(c) == int:
c = 'number'
elif type(c) == str:
#detect if a number is present in the string
if not re.search('\d+', c):
c = df.loc[i, 'Comment'].lower()
else:
#numbers present
#c = df.loc[i, 'Comment'].lower().split()
c = 'number'
else :
c = 'number'
if comment:
if c not in comment_list:
comment_list.append(c)
t = df.loc[i,'Standard Type'].lower()
try:
v = float(df.loc[i,'Standard Value'])
except:
v = (df.loc[i,'Standard Value'])
u = df.loc[i,'Standard Units']
r = df.loc[i,'Standard Relation']
if t not in assays_list:
assays_list.append(t)
if c in comment_uncertain_keywords:
class_list.append(2)
#UNCOMMENT TO CONSIDER INACTIVE KEYWORDS
#elif c in comment_inactive_keywords:
# class_list.append(1)
elif v == 'NA':
class_list.append(2)
elif (t in active_types) and (u == 'nM') and (v < activity_threshold) and (r != '\'>\'') :
class_list.append(0)
# CONSIDERS ALL THE "Inhibition" type with a "<" automatically inactive
#elif (t in inactive_types) and (((v<inhibition_threshold) and (u == '%' )) or (r == '\'<\'' )):
# class_list.append(1)
# DOES NOT CONSIDER ALL THE "Inhibition" type with a "<" automatically inactive
elif (t in inactive_types) and ((v<inhibition_threshold) and (u == '%' )):
class_list.append(1)
elif (t in active_types) and (v > inactivity_threshold ):
class_list.append(1)
####### UNCOMMENT TO CONSIDER ALL the ">" automatically inactive
#elif (t in active_types) and (r == '\'>\'' ):
#class_list.append(1)
elif (t in active_types) and (v < inactivity_threshold ):
class_list.append(2)
else:
class_list.append(2)
df['class'] = class_list
to_keep = ['Title','Smiles','Standard Value','Standard Type','Standard Relation', 'Standard Units','class','Comment']
for i in dict(df).keys():
if i not in to_keep:
df = df.drop(i,axis=1)
df = df.sort_values(by=['Title','class', 'Standard Value'])
df = df.drop_duplicates(subset = 'Title', keep = 'first')
df = df.dropna(subset = ['Smiles'])
df.reset_index(inplace = True)
df = df.drop('index', axis = 1)
df=get_fingerprints_ecfp(df,fp_sim=True)
if gray:
df_gray = df[df['class'] == 2]
df_gray.reset_index(inplace = True,drop = True)
df = df[df['class'] != 2]
df.reset_index(inplace = True)
df = df.drop('index', axis = 1)
#df = df.sort_values(by=['class'])
#df = df.drop_duplicates(subset = 'fp_string', keep = 'first')
#df.reset_index(inplace = True)
#df = df.drop(['index','fp_string'], axis = 1)
print('Database preparation: Removing duplicate entries...')
if comment:
return df, assays_list, comment_list
elif gray:
return df, df_gray
else:
return df
# # Algorithm Functions
# In[9]:
def scaler_light(X_train,y_train):
training_a = X_train[y_train==0]
training_i = X_train[y_train==1]
scaler_a = StandardScaler().fit(training_a)
scaler_i = StandardScaler().fit(training_i)