-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
3778 lines (3201 loc) · 139 KB
/
__init__.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 -*-
###############################################################################
# This is the KVFinder-web service client for PyMOL. It was developed using #
# Qt interface and Python. Changes in this file are not advised, as it #
# controls all interactions with KVFinder-web service. #
# #
# PyMOL KVFinder Web Tools is free software: you can redistribute it and/or #
# modify it under the terms of the GNU General Public License as published #
# by the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# PyMOL KVFinder Web Tools 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 General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License along #
# with PyMOL KVFinder Web Tools. If not, see <http://www.gnu.org/licenses/>. #
# #
###############################################################################
from __future__ import absolute_import, annotations, print_function
import json
import os
from typing import Any, Dict, Optional
import toml
from PyQt6 import QtCore, QtWidgets
__name__ = "PyMOL KVFinder-web Tools"
__version__ = "v1.0.0"
# global reference to avoid garbage collection of our dialog
dialog = None
worker = None
##########################################
# Relevant information #
# Web service (KVFinder-web service) #
# This variable defines the url of the #
# KVFinder-web service. Change this #
# variable to the service you are using #
# Server #
server = "http://kvfinder-web.cnpem.br" #
# Path #
path = "/api" #
# #
# Days until job expire #
days_job_expire = 1 #
# #
# Data limit #
data_limit = "5 Mb" #
# #
# Timers (msec) #
time_restart_job_checks = 5000 #
time_server_down = 60000 #
time_no_jobs = 5000 #
time_between_jobs = 2000 #
time_wait_status = 5000 #
# #
# Times jobs completed with downloaded #
# results are not checked in service #
times_job_completed_no_checked = 500 #
# #
# Verbosity: print extra information #
# 0: No extra information #
# 1: Print GUI information #
# 2: Print Worker information #
# 3: Print all information (Worker/GUI) #
verbosity = 0 #
##########################################
class _Default(object):
"""
Object with default detection parameters of parKVFinder software
Attributes
----------
probe_in: float
Probe In size (A)
probe_out: float
Probe Out size (A)
removal_distance: float
Length to be removed from the cavity-bulk frontier (A)
volume_cutoff: float
Cavities volume filter (A3)
base_name: str
Base name for any outputted file
output_dir_path: str
Path of the output directory
box_adjustment: bool
Whether the box adjustment mode is enabled
x: float
x coordinate of the center of the box
y: float
y coordinate of the center of the box
z: float
z coordinate of the center of the box
min_x: float
Distance of the minimum x coordinate from x coordinate of the center of the box
max_x: float
Distance of the maximum x coordinate from x coordinate of the center of the box
min_y: float
Distance of the minimum y coordinate from y coordinate of the center of the box
max_y: float
Distance of the maximum y coordinate from y coordinate of the center of the box
min_z: float
Distance of the minimum z coordinate from z coordinate of the center of the box
max_z: float
Distance of the maximum z coordinate from z coordinate of the center of the box
angle1: float
Angle 1 of the custom box
angle2: float
Angle 2 of the custom box
padding: float
Padding of the custom box
ligand_adjustment: bool
Whether the ligand adjustment mode is enabled
ligand_cutoff: float
Length to limit a space around a ligand (A)
"""
def __init__(self):
super(_Default, self).__init__()
"""
Initialize class with defult detection parameters in attributes
"""
# Main Parameters #
self.probe_in = 1.4
self.probe_out = 4.0
self.removal_distance = 2.4
self.volume_cutoff = 5.0
self.base_name = "output"
self.output_dir_path = os.getcwd()
# Search Space #
# Box Adjustment
self.box_adjustment = False
self.x = 0.0
self.y = 0.0
self.z = 0.0
self.min_x = 0.0
self.max_x = 0.0
self.min_y = 0.0
self.max_y = 0.0
self.min_z = 0.0
self.max_z = 0.0
self.angle1 = 0
self.angle2 = 0
self.padding = 3.5
# Ligand Adjustment
self.ligand_adjustment = False
self.ligand_cutoff = 5.0
def __init_plugin__(app=None):
"""
Add an entry to the PyMOL "Plugin" menu
"""
from pymol.plugins import addmenuitemqt
addmenuitemqt("PyMOL KVFinder-web Tools", run_plugin_gui)
def run_plugin_gui():
"""
Open PyMOL KVFinder-web Tools dialog
"""
import sys
global dialog
if dialog is None:
dialog = QtWidgets.QApplication([])
window = PyMOLKVFinderWebTools()
window.show()
dialog.exec()
class PyMOLKVFinderWebTools(QtWidgets.QMainWindow):
"""
PyMOL KVFinder Web Tools
This class creates our client graphical user interface (GUI) with PyQt5 package in PyMOL software and defines functions and callback for GUI.
"""
# Signals
msgbox_signal = QtCore.pyqtSignal(bool)
def __init__(self, server=server, path=path):
super(PyMOLKVFinderWebTools, self).__init__()
"""
This method initialize our graphical user interface core attributes and startup configuration, and our worker thread to communicate with KVFinder-web service located at 'server' variable.
Parameters
----------
server: str
KVFinder-web service address (Default: http://kvfinder-web.cnpem.br). Users may set this variable to a locally configured KVFinder-web service by changing 'server' global variable.
path: str
Server path to communicate with KVFinder-web service (Default: /api)
"""
from PyQt6.QtNetwork import QNetworkAccessManager
# Define Default Parameters
self._default = _Default()
# Initialize PyMOLKVFinderWebTools GUI
self.initialize_gui()
# Restore Default Parameters
self.restore(is_startup=True)
# Set box centers
self.x = 0.0
self.y = 0.0
self.z = 0.0
# Define server
self.server = f"{server}/{path.replace('/', '')}"
self.network_manager = QNetworkAccessManager()
# Check server status
status = _check_server_status(self.server)
self.set_server_status(status)
# Create ./KVFinder-web directory for jobs
jobs_dir = os.path.join(os.path.expanduser("~"), ".KVFinder-web")
try:
os.mkdir(jobs_dir)
except FileExistsError:
pass
# Start Worker thread to handle available jobs
global worker
if worker is None:
worker = self._start_worker_thread()
# Get available jobs
self.available_jobs.addItems(_get_jobs())
self.fill_job_information()
# Results
self.results = None
self.input_pdb = None
self.ligand_pdb = None
self.cavity_pdb = None
def initialize_gui(self) -> None:
"""
This method initializes graphical user interface from .ui file, bind scrollbars to QListWidgets and hooks up buttons with callbacks.
"""
# Import the PyQt interface
from PyQt6 import QtWidgets
from PyQt6.uic import loadUi
# populate the QMainWindow from our *.ui file
uifile = os.path.join(os.path.dirname(__file__), "PyMOL-KVFinder-web-tools.ui")
loadUi(uifile, self)
# ScrollBars binded to QListWidgets in Descriptors
scroll_bar_volume = QtWidgets.QScrollBar(self)
self.volume_list.setVerticalScrollBar(scroll_bar_volume)
scroll_bar_area = QtWidgets.QScrollBar(self)
self.area_list.setVerticalScrollBar(scroll_bar_area)
scroll_bar_residues = QtWidgets.QScrollBar(self)
self.residues_list.setVerticalScrollBar(scroll_bar_residues)
# about text
self.about_text.setHtml(about_text)
# Buttons Callback
# hook up QMainWindow buttons callbacks
self.button_run.clicked.connect(self.run)
self.button_exit.clicked.connect(self.close)
self.button_restore.clicked.connect(self.restore)
self.button_grid.clicked.connect(self.show_grid)
# hook up Parameters button callbacks
self.button_browse.clicked.connect(self.select_directory)
self.refresh_input.clicked.connect(lambda: self.refresh(self.input))
# hook up Search Space button callbacks
# Box Adjustment
self.button_draw_box.clicked.connect(self.set_box)
self.button_delete_box.clicked.connect(self.delete_box)
self.button_redraw_box.clicked.connect(self.redraw_box)
self.button_box_adjustment_help.clicked.connect(self.box_adjustment_help)
# Ligand Adjustment
self.refresh_ligand.clicked.connect(lambda: self.refresh(self.ligand))
# hook up methods to results tab
# Jobs
self.available_jobs.currentIndexChanged.connect(self.fill_job_information)
self.button_show_job.clicked.connect(self.show_id)
self.button_add_job_id.clicked.connect(self.add_id)
# Visualization
self.button_browse_results.clicked.connect(self.select_results_file)
self.button_load_results.clicked.connect(self.load_results)
self.volume_list.itemSelectionChanged.connect(
lambda list1=self.volume_list, list2=self.area_list: self.show_cavities(
list1, list2
)
)
self.area_list.itemSelectionChanged.connect(
lambda list1=self.area_list, list2=self.volume_list: self.show_cavities(
list1, list2
)
)
self.avg_depth_list.itemSelectionChanged.connect(
lambda list1=self.avg_depth_list, list2=self.max_depth_list: self.show_depth(
list1, list2
)
)
self.max_depth_list.itemSelectionChanged.connect(
lambda list1=self.max_depth_list, list2=self.avg_depth_list: self.show_depth(
list1, list2
)
)
self.avg_hydropathy_list.itemSelectionChanged.connect(
lambda list1=self.avg_hydropathy_list: self.show_hydropathy(list1)
)
self.residues_list.itemSelectionChanged.connect(self.show_residues)
self.default_view.toggled.connect(self.show_default_view)
self.depth_view.toggled.connect(self.show_depth_view)
self.hydropathy_view.toggled.connect(self.show_hydropathy_view)
def run(self) -> None:
"""
Get detection parameters and molecular structures defined on the GUI and submit a job to KVFinder-web service.
The job submission is handled by QtNetwork package, part of PyQt6, that uses a POST method to send a JSON with data to KVFinder-web service.
"""
from PyQt6 import QtNetwork
from PyQt6.QtCore import QJsonDocument, QUrl
# Create job
parameters = self.create_parameters()
if type(parameters) is dict:
self.job = Job(parameters)
else:
return
print("\n[==> Submitting job to KVFinder-web service ...")
# Post request
try:
# Prepare request
url = QUrl(f"{self.server}/create")
request = QtNetwork.QNetworkRequest(url)
request.setHeader(
QtNetwork.QNetworkRequest.KnownHeaders.ContentTypeHeader,
"application/json",
)
# Prepare data
data = QJsonDocument(self.job.input)
# Post requests
self.reply = self.network_manager.post(request, data.toJson())
self.reply.finished.connect(self._handle_post_response)
except Exception as e:
print(e)
def _handle_post_response(self) -> None:
"""
This methods handles the POST method response.
If there are no error in the request, this methods evaluates the response and process accordingly, by writing incoming results and job information to files.
If there are an error in the request, this method displays a QMessageBox with the corresponding error message and HTTP error code.
"""
from PyQt6 import QtNetwork
# Get QNetworkReply error status
er = self.reply.error()
# Handle Post Response
if er == QtNetwork.QNetworkReply.NetworkError.NoError:
reply = str(self.reply.readAll(), "utf-8")
reply = json.loads(reply)
# Save job id
self.job.id = reply["id"]
# Results not available
if "output" not in reply.keys():
if verbosity in [1, 3]:
print("> Job successfully submitted to KVFinder-web service!")
# Message to user
message = Message(
"Job successfully submitted to KVFinder-web service!", self.job.id
)
message.exec()
# Save job file
self.job.status = "queued"
self.job.save(self.job.id)
print(f"> Job ID: {self.job.id}")
# Add Job ID to Results tab
self.available_jobs.clear()
self.available_jobs.addItems(_get_jobs())
self.available_jobs.setCurrentText(self.job.id)
# Job already sent to KVFinder-web service
else:
status = reply["status"]
# handle job completed
if status == "completed":
if verbosity in [1, 3]:
print("> Job already completed in KVFinder-web service!")
# Message to user
message = Message(
"Job already completed in KVFinder-web service!\nDisplaying results ...",
self.job.id,
status,
)
message.exec()
# Export results
self.job.output = reply
try:
self.job.export()
except Exception as e:
print("Error occurred: ", e)
# Save job file
self.job.status = status
self.job.save(self.job.id)
# Add Job ID to Results tab
if self.job.id not in [
self.available_jobs.itemText(i)
for i in range(self.available_jobs.count())
]:
self.available_jobs.addItem(self.job.id)
self.available_jobs.setCurrentText(self.job.id)
# Show ID
self.show_id()
# Select Results Tab
self.tabs.setCurrentIndex(2)
# handle job not completed
elif status == "running" or status == "queued":
if verbosity in [1, 3]:
print("> Job already submitted to KVFinder-web service!")
# Message to user
message = Message(
"Job already submitted to KVFinder-web service!",
self.job.id,
status,
)
message.exec()
elif er == QtNetwork.QNetworkReply.NetworkError.ConnectionRefusedError:
from PyQt6 import QtWidgets
# Set server status in GUI
self.server_down()
# Message to user
if verbosity in [1, 3]:
print(
"\n\033[93mWarning:\033[0m KVFinder-web service is Offline! Try again later!\n"
)
QtWidgets.QMessageBox.critical(
self,
"Job Submission",
"KVFinder-web service is Offline!\n\nTry again later!",
)
elif er == QtNetwork.QNetworkReply.NetworkError.UnknownContentError:
from PyQt6 import QtWidgets
# Set server status in GUI
self.server_up()
# Message to user
if verbosity in [1, 3]:
print(
f"\n\033[91mError:\033[0mJob exceedes the maximum payload of {data_limit} on KVFinder-web service!\n"
)
QtWidgets.QMessageBox.critical(
self,
"Job Submission",
f"Job exceedes the maximum payload of {data_limit} on KVFinder-web service!",
)
elif er == QtNetwork.QNetworkReply.NetworkError.TimeoutError:
from PyQt6 import QtWidgets
# Set server status in GUI
self.server_down()
# Message to user
if verbosity in [1, 3]:
print(
"\n\033[93mWarning:\033[0m The connection to the KVFinder-web server timed out!\n"
)
QtWidgets.QMessageBox.critical(
self,
"Job Submission",
"The connection to the KVFinder-web server timed out!\n\nCheck your connection and KVFinder-web server status!",
)
else:
reply = str(self.reply.readAll(), "utf-8")
# Message to user
if verbosity in [1, 3]:
print(f"\n\033[91mError {er}\033[0m\n\n")
message = Message(
f"Error {er}!",
job_id=None,
status=None,
notification=f"{self.reply.errorString()}\n{reply}\n",
)
message.exec()
def show_grid(self) -> None:
"""
Callback for the "Show Grid" button.
This method gets minimum and maximum coordinates of the KVFinder-web 3D-grid, dependent on selected parameters, and call draw_grid method with minimum and maximum coordinates.
If there are an error, a QMessageBox will be displayed.
"""
from pymol import cmd
from PyQt6 import QtWidgets
global x, y, z
if self.input.count() > 0:
# Get minimum and maximum dimensions of target PDB
pdb = self.input.currentText()
([min_x, min_y, min_z], [max_x, max_y, max_z]) = cmd.get_extent(pdb)
# Get Probe Out value
probe_out = self.probe_out.value()
probe_out = round(probe_out - round(probe_out, 4) % round(0.6, 4), 1)
# Prepare dimensions
min_x = round(min_x - (min_x % 0.6), 1) - probe_out
min_y = round(min_y - (min_y % 0.6), 1) - probe_out
min_z = round(min_z - (min_z % 0.6), 1) - probe_out
max_x = round(max_x - (max_x % 0.6) + 0.6, 1) + probe_out
max_y = round(max_y - (max_y % 0.6) + 0.6, 1) + probe_out
max_z = round(max_z - (max_z % 0.6) + 0.6, 1) + probe_out
# Get center of each dimension (x, y, z)
x = (min_x + max_x) / 2
y = (min_y + max_y) / 2
z = (min_z + max_z) / 2
# Draw Grid
self.draw_grid(min_x, max_x, min_y, max_y, min_z, max_z)
else:
QtWidgets.QMessageBox.critical(self, "Error", "Select an input PDB!")
return
def draw_grid(self, min_x, max_x, min_y, max_y, min_z, max_z) -> None:
"""
Draw Grid in PyMOL.
An object named grid is created on PyMOL viewer.
Parameters
----------
min_x: float
Minimum X coordinate.
max_x: float
Maximum X coordinate.
min_y: float
Minimum Y coordinate.
max_y: float
Maximum Y coordinate.
min_z: float
Minimum Z coordinate.
max_z: float
Maximum Z coordinate.
"""
from math import cos, sin
from pymol import cmd
# Prepare dimensions
angle1 = 0.0
angle2 = 0.0
min_x = x - min_x
max_x = max_x - x
min_y = y - min_y
max_y = max_y - y
min_z = z - min_z
max_z = max_z - z
# Get positions of grid vertices
# P1
x1 = (
-min_x * cos(angle2)
- (-min_y) * sin(angle1) * sin(angle2)
+ (-min_z) * cos(angle1) * sin(angle2)
+ x
)
y1 = -min_y * cos(angle1) + (-min_z) * sin(angle1) + y
z1 = (
min_x * sin(angle2)
+ min_y * sin(angle1) * cos(angle2)
- min_z * cos(angle1) * cos(angle2)
+ z
)
# P2
x2 = (
max_x * cos(angle2)
- (-min_y) * sin(angle1) * sin(angle2)
+ (-min_z) * cos(angle1) * sin(angle2)
+ x
)
y2 = (-min_y) * cos(angle1) + (-min_z) * sin(angle1) + y
z2 = (
(-max_x) * sin(angle2)
- (-min_y) * sin(angle1) * cos(angle2)
+ (-min_z) * cos(angle1) * cos(angle2)
+ z
)
# P3
x3 = (
(-min_x) * cos(angle2)
- max_y * sin(angle1) * sin(angle2)
+ (-min_z) * cos(angle1) * sin(angle2)
+ x
)
y3 = max_y * cos(angle1) + (-min_z) * sin(angle1) + y
z3 = (
-(-min_x) * sin(angle2)
- max_y * sin(angle1) * cos(angle2)
+ (-min_z) * cos(angle1) * cos(angle2)
+ z
)
# P4
x4 = (
(-min_x) * cos(angle2)
- (-min_y) * sin(angle1) * sin(angle2)
+ max_z * cos(angle1) * sin(angle2)
+ x
)
y4 = (-min_y) * cos(angle1) + max_z * sin(angle1) + y
z4 = (
-(-min_x) * sin(angle2)
- (-min_y) * sin(angle1) * cos(angle2)
+ max_z * cos(angle1) * cos(angle2)
+ z
)
# P5
x5 = (
max_x * cos(angle2)
- max_y * sin(angle1) * sin(angle2)
+ (-min_z) * cos(angle1) * sin(angle2)
+ x
)
y5 = max_y * cos(angle1) + (-min_z) * sin(angle1) + y
z5 = (
(-max_x) * sin(angle2)
- max_y * sin(angle1) * cos(angle2)
+ (-min_z) * cos(angle1) * cos(angle2)
+ z
)
# P6
x6 = (
max_x * cos(angle2)
- (-min_y) * sin(angle1) * sin(angle2)
+ max_z * cos(angle1) * sin(angle2)
+ x
)
y6 = (-min_y) * cos(angle1) + max_z * sin(angle1) + y
z6 = (
(-max_x) * sin(angle2)
- (-min_y) * sin(angle1) * cos(angle2)
+ max_z * cos(angle1) * cos(angle2)
+ z
)
# P7
x7 = (
(-min_x) * cos(angle2)
- max_y * sin(angle1) * sin(angle2)
+ max_z * cos(angle1) * sin(angle2)
+ x
)
y7 = max_y * cos(angle1) + max_z * sin(angle1) + y
z7 = (
-(-min_x) * sin(angle2)
- max_y * sin(angle1) * cos(angle2)
+ max_z * cos(angle1) * cos(angle2)
+ z
)
# P8
x8 = (
max_x * cos(angle2)
- max_y * sin(angle1) * sin(angle2)
+ max_z * cos(angle1) * sin(angle2)
+ x
)
y8 = max_y * cos(angle1) + max_z * sin(angle1) + y
z8 = (
(-max_x) * sin(angle2)
- max_y * sin(angle1) * cos(angle2)
+ max_z * cos(angle1) * cos(angle2)
+ z
)
# Create box object
if "grid" in cmd.get_names("objects"):
cmd.delete("grid")
# Create vertices
cmd.pseudoatom("grid", name="v2", pos=[x2, y2, z2], color="white")
cmd.pseudoatom("grid", name="v3", pos=[x3, y3, z3], color="white")
cmd.pseudoatom("grid", name="v4", pos=[x4, y4, z4], color="white")
cmd.pseudoatom("grid", name="v5", pos=[x5, y5, z5], color="white")
cmd.pseudoatom("grid", name="v6", pos=[x6, y6, z6], color="white")
cmd.pseudoatom("grid", name="v7", pos=[x7, y7, z7], color="white")
cmd.pseudoatom("grid", name="v8", pos=[x8, y8, z8], color="white")
# Connect vertices
cmd.select("vertices", "(name v3,v7)")
cmd.bond("vertices", "vertices")
cmd.select("vertices", "(name v2,v6)")
cmd.bond("vertices", "vertices")
cmd.select("vertices", "(name v5,v8)")
cmd.bond("vertices", "vertices")
cmd.select("vertices", "(name v2,v5)")
cmd.bond("vertices", "vertices")
cmd.select("vertices", "(name v4,v6)")
cmd.bond("vertices", "vertices")
cmd.select("vertices", "(name v4,v7)")
cmd.bond("vertices", "vertices")
cmd.select("vertices", "(name v3,v5)")
cmd.bond("vertices", "vertices")
cmd.select("vertices", "(name v6,v8)")
cmd.bond("vertices", "vertices")
cmd.select("vertices", "(name v7,v8)")
cmd.bond("vertices", "vertices")
cmd.pseudoatom("grid", name="v1x", pos=[x1, y1, z1], color="white")
cmd.pseudoatom("grid", name="v2x", pos=[x2, y2, z2], color="white")
cmd.select("vertices", "(name v1x,v2x)")
cmd.bond("vertices", "vertices")
cmd.pseudoatom("grid", name="v1y", pos=[x1, y1, z1], color="white")
cmd.pseudoatom("grid", name="v3y", pos=[x3, y3, z3], color="white")
cmd.select("vertices", "(name v1y,v3y)")
cmd.bond("vertices", "vertices")
cmd.pseudoatom("grid", name="v4z", pos=[x4, y4, z4], color="white")
cmd.pseudoatom("grid", name="v1z", pos=[x1, y1, z1], color="white")
cmd.select("vertices", "(name v1z,v4z)")
cmd.bond("vertices", "vertices")
cmd.delete("vertices")
def restore(self, is_startup=False) -> None:
"""
Callback for the "Restore Default Values" button.
This method restore detection parameters to default (class Default). If the GUI is not starting up, extra steps are taken to clean the enviroment.
Parameters
----------
is_startup: bool
Whether the GUI is starting up.
"""
from pymol import cmd
from PyQt6 import QtWidgets
# Restore Results Tab
if not is_startup:
reply = QtWidgets.QMessageBox(self)
reply.setText("Also restore Results Visualization tab?")
reply.setWindowTitle("Restore Values")
reply.setStandardButtons(
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No
)
reply.setIcon(QtWidgets.QMessageBox.Information)
reply.checkbox = QtWidgets.QCheckBox("Also remove input and ligand PDBs?")
reply.layout = reply.layout()
reply.layout.addWidget(reply.checkbox, 1, 2)
if reply.exec() == QtWidgets.QMessageBox.Yes:
# Remove cavities, residues and pdbs (input, ligand, cavity)
cmd.delete("cavities")
cmd.delete("residues")
if self.input_pdb and reply.checkbox.isChecked():
cmd.delete(self.input_pdb)
if self.ligand_pdb and reply.checkbox.isChecked():
cmd.delete(self.ligand_pdb)
if self.cavity_pdb:
cmd.delete(self.cavity_pdb)
global results
results = self.input_pdb = self.ligand_pdb = self.cavity_pdb = None
cmd.frame(1)
# Clean results
self.clean_results()
self.vis_results_file_entry.clear()
# Restore PDB and ligand input
self.refresh(self.input)
self.refresh(self.ligand)
# Delete grid
cmd.delete("grid")
# Main tab #
self.base_name.setText(self._default.base_name)
self.probe_in.setValue(self._default.probe_in)
self.probe_out.setValue(self._default.probe_out)
self.volume_cutoff.setValue(self._default.volume_cutoff)
self.removal_distance.setValue(self._default.removal_distance)
self.output_dir_path.setText(self._default.output_dir_path)
# Search Space Tab #
# Box Adjustment
self.box_adjustment.setChecked(self._default.box_adjustment)
self.padding.setValue(self._default.padding)
self.delete_box()
# Ligand Adjustment
self.ligand_adjustment.setChecked(self._default.ligand_adjustment)
self.ligand.clear()
self.ligand_cutoff.setValue(self._default.ligand_cutoff)
def refresh(self, combo_box) -> None:
"""
Callback for the "Refresh" button.
This method gets objects on the PyMOL viewer and displays them on a target combo box.
Parameters
----------
combo_box: QComboBox
A target QComboBox to add the object names that are on PyMOL scene
"""
from pymol import cmd
combo_box.clear()
for item in cmd.get_names("all"):
if (
cmd.get_type(item) == "object:molecule"
and item != "box"
and item != "grid"
and item != "cavities"
and item != "residues"
and item[-16:] != ".KVFinder.output"
and item != "target_exclusive"
):
combo_box.addItem(item)
return
def select_directory(self) -> None:
"""
Callback for the "Browse ..." button.
This method opens a QFileDialog to select a directory.
"""
from PyQt6 import QtCore, QtWidgets
fname = QtWidgets.QFileDialog.getExistingDirectory(
caption="Choose Output Directory", directory=os.getcwd()
)
if fname:
fname = QtCore.QDir.toNativeSeparators(fname)
if os.path.isdir(fname):
self.output_dir_path.setText(fname)
return
def set_box(self) -> None:
"""
This method creates the box coordinates, enables 'Delete Box' and 'Redraw Box' buttons and calls draw_box method.
It gets the minimum and maximum coordinates of the current selection 'sele'. With that, it calculates the center, minimum and maximum coordinates and rotation angles of the box. Afterwards, enable the components of Box adjusment frame and set their values.
"""
from pymol import cmd
# Delete Box object in PyMOL
if "box" in cmd.get_names("selections"):
cmd.delete("box")
# Get dimensions of selected residues
selection = "sele"
if selection in cmd.get_names("selections"):
([min_x, min_y, min_z], [max_x, max_y, max_z]) = cmd.get_extent(selection)
else:
([min_x, min_y, min_z], [max_x, max_y, max_z]) = cmd.get_extent("")
# Get center of each dimension (x, y, z)
self.x = (min_x + max_x) / 2
self.y = (min_y + max_y) / 2
self.z = (min_z + max_z) / 2
# Set Box variables in interface
self.min_x.setValue(round(self.x - (min_x - self.padding.value()), 1))
self.max_x.setValue(round((max_x + self.padding.value()) - self.x, 1))
self.min_y.setValue(round(self.y - (min_y - self.padding.value()), 1))
self.max_y.setValue(round((max_y + self.padding.value()) - self.y, 1))
self.min_z.setValue(round(self.z - (min_z - self.padding.value()), 1))
self.max_z.setValue(round((max_z + self.padding.value()) - self.z, 1))
self.angle1.setValue(0)
self.angle2.setValue(0)
# Setting background box values
self.min_x_set = self.min_x.value()
self.max_x_set = self.max_x.value()
self.min_y_set = self.min_y.value()
self.max_y_set = self.max_y.value()
self.min_z_set = self.min_z.value()
self.max_z_set = self.max_z.value()
self.angle1_set = self.angle1.value()
self.angle2_set = self.angle2.value()
self.padding_set = self.padding.value()
# Draw box
self.draw_box()
# Enable/Disable buttons
self.button_draw_box.setEnabled(False)
self.button_redraw_box.setEnabled(True)
self.min_x.setEnabled(True)
self.min_y.setEnabled(True)
self.min_z.setEnabled(True)
self.max_x.setEnabled(True)
self.max_y.setEnabled(True)
self.max_z.setEnabled(True)
self.angle1.setEnabled(True)
self.angle2.setEnabled(True)
def draw_box(self) -> None:
"""
Callback for the "Draw box" button.
This method calculates each vertice of the custom box. Then, it draws and connects them on the PyMOL viewer as a object named 'box'.
"""
from math import cos, pi, sin
import pymol
from pymol import cmd
# Convert angle
angle1 = (self.angle1.value() / 180.0) * pi
angle2 = (self.angle2.value() / 180.0) * pi
# Get positions of box vertices
# P1
x1 = (
-self.min_x.value() * cos(angle2)
- (-self.min_y.value()) * sin(angle1) * sin(angle2)
+ (-self.min_z.value()) * cos(angle1) * sin(angle2)
+ self.x
)
y1 = (
-self.min_y.value() * cos(angle1)
+ (-self.min_z.value()) * sin(angle1)
+ self.y
)
z1 = (
self.min_x.value() * sin(angle2)
+ self.min_y.value() * sin(angle1) * cos(angle2)
- self.min_z.value() * cos(angle1) * cos(angle2)
+ self.z