forked from VirtualFlow/VFU
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpose_prediction.py
2111 lines (1664 loc) · 92.2 KB
/
pose_prediction.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 python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 25 20:01:20 2022
@author: akshat
"""
import os
import time
import subprocess
import multiprocessing
from lig_process import process_ligand
def run_plants_docking(receptor, smi, center_x, center_y, center_z, size_x, size_y, size_z):
'''
Input Parameters:
receptor: The path to the receptor file. This file should be in mol2 format.
smi: The path to the SMILES file.
center_x, center_y, center_z: The x, y, z coordinates for the center of the binding site.
size_x, size_y, size_z: The dimensions of the binding site.
Output:
A dictionary of results for each ligand with its score and the path to the result file.
Function Description:
The function run_plants_docking runs PLANTS docking software to dock ligands to the given receptor. It prepares a config file and then runs PLANTS with the input ligands.
PLANTS software creates a result directory for each ligand and saves docking results inside that directory. The function copies the directory in the outputs directory and then removes
it from the present working directory. It then returns a dictionary containing the score and path to the result file for each ligand. It raises an exception if the receptor is not in mol2 format.
Note: The default values for cluster_structures and cluster_rmsd are 10 and 2.0 respectively.
'''
results = {}
print('Note: I am defaulting to setting cluster_structures to 10; please change me in function run_plants_docking, line 40')
print('Note: I am defaulting to setting cluster_rmsd to 2; please change me in function run_plants_docking, line 41')
# receptor needs to be in mol2 format:
receptor_format = receptor.split('.')[-1]
if receptor_format != 'mol2':
raise Exception('Receptor needs to be in mol2 format. Please try again, after incorporating this correction.')
# prepare the ligands:
process_ligand(smi, 'mol2') # mol2 ligand format is supported in plants
lig_locations = os.listdir('./ligands/')
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
# Prepare the config file:
with open('./config.txt', 'w') as f:
f.writelines('protein_file {}\n'.format(receptor))
f.writelines('ligand_file {}\n'.format(lig_path))
f.writelines('output_dir ./result_{}\n'.format(lig_.split('.')[0]))
f.writelines('write_multi_mol2 0\n')
f.writelines('bindingsite_center {} {} {}\n'.format(center_x, center_y, center_z))
f.writelines('bindingsite_radius {}\n'.format( max([size_x, size_y, size_z]) ))
f.writelines('cluster_structures {}\n'.format( 10 ) )
f.writelines('cluster_rmsd {}\n'.format( 2.0 ) )
# Run the command:
plants_cmd = ['./executables/PLANTS', '--mode', 'screen', 'config.txt']
plants_cmd = subprocess.run(plants_cmd, capture_output=True)
plants_cmd = plants_cmd.stdout.decode("utf-8").split('\n')[-6]
score_ = float(plants_cmd.split(' ')[-1])
# Copy the direcory in the right place:
os.system('cp -a {} ./outputs/'.format('./result_{}'.format(lig_.split('.')[0]) ))
os.system('rm -rf result_{}'.format(lig_.split('.')[0]))
os.system('rm config.txt')
results[lig_] = [score_, './results/result_{}'.format(lig_.split('.')[0])]
return results
def run_autodock_gpu_docking(receptor, smi, program_choice):
'''
Function: run_autodock_gpu_docking(receptor, smi, program_choice)
Description:
This function performs molecular docking on a given receptor using AutoDock-GPU or AutoDock-CPU program.
It prepares the ligands in pdbqt format and executes docking to calculate docking scores for each ligand. The function returns a dictionary containing the results for each ligand.
Parameters:
receptor (str): file path for the receptor (in .maps.fld format)
smi (str): SMILES string for the ligand(s)
program_choice (str): program of choice for docking, either 'autodock_cpu' or 'autodock_gpu'
Returns:
results (dict): a dictionary containing the docking score and .dlg file path for each ligand.
Note: The receptor file needs to be in .maps.fld format for AutoDock-GPU. The ligands will be converted to pdbqt format using the 'process_ligand' function from the 'lig_process' module.
'''
print('Note: For use of vina gpu, the receptor needs to be prepared in a specific way. Have a look at the examples provided in https://github.com/ccsb-scripps/AutoDock-GPU & the example dir we provided within executables/vf_gpu_example.zip')
command = []
# receptor needs to be in mol2 format:
receptor_format = receptor.split('.')
if receptor_format[-1] != 'fld' and receptor_format[-2] != 'maps':
raise Exception('Receptor needs to be of file type .maps.fld (example: 1stp_protein.maps.fld). Please try again, after incorporating this correction.')
# check for the existence of the executable:
try:
if 'gpu' in program_choice:
executable = [x for x in os.listdir('./executables') if 'autodock_gpu' in x][0]
elif 'cpu' in program_choice:
executable = [x for x in os.listdir('./executables') if 'autodock_cpu' in x][0]
else:
raise Exception('Executable must be of format autodock_cpu/gpu')
except:
raise Exception('Executable file autodock_cpu/gpu not found in executables directory')
# Assign the right program for docking:
command.append('./executables/{}'.format(executable))
# Prepare the ligands:
process_ligand(smi, 'pdbqt')
lig_locations = os.listdir('./ligands/')
# Get ready for running the files:
dlg_file = [x for x in os.listdir('./') if '.dlg' in x][0]
results = {}
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
vina_gpu_cmd = command + ['--ffile', '{}'.format(receptor)]
vina_gpu_cmd = vina_gpu_cmd + ['--lfile', '{}'.format(lig_path)]
vina_gpu_cmd = subprocess.run(vina_gpu_cmd, capture_output=True)
vina_gpu_cmd = vina_gpu_cmd.stdout.decode("utf-8").split('\n')[-6]
if vina_gpu_cmd[-1] != 'All jobs ran without errors.\n':
print('An error was encountered when executing docking for: ', lig_path)
results[lig_] = ['FAIL', vina_gpu_cmd]
else:
lines = [x.strip() for x in vina_gpu_cmd if 'best energy' in x][0]
docking_score = float(lines.split(',')[1].split(' ')[-2])
results[lig_] = [docking_score, dlg_file]
return results
def run_EquiBind(receptor, smi):
'''
Runs the EquiBind program for protein-ligand binding prediction.
Args:
- receptor (str): the file path of the receptor protein in PDB format.
- smi (str): the SMILES string of the ligand molecule.
Returns:
- results (dict): a dictionary of the form {ligand file path: results file path},
containing the file paths of the output results for each ligand.
Raises:
- Exception: if the EquiBind files are not found in the current directory.
- Exception: if the receptor file is not in PDB format.
'''
files_ls = os.listdir('./')
if not('data' in files_ls and 'inference.py' in files_ls):
raise Exception('Please make sure process EquiBind based on the instructions provided in the readme. I could not find the key EquiBind files.')
if receptor.split('.')[2] != 'pdb':
raise Exception('For EquiBind, protein file needs to be in pdb file type. Please incorporate this correction')
# Process the ligands
process_ligand(smi, 'sdf')
# Make a direcotry containing all the tasks to be performed:
os.sytem('mkdir ./data/to_predict')
results = {}
lig_locations = os.listdir('./ligands/')
for i,lig_ in enumerate(lig_locations):
lig_path = 'ligands/{}'.format(lig_)
os.system('./data/to_predict/test{}'.format(i))
os.system('cp {} {}'.format(receptor, './data/to_predict/test{}/rec.pdb'.format(i))) # Copy the protein file:
os.system('cp {} {}'.format(lig_path, './data/to_predict/test{}/ligand.sdf'.format(i))) # Copy the ligand file:
results[lig_path] = './data/results/output/test{}'.format(i)
os.system('python inference.py --config=configs_clean/inference.yml')
print('Results are saved in: ./data/results/output')
return results
def run_rDock(receptor, smi, ref_lig):
"""
Runs rDock for docking the given ligand SMILES strings with the receptor molecule.
Args:
- receptor (str): The path of the receptor file in '.mol2' format.
- smi (str): The SMILES string of the ligand molecule.
- ref_lig (str): Reference ligand that needs to be specified for rDock
Returns:
- results (dict): A dictionary with ligand file names as keys and their corresponding docking scores as values.
Raises:
- Exception: If the receptor is not in '.mol2' format.
- Exception: If the prm file parameters need modification.
"""
if os.path.exists(ref_lig) == False:
raise Exception('Required reference ligand not found')
# receptor needs to be in mol2 format:
receptor_format = receptor.split('.')[-1]
if receptor_format != 'mol2':
raise Exception('Receptor needs to be in mol2 format. Please try again, after incorporating this correction.')
# Create ligands as '.sd' file type:
process_ligand(smi, 'sd')
lig_locations = os.listdir('./ligands/')
# Creation of the prm file:
print('Please have a look at the prm parameters. Inside [TODO]; we have assigned some default values.')
with open('config.prm', 'w') as f:
f.writelines('RBT_PARAMETER_FILE_V1.00\n')
f.writelines('TITLE gart_DUD\n')
f.writelines('RECEPTOR_FILE {}\n'.format(receptor))
f.writelines('SECTION MAPPER\n')
f.writelines(' SITE_MAPPER RbtLigandSiteMapper\n')
f.writelines(' REF_MOL {}\n'.format(ref_lig))
f.writelines(' RADIUS 6.0\n')
f.writelines(' SMALL_SPHERE 1.0\n')
f.writelines(' MIN_VOLUME 100\n')
f.writelines(' MAX_CAVITIES 1\n')
f.writelines(' VOL_INCR 0.0\n')
f.writelines(' GRIDSTEP 0.5\n')
f.writelines('END_SECTION\n')
f.writelines('SECTION CAVITY\n')
f.writelines(' SCORING_FUNCTION RbtCavityGridSF\n')
f.writelines(' WEIGHT 1.0\n')
f.writelines('END_SECTION\n')
# Cavity generation:
os.system('rbcavity -was -d -r config.prm')
results = {}
# Perform docking:
os.system('mkdir rDock_outputs')
for i,lig_ in enumerate(lig_locations):
os.system('mkdir rDock_outputs/{}'.format(i))
lig_path = 'ligands/{}'.format(lig_)
os.system('rbdock -i {} -o {} -r config.prm -p dock.prm -n 50'.format(lig_path, 'rDock_outputs/{}.sd'.format(i)))
# Read the docking scores:
with open('rDock_outputs/{}.sd'.format(i), 'r') as f:
lines = f.readlines()
score = []
for i,item in enumerate(lines):
if item.strip() == '> <SCORE>':
score.append(float(lines[i+1]))
docking_score = min(score)
results[lig_] = docking_score
return results
def generate_ledock_file(receptor='pro.pdb',rmsd=1.0,x=[0,0],y=[0,0],z=[0,0], n_poses=10, l_list=[],l_list_outfile='',out='dock.in'):
"""
Generate a LeDock input file with the given receptor and ligand information.
Args:
- receptor (str): the name of the receptor PDB file.
- rmsd (float): the RMSD tolerance for docking.
- x (list of two floats): the X-coordinates of the binding pocket, in the format [x_min, x_max].
- y (list of two floats): the Y-coordinates of the binding pocket, in the format [y_min, y_max].
- z (list of two floats): the Z-coordinates of the binding pocket, in the format [z_min, z_max].
- n_poses (int): the number of binding poses to generate.
- l_list (list of str): a list of ligand files to dock.
- l_list_outfile (str): the name of the output file to write the ligand list to.
- out (str): the name of the output docking file to generate.
Returns:
None.
"""
rmsd=str(rmsd)
x=[str(x) for x in x]
y=[str(y) for y in y]
z=[str(z) for z in z]
n_poses=str(n_poses)
with open(l_list_outfile,'w') as l_out:
for element in l_list:
l_out.write(element)
l_out.close()
file=[
'Receptor\n',
receptor + '\n\n',
'RMSD\n',
rmsd +'\n\n',
'Binding pocket\n',
x[0],' ',x[1],'\n',
y[0],' ',y[1],'\n',
z[0],' ',z[1],'\n\n',
'Number of binding poses\n',
n_poses + '\n\n',
'Ligands list\n',
l_list_outfile + '\n\n',
'END']
with open(out,'w') as output:
for line in file:
output.write(line)
output.close()
def run_leDock(receptor, smi, center_x, center_y, center_z, size_x, size_y, size_z):
"""
Dock the ligand molecules to the given protein using the Ledock docking software. The docking box is centered at the given
coordinates with given dimensions.
Args:
- receptor (str): the pdb file name of the protein receptor.
- smi (str): the SMILES string of the ligand to dock.
- center_x (float): the x coordinate of the center of the docking box.
- center_y (float): the y coordinate of the center of the docking box.
- center_z (float): the z coordinate of the center of the docking box.
- size_x (float): the dimension of the docking box in the x direction.
- size_y (float): the dimension of the docking box in the y direction.
- size_z (float): the dimension of the docking box in the z direction.
Returns:
- results (dict): a dictionary with the ligand file path as key and a list of the path of the output file and the
predicted binding score as value. If the docking process fails for a ligand, the value for the
ligand key is 'FAIL'.
"""
# Ensure receptor is in the right format
receptor_format = receptor.split('.')[-1]
if receptor_format != 'pdb':
raise Exception('Receptor needs to be in pdb format. Please try again, after incorporating this correction.')
# prepare the ligands:
process_ligand(smi, 'mol2') # mol2 ligand format is supported in ledock
lig_locations = os.listdir('./ligands/')
results = {}
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
generate_ledock_file(receptor=receptor,
x=[center_x-size_x, center_x+size_x],
y=[center_y-size_y, center_y+size_y],
z=[center_z-size_z, center_z+size_z],
n_poses=10,
rmsd=1.0,
l_list= lig_path,
l_list_outfile='ledock_ligand.list',
out='dock.in')
ledock_cmd = ['./executables/ledock', 'dock.in']
ledock_cmd = subprocess.run(ledock_cmd, capture_output=True)
if ledock_cmd.returncode == 0:
os.system('cp ./ligands/{}.dok ./outputs/'.format(lig_.split('.')[0]))
with open('./outputs/{}.dok'.format(lig_.split('.')[0]), 'r') as f:
lines = f.readlines()
lines = [x for x in lines if 'Score' in x]
scores = []
for item in lines:
A = item.split('Score')[-1].strip().split(': ')[1].split(' ')[0]
scores.append(float(A))
results[lig_path] = ['./outputs/{}.dok'.format(lig_.split('.')[0]), min(scores)]
else:
results[lig_path] = 'FAIL'
os.system('rm dock.in ledock_ligand.list')
def process_idock_output(results):
'''
This function processes the output of iDock docking simulation.
The output pdbqt files are read and the corresponding log.csv file is analyzed for the docking score.
The scores are then saved in the 'results' dictionary in the format - {ligand_path: docking_score}
The pdbqt files are saved in the outputs directory.
Parameters:
results (dict): The dictionary to store the results.
Returns:
None
'''
poses_ = os.listdir('./')
poses_ = [x for x in poses_ if 'pdbqt' in x]
for item in poses_:
try:
ob_cmd = ['obenergy', './{}'.format(item)]
command_obabel_check = subprocess.run(ob_cmd, capture_output=True)
command_obabel_check = command_obabel_check.stdout.decode("utf-8").split('\n')[-2]
total_energy = float(command_obabel_check.split(' ')[-2])
except:
total_energy = 10000 # Calculation has failed.
if total_energy < 10000:
# Read the output file:
with open('./log.csv', 'r') as f:
lines = f.readlines()
lines = lines[1: ]
map_ = {}
for item in lines:
A =item.split(',')
map_[A[0]] = float(A[2])
# Save the result:
results[item] = map_[item.split('.')[0]]
# Copy the file:
os.system('cp {} ./outputs/{}'.format(item, item))
else:
os.system('rm {}'.format(item))
os.system('rm log.csv')
return
def run_adfr_docking(receptor, smi):
'''
This function runs docking simulation using ADFR (AutoDock FR) program. The program requires the receptor to be in pdbqt format.
The program also requires a target file in trg format. The target file contains information on docking parameters.
The ligand is processed to be in pdbqt format.
The ligand files are docked to the receptor and the docking scores are returned in a dictionary.
Parameters:
receptor (str): The file path of the receptor in pdbqt format.
smi (str): The SMILES string of the ligand.
Returns:
results (dict): A dictionary containing the ligand file path as keys and the docking score as values.
'''
# receptor needs to be in mol2 format:
receptor_format = receptor.split('.')[-1]
if receptor_format != 'pdbqt':
raise Exception('Receptor needs to be in pdbqt format. Please try again, after incorporating this correction.')
files_ls = os.listdir('./')
target_file = [x for x in files_ls if '.trg' in x]
if len(target_file) == 0:
raise Exception('A trg file containing all the parameters is required for running adfr. Please have a look at the tutorial in: https://ccsb.scripps.edu/adfr/documentation/')
# prepare the ligands:
process_ligand(smi, 'pdbqt')
lig_locations = os.listdir('./ligands/')
print('Using target file: ', target_file[0])
results = {}
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
cmd = ['./executables/adfr', '-t', '{}'.format(target_file[0]), '-l', '{}'.format(lig_path), '--jobName', 'rigid']
# Perform the docking:
command_run = subprocess.run(cmd, capture_output=True)
if command_run.returncode != 0:
results[lig_path] = 'FAIL'
docking_out = command_run.stdout.decode("utf-8")
docking_scores = []
for item in docking_out:
A = item.split(' ')
A = [x for x in A if x != '']
try:
a_1, a_2, a_3 = float(A[0]), float(A[1]), float(A[2])
except:
continue
docking_scores.append(float(a_2))
results[lig_] = docking_scores
return results
def run_flexx_docking(receptor, smi, ref_lig):
"""
Runs the flexx docking program on the given receptor and ligands.
Args:
receptor (str): The path to the receptor file in pdb format.
smi (str): The SMILES string of the ligand to dock.
ref_lig (str): Reference ligand that needs to be specified for flexx
Returns:
dict: A dictionary with the results of the docking. The dictionary contains the ligand file name as
the key and the docking scores and the output file path as the value. If the execution is unsuccessful
or if extremely high pose energy is encountered, the value for the corresponding ligand is a string with a message.
"""
import multiprocessing
results = {}
if os.path.exists(ref_lig) == False:
raise Exception('Required reference ligand not found')
executable_files = os.listdir('./executables')
if 'flexx' not in executable_files:
raise Exception('The flexx executable was not foung. Please note: the execuatable file (named flexx) needs to be placed inside the directory executables')
if receptor.split('.')[-1] != 'pdb':
raise Exception('Receptor needs to be in pdb format')
# prepare the ligands:
process_ligand(smi, 'mol2')
lig_locations = os.listdir('./ligands/')
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
out_path = './outputs/pose_{}.sdf'.format(lig_.split('.')[0])
os.system('./flexx -i {} -o {} -p {} -r {} --thread-count {}'.format(lig_path, out_path, receptor, ref_lig, multiprocessing.cpu_count()))
# Check energy of docked pose:
total_energy = check_energy(lig_)
if total_energy < 10000:
# Read in the docking scores:
with open(out_path, 'r') as f:
lines = f.readlines()
for i,item in enumerate(lines):
docking_scores = []
if '> <docking-score>' in item :
docking_score = float(lines[i+1])
docking_scores.append(docking_score)
results[lig_] = [docking_scores, out_path]
else:
results[lig_] = 'Extremely high pose energy encountered/Unsuccessfull execution.'
return results
def run_AutodockZN(receptor, smi, center_x, center_y, center_z, size_x, size_y, size_z, exhaustiveness):
"""
Runs AutoDockZn for a given receptor and ligand.
Parameters:
- receptor (str): path of receptor file in pdbqt format.
- smi (str): SMILES string of the ligand.
- center_x (float): x-coordinate of the center of binding box.
- center_y (float): y-coordinate of the center of binding box.
- center_z (float): z-coordinate of the center of binding box.
- size_x (float): size of the binding box along x-axis.
- size_y (float): size of the binding box along y-axis.
- size_z (float): size of the binding box along z-axis.
- exhaustiveness (int): exhaustiveness of the search algorithm.
Returns:
- results (dict): a dictionary of the form ligand_path:[docking_output_path, out_path] containing the paths of docked poses and the output files of the AutoDockVina runs for each ligand.
Raises:
- Exception: if receptor file is not in pdbqt format.
- Exception: if required files of ADFRsuite cannot be located.
"""
receptor_format = receptor.split('.')[-1]
if receptor_format != 'pdbqt':
raise Exception('Receptor needs to be in pdbqt format. Please try again, after incorporating this correction.')
if os.path.exists('~/ADFRsuite-1.0/bin/pythonsh') == False:
raise Exception('Could not locate ADFRsuite file (ADFRsuite-1.0/bin/pythonsh) in the home directory.')
if os.path.exists('~/ADFRsuite-1.0/bin/autogrid4') == False:
raise Exception('Could not locate ADFRsuite file (ADFRsuite-1.0/bin/autogrid4) in the home directory.')
# prepare the ligands:
process_ligand(smi, 'pdbqt')
lig_locations = os.listdir('./ligands/')
results = {}
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
out_path = './outputs/pose_{}.pdbqt'.format(lig_.split('.')[0])
# Generate affinity maps:
os.system('~/ADFRsuite-1.0/bin/pythonsh ./config/prepare_gpf4zn.py -l {} -r {} -o receptor_tz.gpf -p npts={},{},{} -p gridcenter={},{},{} –p parameter_file=./config/AD4Zn.dat'.format(lig_path, receptor, size_x, size_y, size_z, center_x, center_y, center_z))
os.system('~/ADFRsuite-1.0/bin/autogrid4 -p receptor_tz.gpf -l receptor_tz.glg')
# Run AutoDockVina:
cmd = ['./config/AutodockVina_1.2', '--ligand', '{}'.format(lig_path), '--maps', 'receptor_tz', '--scoring', 'ad4', '--exhaustiveness', '{}'.format(exhaustiveness), '--out', '{}'.format(out_path)]
command_run = subprocess.run(cmd, capture_output=True)
# Check the quality of generated structure (some post-processing quality control):
total_energy = check_energy(lig_)
if total_energy < 10000:
# Collect the docking output:
docking_out = command_run.stdout.decode("utf-8")
A = docking_out.split('\n')
docking_score = []
for item in A:
line_split = item.split(' ')
line_split = [x for x in line_split if x != '']
if len(line_split) == 4:
try:
vr_1 = float(line_split[0])
vr_2 = float(line_split[1])
vr_3 = float(line_split[2])
vr_4 = float(line_split[3])
docking_score.append(vr_2)
except:
continue
results[lig_path] = [docking_out, out_path]
# Delete auxilarry files:
os.system('rm receptor_tz.gpf receptor_tz.glg')
return results
def run_mcdock(receptor, smi):
"""
Runs the MCDock molecular docking software on a given receptor and SMILES string.
Args:
- receptor: a string containing the filename of the receptor in XYZ format.
- smi: a string containing the SMILES representation of the ligand to be docked.
Returns:
- A dictionary containing the binding energies of each ligand docked. The keys are the file paths of the ligands docked, and the values are lists of the binding energies for each conformation generated by MCDock.
"""
# Check to ensure receptor is in the right format:
if receptor.split('.')[-1] != 'xyz':
raise Exception('Please provide the receptor in xyz format for MCDock')
# Check to ensure MCDock executable exists:
if os.path.exists('./executables/mcdock'):
raise Exception('Executable named mcdock not found in the executables directory')
# Process all ligands:
process_ligand(smi, 'xyz')
lig_locations = os.listdir('./ligands/')
results = {}
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
out_path = './outputs/pose_{}.xyz'.format(lig_.split('.')[0])
# Run docking
os.system('./executables/mcdock --target {} --ligand {}'.format(receptor, lig_path))
# Read in the results:
with open('./out.xyz', 'r') as f:
lines = f.readlines()
lines = [x for x in lines if 'Binding Energy' in x]
binding_energies = []
for item in lines:
binding_energies.append(float(item.split(' ')[2].split('\t')[0]))
# Delete/move auxillary files:
os.system('rm min.xyz')
os.system('cp out.xyz {}'.format(out_path))
os.system('rm out.xyz conformers.xyz')
results[lig_path] = binding_energies
return results
def run_ligand_fit(receptor, smi, center_x, center_y, center_z):
"""
Runs the LigandFit docking program to dock ligands to a protein receptor.
Args:
- receptor (str): The path to the protein receptor file in PDB format.
- smi (str): The SMILES string of the ligand to be docked.
- center_x (float): The x-coordinate of the center of the search box.
- center_y (float): The y-coordinate of the center of the search box.
- center_z (float): The z-coordinate of the center of the search box.
Returns:
- results (dict): A dictionary containing the docked poses of the ligands and their corresponding scores.
Each key is the filename of a docked ligand pose in PDB format, and each value is a list
containing the score of the docked pose and the path to the output file.
"""
if receptor.split('.')[-1] != 'pdb':
raise Exception('Please provide the receptor in pdb format for LigandFit')
if os.path.exists('./executables/ligandfit') == False:
raise Exception('Executable named ligandfit not found in the executables directory')
if os.path.exists('./config/receptor.mtz') == False:
raise Exception('Receptor mtz file (titled receptor.mtz) not found in config directory. File is required for running LigandFit')
# Process all ligands:
process_ligand(smi, 'pdb')
lig_locations = os.listdir('./ligands/')
results = {}
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
out_path = './outputs/pose_{}.xyz'.format(lig_.split('.')[0])
os.system('./executables/ligandfit data=./config/receptor.mtz model={} ligand={} search_center={},{},{}'.format(receptor, lig_path, center_x, center_y, center_z))
# Read in results:
with open('./LigandFit_run_1_/ligand_1_1.log', 'r') as f:
lines = f.readlines()
lines = [x for x in lines if 'Best score' in x]
scores = []
for item in lines:
scores.append( float([x for x in item.split(' ') if x != ''][-2]) )
# Remove auxillary file:
os.system('rm -rf PDS')
os.system('cp ./LigandFit_run_1_/ligand_fit_1.pdb {}'.format(out_path))
os.system('rm -rf LigandFit_run_1_')
results[lig_] = [scores, out_path]
return results
def run_GalaxyDock3(receptor, smi, center_x, center_y, center_z, exhaustiveness):
"""
Dock ligands to a protein receptor using GalaxyDock3 software.
Args:
- receptor (str): the path to the receptor PDB file. It should end with '.pdb'.
- smi (str): a SMILES string containing the ligands to be docked.
- center_x (float): the x-coordinate of the center of the docking box in Angstroms.
- center_y (float): the y-coordinate of the center of the docking box in Angstroms.
- center_z (float): the z-coordinate of the center of the docking box in Angstroms.
- exhaustiveness (int): the number of ligand poses to generate in the docking search.
Returns:
- results (dict): a dictionary containing the output files and docking scores for each ligand. The dictionary has the format:
Raises:
- Exception: If the receptor file format is not '.pdb'.
- Exception: If the GalaxyDock3 executable is not found in the 'executables' directory.
- Exception: If the 'data' directory is not found.
"""
results = {}
# Check to ensure receptor is in the right format:
if receptor.split('.')[-1] != 'pdb':
raise Exception('Please provide the receptor in pdb format for MCDock')
# Check to ensure MCDock executable exists:
if os.path.exists('./executables/GalaxyDock3'):
raise Exception('Executable named GalaxyDock3 not found in the executables directory')
if os.path.exists('./data'):
raise Exception('Data directory (./data) not found. Please have a look at the data directory in https://galaxy.seoklab.org/files/by2hsnvxjf/softwares/galaxydock.html (click the link galaxydock3)')
# Process all ligands:
process_ligand(smi, 'mol2')
lig_locations = os.listdir('./ligands/')
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
out_path = './outputs/pose_{}.mol2'.format(lig_.split('.')[0])
# grid_n_elem : Number of grid points for each directioni. This is should be
# given in odd number. [61 61 61]
grid_n_elem = [61, 61, 61]
print('Note: i am setting grid_n_elem to [61, 61, 61]. Please change this default behaviour if need be. ')
# grid_width : Grid space between points in angstrom. [0.375]
grid_width = 0.375
print('Note: i am setting grid_width to 0.375. Please change this default behaviour if need be. ')
# Generate the input file:
with open('./galaxydock.in', 'w') as f:
f.writelines(['!==============================================\n'])
f.writelines(['! I/O Parameters\n'])
f.writelines(['!==============================================\n'])
f.writelines(['data_directory ./data\n'])
f.writelines(['infile_pdb {}\n'.format(receptor)])
f.writelines(['infile_ligand {}\n'.format(lig_path)])
f.writelines(['top_type polarh\n'])
f.writelines(['fix_type all\n'])
f.writelines(['ligdock_prefix out\n'])
f.writelines(['!==============================================\n'])
f.writelines(['! Grid Options\n'])
f.writelines(['!==============================================\n'])
f.writelines(['grid_box_cntr {} {} {}\n'.format(center_x, center_y, center_z)])
f.writelines(['grid_n_elem {} {} {}\n'.format(grid_n_elem[0], grid_n_elem[1], grid_n_elem[2])])
f.writelines(['grid_width {}\n'.format(grid_width)])
f.writelines(['!==============================================\n'])
f.writelines(['! Energy Parameters\n'])
f.writelines(['!==============================================\n'])
f.writelines(['weight_type GalaxyDock3\n'])
f.writelines(['!==============================================\n'])
f.writelines(['! Initial Bank Parameters\n'])
f.writelines(['!==============================================\n'])
f.writelines(['first_bank rand\n'])
f.writelines(['max_trial {}\n'.format(exhaustiveness)])
f.writelines(['e0max 1000.0\n'])
f.writelines(['e1max 1000000.0\n'])
f.writelines(['n_proc 1'])
# Run the script:
os.system('./executables/GalaxyDock3 galaxydock.in > log')
# Read in results:
with open('./out_fb.E.info', 'r') as f:
lines = f.readlines()
lines = lines[3: ]
docking_scores = []
for item in lines:
try:
A = item.split(' ')
A = [x for x in A if x != '']
docking_scores.append(float(A[5]))
except:
continue
# Remove auxillary files
os.system('rm log out_cl.E.info merged_ligand.mol2 out_cl.size.info out_co.info out_fb.E.info out_cl.mol2 out_ib.E.info out_ib.mol2')
# Transfer out_fb.mol2
os.system('cp {} {}'.format('out_fb.mol2', out_path))
os.system('rm out_fb.mol2')
results[lig_path] = [out_path, docking_scores]
return results
def run_dock6(receptor, smi, chimera_path, dock6_path, ref_lig):
"""
Runs Dock6 molecular docking program to dock a set of ligands to a receptor protein.
Parameters:
receptor (str): Path to the receptor file in pdb format.
smi (str): SMILES string for the ligands to dock.
chimera_path (str): Path in system for Chimera application
dock6_path (str): Path in system for dock6 application
ref_lig (str): Reference ligand that needs to be specified for dock6
Returns:
Dictionary containing the results of Dock6 docking for each ligand. The keys are the file paths of the
ligand files used for docking and the values are lists containing the file path of the output docked
ligand mol2 file and the docking score for the ligand.
Raises:
Exception: If the path to the Chimera software or Dock6 directory is invalid, if the reference ligand file
is not specified, or if the receptor file is not in pdb format.
"""
box_padding = 12.0
results = {}
if os.path.exists(chimera_path) == False:
raise Exception('Location of Chemira not found (used location from variable chimera_path) when trying to initiate dock6 calculation.')
if os.path.exists(dock6_path) == False:
raise Exception('Location of dock6 not found (used location from variable dock6_path) when trying to initiate dock6 calculation.')
if os.path.exists(ref_lig) == False:
raise Exception('Please specify the location of the reference ligand for dock6 to run')
# Check to ensure receptor is in the right format:
if receptor.split('.')[-1] != 'pdb':
raise Exception('Please provide the receptor in pdb format for dock6')
# Prepare the receptor using Chimera:
os.system('{}/bin/chimera --nogui {} ./config/dockprep.py'.format(chimera_path, receptor))
# doc6 pre-processing
os.system('{}/bin/sphgen INSPH'.format(dock6_path))
os.system('{}/bin/sphere_selector rec.sph {} {}'.format(dock6_path, ref_lig, box_padding))
os.system('{}/bin/showbox < box.in'.format(dock6_path))
os.system('{}/bin/grid -i grid.in'.format(dock6_path))
# Process all ligands:
process_ligand(smi, 'mol2')
lig_locations = os.listdir('./ligands/')
for lig_ in lig_locations:
lig_path = 'ligands/{}'.format(lig_)
out_path = './outputs/pose_{}.xyz'.format(lig_.split('.')[0])
# Generate dock6 input file:
with open('./dock.in', 'w') as f:
f.writelines(['conformer_search_type flex\n'])
f.writelines(['user_specified_anchor no\n'])
f.writelines(['limit_max_anchors no\n'])
f.writelines(['min_anchor_size 40\n'])
f.writelines(['pruning_use_clustering yes\n'])
f.writelines(['pruning_max_orients 100\n'])
f.writelines(['pruning_clustering_cutoff 100\n'])
f.writelines(['pruning_conformer_score_cutoff 25.0\n'])
f.writelines(['pruning_conformer_score_scaling_factor 1.0\n'])
f.writelines(['use_clash_overlap no\n'])
f.writelines(['write_growth_tree no\n'])
f.writelines(['use_internal_energy yes\n'])
f.writelines(['internal_energy_cutoff 100.0\n'])
f.writelines(['ligand_atom_file {}\n'.format(lig_path)])
f.writelines(['limit_max_ligands no\n'])
f.writelines(['receptor_site_file selected_spheres.sph\n'])
f.writelines(['max_orientations 500\n'])
f.writelines(['chemical_matching no\n'])
f.writelines(['use_ligand_spheres no\n'])
f.writelines(['bump_filter no\n'])
f.writelines(['score_molecules yes\n'])
f.writelines(['contact_score_primary no\n'])
f.writelines(['contact_score_secondary no\n'])
f.writelines(['grid_score_primary yes\n'])
f.writelines(['grid_score_secondary no\n'])
f.writelines(['grid_score_rep_rad_scale 1\n'])
f.writelines(['grid_score_vdw_scale 1\n'])
f.writelines(['grid_score_grid_prefix grid\n'])
f.writelines(['dock3.5_score_secondary no\n'])
f.writelines(['continuous_score_secondary no\n'])
f.writelines(['footprint_similarity_score_secondary no\n'])
f.writelines(['pharmacophore_score_secondary no\n'])
f.writelines(['descriptor_score_secondary no\n'])
f.writelines(['gbsa_zou_score_secondary no\n'])
f.writelines(['gbsa_hawkins_score_secondary no\n'])
f.writelines(['SASA_score_secondary no\n'])
f.writelines(['amber_score_secondary no\n'])
f.writelines(['minimize_ligand yes\n'])
f.writelines(['minimize_anchor yes\n'])
f.writelines(['minimize_flexible_growth yes\n'])
f.writelines(['use_advanced_simplex_parameters no\n'])
f.writelines(['simplex_max_cycles 1\n'])
f.writelines(['simplex_score_converge 0.1\n'])
f.writelines(['simplex_cycle_converge 1.0\n'])
f.writelines(['simplex_trans_step 1.0\n'])
f.writelines(['simplex_rot_step 0.1\n'])
f.writelines(['simplex_tors_step 10.0\n'])
f.writelines(['simplex_anchor_max_iterations 500\n'])
f.writelines(['simplex_grow_max_iterations 500\n'])
f.writelines(['simplex_grow_tors_premin_iterations 0\n'])
f.writelines(['simplex_random_seed 0\n'])
f.writelines(['simplex_restraint_min no\n'])
f.writelines(['atom_model all\n'])
f.writelines(['vdw_defn_file {}/parameters\n'.format(dock6_path)])
f.writelines(['flex_defn_file {}/parameters/flex.defn\n'.format(dock6_path)])
f.writelines(['flex_drive_file {}/parameters/flex_drive.tbl\n'.format(dock6_path)])
f.writelines(['vdw_defn_file {}/parameters/vdw_AMBER_parm99.defn\n'.format(dock6_path)])
f.writelines(['flex_defn_file {}/parameters/flex.defn\n'.format(dock6_path)])
f.writelines(['ligand_outfile_prefix ligand_out\n'])
f.writelines(['write_orientations no\n'])
f.writelines(['num_scored_conformers 1\n'])
f.writelines(['rank_ligands no\n'])
# Run the docking:
os.system('{}/bin/dock6 -i dock.in'.format(dock6_path))
# Remove aux files:
os.system('rm dock.in')
dock_file = [x for x in os.listdir('./') if 'ligand_out' in x]
dock_file = [x for x in dock_file if 'mol2' in x][0]
os.system('cp {} {}'.format(dock_file, out_path))
os.system('rm dock_file')
# Save the results:
with open('./ligand_out_scored.mol2', 'r') as f:
lines = f.readlines()
docking_score = float(lines[2].split(' ')[-1])
results[lig_path] = [out_path, docking_score]
os.system('rm ligand_out_scored.mol2')
return results
def run_fred_docking(receptor, smi, center_x, center_y, center_z, size_x, size_y, size_z, exhaustiveness):
"""
Runs FRED docking to dock ligands to a receptor.
Args:
- receptor (str): The path to the receptor file in PDB format.
- smi (str): The SMILES string of the ligand(s) to dock.
- center_x (float): The x-coordinate of the center of the docking box.
- center_y (float): The y-coordinate of the center of the docking box.
- center_z (float): The z-coordinate of the center of the docking box.
- size_x (float): The size of the docking box along the x-axis.
- size_y (float): The size of the docking box along the y-axis.
- size_z (float): The size of the docking box along the z-axis.
- exhaustiveness (int): The exhaustiveness of the docking search. Higher values lead to more exhaustive searches.
Returns:
- results (dict): A dictionary where the keys are the paths to the ligand files and the values are the paths to the output poses in Mol2 format.
"""
if receptor.split('.')[-1] != 'pdb':
raise Exception('Please provide the receptor in pdb format for FRED')
if os.path.exists('./oe_license.txt') == False:
raise Exception('OpenEye licence file (oe_license.txt) not found in working directory')
process_ligand(smi, 'mol2')