-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlayouts.py
1570 lines (1347 loc) · 79.8 KB
/
layouts.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
from logging import getLogger, CRITICAL
from matplotlib import pyplot, rcParams, patches
from numpy import array, zeros, linspace, deg2rad, sum, cos, sin, sqrt, pi
from os import path
from PIL import Image, PngImagePlugin
try:
from pymol2 import PyMOL # Please refer to https://pymol.org/2/ for download of PyMOL library
except ModuleNotFoundError:
print("PyMOL is not installed!")
from re import search
from types import FunctionType
from warnings import filterwarnings
filterwarnings("ignore")
getLogger("matplotlib").setLevel(CRITICAL)
def obtain_widget_icon(save_path: str, widget_type: str, params: dict, dpi: int = 1200):
"""
Obtain the widget icon based on the predetermined setting.
:param save_path: the path of save icon.
:type save_path: str
:param widget_type: widget type including "arrow" and "rotation".
:type widget_type: str
:param params: parameters of the widget.
:type params: dict
:param dpi: dots per inch.
:type dpi: int
"""
if widget_type == "line":
if "degree" in params:
if 0 <= params["degree"] <= 180:
x = pi * params["degree"] / 180
figure = pyplot.figure(figsize=(2, 2))
if "color" in params:
color = params["color"]
else:
color = "black"
if "linestyle" in params:
linestyle = params["linestyle"]
else:
linestyle = "-"
if "linewidth" in params:
linewidth = params["linewidth"]
else:
linewidth = 1.0
pyplot.xlim(-1, 1)
pyplot.ylim(-1, 1)
pyplot.plot([-cos(x), cos(x)], [-sin(x), sin(x)], linewidth=linewidth,
color=color, linestyle=linestyle)
pyplot.axis('off')
figure.savefig(save_path, dpi=dpi, transparent=True, pad_inches=0, bbox_inches="tight")
pyplot.close()
else:
raise ValueError("The scope of \"degree\" is [0, 360].")
else:
raise ValueError("\"degree\" is a parameter that \"arrow\" must specify.")
elif widget_type == "arrow":
if "degree" in params:
if 0 <= params["degree"] <= 360:
x = pi * params["degree"] / 180
figure = pyplot.figure(figsize=(2, 2))
if "color" in params:
color = params["color"]
else:
color = "black"
if "linestyle" in params:
linestyle = params["linestyle"]
else:
linestyle = "-"
if "width" in params:
width = params["width"]
else:
width = 0.02
if "head_width" in params:
head_width = params["head_width"]
else:
head_width = 0.3
if "head_length" in params:
head_length = params["head_length"]
else:
head_length = 0.4
if "overhang" in params:
overhang = params["overhang"]
else:
overhang = 0.25
pyplot.arrow(0.5 - 0.5 * cos(x), 0.5 - 0.5 * sin(x), 1.0 * cos(x), 1.0 * sin(x), width=width,
head_width=head_width, head_length=head_length, overhang=overhang,
length_includes_head=True, color=color, linestyle=linestyle)
pyplot.axis('off')
figure.savefig(save_path, dpi=dpi, transparent=True)
pyplot.close()
else:
raise ValueError("The scope of \"degree\" is [0, 360].")
else:
raise ValueError("\"degree\" is a parameter that \"arrow\" must specify.")
elif widget_type == "rotation":
# use style 1.
if "turn" in params and "degree" in params:
if params["turn"] in ["right", "left"] and 0 <= params["degree"] <= 180:
major_axis, minor_axis = 1.8, 0.6
if params["turn"] == "right":
x_values = cos(deg2rad(linspace(-90, 270, 361)[::-1])) * major_axis / 2.0
y_values = sin(deg2rad(linspace(-90, 270, 361)[::-1])) * minor_axis / 2.0
else:
x_values = cos(deg2rad(linspace(-90, 270, 361))) * major_axis / 2.0
y_values = sin(deg2rad(linspace(-90, 270, 361))) * minor_axis / 2.0
pyplot.figure(figsize=(2, 2))
ax = pyplot.subplot(1, 1, 1)
pyplot.vlines(0, -0.6, -1, color="k", lw=3, zorder=0)
# noinspection PyUnresolvedReferences
ax.add_patch(patches.Ellipse(xy=(0.0, 0.0), width=major_axis, height=minor_axis, fc="silver"))
pyplot.vlines(0, 0, +1, color="k", lw=3, zorder=2)
if params["turn"] == "right":
pyplot.fill_between([0.0, +0.3], [-0.45, -0.3], [-0.15, -0.3], color="k", zorder=3)
else:
pyplot.fill_between([-0.3, 0.0], [-0.3, -0.45], [-0.3, -0.15], color="k", zorder=3)
if params["degree"] != 180:
pyplot.plot([0, x_values[params["degree"] + 1]], [0, y_values[params["degree"] + 1]],
color="k", lw=2, ls=":", zorder=4)
pyplot.scatter([0, x_values[params["degree"] + 1]], [0, y_values[params["degree"] + 1]],
marker="o", s=40, color="k", zorder=4)
pyplot.plot(x_values[:params["degree"] + 1], y_values[:params["degree"] + 1], color="k", lw=3, zorder=4)
pyplot.xlim(-1, +1)
pyplot.ylim(-1, +1)
pyplot.axis("off")
pyplot.savefig(save_path, transparent=True, pad_inches=0, bbox_inches="tight", dpi=1200)
pyplot.close()
else:
raise ValueError("The scope of \"turn\" is \"right\" or \"left\" and that of \"degree\" is [0, 360].")
# use style 2.
elif "elevation" in params and "azimuth" in params:
if -180 <= params["elevation"] <= 180 and -180 <= params["azimuth"] <= 180:
if params["elevation"] == 0 and params["azimuth"] == 0:
raise ValueError("\"elevation\" and \"azimuth\" cannot be both 0.")
major_axis, minor_axis = 1.2, 1.2 / sqrt(3)
x_values_1 = cos(deg2rad(linspace(0, 360, 361))) * major_axis / 2.0
y_values_1 = sin(deg2rad(linspace(0, 360, 361))) * minor_axis / 2.0
x_values_2 = cos(deg2rad(linspace(-90, 270, 361))) * minor_axis / 2.0
y_values_2 = sin(deg2rad(linspace(-90, 270, 361))) * major_axis / 2.0
x_values_3 = cos(deg2rad(linspace(0, 360, 361))) * major_axis / 2.0
y_values_3 = sin(deg2rad(linspace(0, 360, 361))) * major_axis / 2.0
# elevation angle in the z plane.
elevation_x_values = cos(deg2rad(linspace(-150, 210, 361)[::-1])) * minor_axis / 2.0
elevation_y_values = sin(deg2rad(linspace(-150, 210, 361)[::-1])) * major_axis / 2.0
line_info, area_info, last_x, last_y = [], None, None, None
if 0 < params["elevation"] <= 90:
addition = int(params["elevation"] / 3 * 4)
x, y = elevation_x_values[:addition], elevation_y_values[:addition]
line_info.append((x, y, "-"))
last_x, last_y = x[-1], y[-1]
upper = []
for x_value, y_value in zip(x, y):
upper.append(x_value if x_value <= 0 else x_value / last_x * last_y)
area_info = (array(x.tolist() + [0]), array(y.tolist() + [0]), array(upper + [0]))
elevation_data = line_info, area_info, last_x, last_y
elif params["elevation"] > 90:
x_1, y_1 = elevation_x_values[:120], elevation_y_values[:120]
addition = int((params["elevation"] - 90) / 3 * 2)
x_2, y_2 = elevation_x_values[120:120 + addition], elevation_y_values[120:120 + addition]
line_info.append((x_1, y_1, "-"))
line_info.append((x_2, y_2, ":"))
last_x, last_y = x_2[-1], y_2[-1]
area_info = [[], [], []]
for x_value, y_value in zip(x_1, y_1):
area_info[0].append(x_value)
area_info[1].append(x_value)
area_info[2].append(y_value)
for index in range(addition):
area_info[0].append(x_2[index])
area_info[1].append(x_2[index] / last_x * last_y)
area_info[2].append(y_2[index])
area_info = (array(area_info[0]), array(area_info[1]), array(area_info[2]))
elevation_data = line_info, area_info, last_x, last_y
elif -90 < params["elevation"] < 0:
addition = int((90 + params["elevation"]) / 3 * 2)
x, y = elevation_x_values[300 + addition:], elevation_y_values[300 + addition:]
line_info.append((x, y, "-"))
last_x, last_y = x[0], y[0]
upper = []
for x_value, y_value in zip(x, y):
upper.append(x_value / last_x * last_y)
area_info = (array(x.tolist() + [0]), array(y.tolist() + [0]), array(upper + [0]))
elevation_data = line_info, area_info, last_x, last_y
elif -90 == params["elevation"]:
addition = int((90 + params["elevation"]) / 3 * 2)
x, y = elevation_x_values[300 + addition:], elevation_y_values[300 + addition:]
line_info.append((x, y, "-"))
last_x, last_y = x[0], y[0]
upper = []
for x_value, y_value in zip(x, y):
upper.append(x_value)
area_info = (x, y, upper)
elevation_data = line_info, area_info, last_x, last_y
elif -90 > params["elevation"]:
x_1, y_1 = elevation_x_values[300:], elevation_y_values[300:]
addition = int((-params["elevation"] - 90) / 3 * 4)
x_2, y_2 = elevation_x_values[300 - addition:300], elevation_y_values[300 - addition:300]
line_info.append((x_1, y_1, "-"))
line_info.append((x_2, y_2, ":"))
last_x, last_y = x_2[0], y_2[0]
area_info = [[], [], []]
for x_value, y_value in zip(x_1, y_1):
area_info[0].append(x_value)
area_info[1].append(x_value)
area_info[2].append(y_value)
for x_value, y_value in zip(x_2[::-1], y_2[::-1]):
area_info[0].append(x_value)
area_info[1].append(y_value)
area_info[2].append(x_value / last_x * last_y)
elevation_data = line_info, area_info, last_x, last_y
else:
elevation_data = None
# azimuth angle for the x,y plane.
azimuth_x_values = cos(deg2rad(linspace(-120, 240, 361))) * major_axis / 2.0
azimuth_y_values = sin(deg2rad(linspace(-120, 240, 361))) * minor_axis / 2.0
line_info, area_info, last_x, last_y = [], None, None, None
if 0 < params["azimuth"] <= 90:
addition = int(params["azimuth"] / 3 * 4)
x, y = azimuth_x_values[:addition], azimuth_y_values[:addition]
line_info.append((x, y, "-"))
last_x, last_y = x[-1], y[-1]
upper = []
for x_value, y_value in zip(x, y):
upper.append(x_value if x_value <= 0 else x_value / last_x * last_y)
area_info = (x, y, array(upper))
azimuth_data = line_info, area_info, last_x, last_y
elif params["azimuth"] > 90:
x_1, y_1 = azimuth_x_values[:120], azimuth_y_values[:120]
addition = int((params["azimuth"] - 90) / 3 * 2)
x_2, y_2 = azimuth_x_values[120:120 + addition], azimuth_y_values[120:120 + addition]
line_info.append((x_1, y_1, "-"))
line_info.append((x_2, y_2, ":"))
last_x, last_y = x_2[-1], y_2[-1]
area_info = [[], [], []]
for index, (x_value, y_value) in enumerate(zip(x_1, y_1)):
if index < 120 - addition:
upper_value = x_value if x_value < 0 else x_value / last_x * last_y
else:
upper_value = y_2[::-1][index - 120 + addition]
area_info[0].append(x_value)
area_info[1].append(y_value)
area_info[2].append(upper_value)
area_info = (array(area_info[0]), array(area_info[1]), array(area_info[2]))
azimuth_data = line_info, area_info, last_x, last_y
elif -90 <= params["azimuth"] < 0:
addition = int((90 + params["azimuth"]) / 3 * 2)
x, y = azimuth_x_values[300 + addition:], azimuth_y_values[300 + addition:]
line_info.append((x, y, "-"))
last_x, last_y = x[0], y[0]
upper = []
for x_value, y_value in zip(x, y):
upper.append(x_value / last_x * last_y)
area_info = (array(x.tolist() + [0]), array(y.tolist() + [0]), array(upper + [0]))
azimuth_data = line_info, area_info, last_x, last_y
elif -90 > params["azimuth"]:
x_1, y_1 = azimuth_x_values[300:], azimuth_y_values[300:]
addition = int((-params["azimuth"] - 90) / 3 * 4)
x_2, y_2 = azimuth_x_values[300 - addition:300], azimuth_y_values[300 - addition:300]
line_info.append((x_1, y_1, "-"))
line_info.append((x_2, y_2, ":"))
last_x, last_y = x_2[0], y_2[0]
area_info = [[], [], []]
for index in range(min(60, addition)):
area_info[0].append(x_1[index])
area_info[1].append(y_1[index])
area_info[2].append(y_2[::-1][index])
if addition > 60:
for index in range(60, addition):
area_info[0].append(x_2[::-1][index])
area_info[1].append(x_2[::-1][index] / last_x * last_y)
area_info[2].append(y_2[::-1][index])
else:
for index in range(addition, 60):
area_info[0].append(x_1[index])
area_info[1].append(y_1[index])
area_info[2].append(x_1[index] / last_x * last_y)
area_info[0].append(0)
area_info[1].append(0)
area_info[2].append(0)
azimuth_data = line_info, area_info, last_x, last_y
else:
azimuth_data = None
pyplot.figure(figsize=(2, 2))
pyplot.plot(x_values_1[:180], y_values_1[:180], color="grey", lw=1, ls=":", zorder=0)
pyplot.plot(x_values_1[180:], y_values_1[180:], color="grey", lw=1, zorder=0)
pyplot.plot(x_values_2[:180], y_values_2[:180], color="grey", lw=1, ls=":", zorder=0)
pyplot.plot(x_values_2[180:], y_values_2[180:], color="grey", lw=1, zorder=0)
pyplot.plot(x_values_3, y_values_3, color="grey", lw=1, zorder=0)
if elevation_data is not None:
line_info, area_info, last_x, last_y = elevation_data
if area_info is not None:
if params["elevation"] < 0:
pyplot.fill_between(area_info[0], area_info[1], area_info[2],
fc="royalblue", lw=0, alpha=0.5, zorder=2)
else:
pyplot.fill_between(area_info[0], area_info[1], area_info[2],
fc="royalblue", lw=0, alpha=0.5, zorder=4)
for x, y, style in line_info:
pyplot.plot(x, y, color="k", lw=3, ls=style, zorder=5)
if params["elevation"] > 0:
pyplot.fill_between([-0.15, 0, +0.15], [-1, -1, -1], [-1, -0.7, -1], color="k", lw=0, zorder=6)
elif params["elevation"] < 0:
pyplot.fill_between([-0.15, 0, +0.15], [+1, +1, +1], [+1, 0.7, +1], color="k", lw=0, zorder=6)
if azimuth_data is not None:
line_info, area_info, last_x, last_y = azimuth_data
if area_info is not None:
pyplot.fill_between(area_info[0], area_info[1], area_info[2],
fc="chocolate", lw=0, alpha=0.5, zorder=3)
for x, y, style in line_info:
pyplot.plot(x, y, color="k", lw=3, ls=style, zorder=5)
if params["azimuth"] > 0:
pyplot.fill_between([0.7, 1.0], [0, -0.15], [0, +0.15], color="k", lw=0, zorder=6)
elif params["azimuth"] < 0:
pyplot.fill_between([-1, -0.7], [-0.15, 0], [+0.15, 0], color="k", lw=0, zorder=6)
pyplot.xlim(-1, +1)
pyplot.ylim(-1, +1)
pyplot.axis("off")
pyplot.savefig(save_path, transparent=True, pad_inches=0, bbox_inches="tight", dpi=1200)
pyplot.close()
else:
raise ValueError("The scope of \"elevation\" and \"azimuth\" is [-180, +180].")
else:
raise ValueError("No such rotation type! "
+ "You can input \"turn\" and \"degree\" for style 1, "
+ "or input \"elevation\" and \"azimuth\" for style 2.")
else:
raise ValueError("No such widget type (\"arrow\" and \"rotation\" only).")
class DefaultStructureImage:
def __init__(self, structure_paths: list):
self._mol = PyMOL()
self._mol.start()
self.__structure_names = []
for structure_path in structure_paths:
self._mol.cmd.load(structure_path, quiet=1)
self.__structure_names.append(structure_path[structure_path.rindex("/") + 1: structure_path.rindex(".")])
self._mol.cmd.ray(quiet=1) # make PyMOL run silently.
def set_cache(self, cache_contents: list):
"""
Set cache contents of the structure.
:param cache_contents: hidden contents.
:type cache_contents: list
"""
for hidden_information in cache_contents:
if ":" in hidden_information:
shading_type, target_information = hidden_information.split(":")
if shading_type == "atom":
for target in target_information.split(","):
if "+" in target:
if target.count("+") > 1:
selected_model, selected_chain, selected_atom = target.split("+")
selection_command = "(m. " + selected_model + " and c. " + selected_chain
selection_command = selection_command + " and e. " + selected_atom + ")"
else:
selected_chain, selected_atom = target.split("+")
selection_command = "(c. " + selected_chain + " and e. " + selected_atom + ")"
else:
selection_command = "(e. " + target + ")"
self._mol.cmd.hide(selection=selection_command)
elif shading_type == "position":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_position = target.split("+")
if search(pattern=r"^[0-9]*[1-9][0-9]*$", string=selected_position):
selection_command = "(c. " + selected_chain + " and i. " + selected_position + ")"
else:
raise ValueError("Position (" + selected_position + ") should be a positive integer!")
else:
if search(pattern=r"^[0-9]*[1-9][0-9]*$", string=target):
selection_command = "(i. " + target + ")"
else:
raise ValueError("Position (" + target + ") should be a positive integer!")
self._mol.cmd.hide(selection=selection_command)
elif shading_type == "range":
for target in target_information.split(","):
if "+" in target:
if target.count("+") > 1:
selected_model, selected_chain, selected_range = target.split("+")
if "-" in selected_range and selected_range.count("-") == 1:
former, latter = selected_range.split("-")
if int(former) < int(latter):
selection_command = "(m. " + selected_model + " and c. " + selected_chain
selection_command = selection_command + " and i. " + selected_range + ")"
else:
raise ValueError("The former position needs to be less than the latter position"
+ " in the Range (" + selected_range + ").")
else:
raise ValueError("Range (" + selected_range + ") needs to "
+ "meet the \"number-number\" format!")
else:
selected_chain, selected_range = target.split("+")
if "-" in selected_range and selected_range.count("-") == 1:
former, latter = selected_range.split("-")
if int(former) < int(latter):
selection_command = "(c. " + selected_chain + " and i. " + selected_range + ")"
else:
raise ValueError("The former position needs to be less than the latter position"
+ " in the Range (" + selected_range + ").")
else:
raise ValueError("Range (" + selected_range + ") needs to "
+ "meet the \"number-number\" format!")
else:
if "-" in target and target.count("-") == 1:
former, latter = target.split("-")
if int(former) < int(latter):
selection_command = "(i. " + target + ")"
else:
raise ValueError("The former position needs to be less than the latter position "
+ "in the Range (" + target + ").")
else:
raise ValueError("Range (" + target + ") needs to meet the \"number-number\" format!")
self._mol.cmd.hide(selection=selection_command)
elif shading_type == "residue":
for target in target_information.split(","):
if "+" in target:
if target.count("+") > 1:
selected_model, selected_chain, selected_residue = target.split("+")
selection_command = "(m. " + selected_model + " and c. " + selected_chain
selection_command = selection_command + " and r. " + selected_residue + ")"
else:
selected_chain, selected_residue = target.split("+")
selection_command = "(c. " + selected_chain + " and r. " + selected_residue + ")"
else:
selection_command = "(r. " + target + ")"
self._mol.cmd.hide(selection=selection_command)
elif shading_type == "segment":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_segment = target.split("+")
if search(pattern=r"^[A-Z]+$", string=selected_segment):
selection_command = "(c. " + selected_chain + " and ps. " + selected_segment + ")"
else:
raise ValueError("Segment (" + selected_segment + ") should be a string "
+ "composed of uppercase letters!")
else:
if search(pattern=r"^[A-Z]+$", string=target):
selection_command = "(ps. " + target + ")"
else:
raise ValueError("Segment (" + target + ") should be a string "
+ "composed of uppercase letters!")
self._mol.cmd.hide(selection=selection_command)
elif shading_type == "chain":
for target in target_information.split(","):
if "+" in target:
selected_model, selected_chain = target.split("+")
selection_command = "(m. " + selected_model + " and c. " \
+ selected_chain + " and (not hetatm))"
else:
selection_command = "(c. " + target + " and (not hetatm))"
self._mol.cmd.hide(selection=selection_command)
elif shading_type == "model":
for target in target_information.split(","):
selection_command = "(m. " + target + ")"
self._mol.cmd.hide(selection=selection_command)
else:
raise ValueError("No such shading type! We only support "
+ "\"position\", \"range\", \"residue\", \"segment\", \"chain\" and \"model\".")
else:
raise ValueError("No such representing information! We only support one type of information, i.e. "
+ "\"shading type:target,target,...,target\"")
def set_zoom(self, zoom_contents: list, buffer: float = 0.0):
"""
Set zoom contents of the structure.
:param zoom_contents: structure content that needs to be zoomed.
:type zoom_contents: list
:param buffer: the buffer area size of the target structure.
:type buffer: float
"""
for zoom_information in zoom_contents:
if ":" in zoom_information:
shading_type, target_information = zoom_information.split(":")
if shading_type == "atom":
for target in target_information.split(","):
if "+" in target:
if target.count("+") > 1:
selected_model, selected_chain, selected_atom = target.split("+")
selection_command = "(m. " + selected_model + " and c. " + selected_chain
selection_command = selection_command + " and e. " + selected_atom + ")"
else:
selected_chain, selected_atom = target.split("+")
selection_command = "(c. " + selected_chain + " and e. " + selected_atom + ")"
else:
selection_command = "(e. " + target + ")"
self._mol.cmd.zoom(selection=selection_command, buffer=buffer)
elif shading_type == "position":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_position = target.split("+")
if search(pattern=r"^[0-9]*[1-9][0-9]*$", string=selected_position):
selection_command = "(c. " + selected_chain + " and i. " + selected_position + ")"
else:
raise ValueError("Position (" + selected_position + ") should be a positive integer!")
else:
if search(pattern=r"^[0-9]*[1-9][0-9]*$", string=target):
selection_command = "(i. " + target + ")"
else:
raise ValueError("Position (" + target + ") should be a positive integer!")
self._mol.cmd.zoom(selection=selection_command, buffer=buffer)
elif shading_type == "range":
for target in target_information.split(","):
if "+" in target:
if target.count("+") > 1:
selected_model, selected_chain, selected_range = target.split("+")
if "-" in selected_range and selected_range.count("-") == 1:
former, latter = selected_range.split("-")
if int(former) < int(latter):
selection_command = "(m. " + selected_model + " and c. " + selected_chain
selection_command = selection_command + " and i. " + selected_range + ")"
else:
raise ValueError("The former position needs to be less than the latter position"
+ " in the Range (" + selected_range + ").")
else:
raise ValueError("Range (" + selected_range + ") needs to "
+ "meet the \"number-number\" format!")
else:
selected_chain, selected_range = target.split("+")
if "-" in selected_range and selected_range.count("-") == 1:
former, latter = selected_range.split("-")
if int(former) < int(latter):
selection_command = "(c. " + selected_chain + " and i. " + selected_range + ")"
else:
raise ValueError("The former position needs to be less than the latter position"
+ " in the Range (" + selected_range + ").")
else:
raise ValueError("Range (" + selected_range + ") needs to "
+ "meet the \"number-number\" format!")
else:
if "-" in target and target.count("-") == 1:
former, latter = target.split("-")
if int(former) < int(latter):
selection_command = "(i. " + target + ")"
else:
raise ValueError("The former position needs to be less than the latter position "
+ "in the Range (" + target + ").")
else:
raise ValueError("Range (" + target + ") needs to meet the \"number-number\" format!")
self._mol.cmd.zoom(selection=selection_command, buffer=buffer)
elif shading_type == "residue":
for target in target_information.split(","):
if "+" in target:
if target.count("+") > 1:
selected_model, selected_chain, selected_residue = target.split("+")
selection_command = "(m. " + selected_model + " and c. " + selected_chain
selection_command = selection_command + " and r. " + selected_residue + ")"
else:
selected_chain, selected_residue = target.split("+")
selection_command = "(c. " + selected_chain + " and r. " + selected_residue + ")"
else:
selection_command = "(r. " + target + ")"
self._mol.cmd.zoom(selection=selection_command, buffer=buffer)
elif shading_type == "segment":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_segment = target.split("+")
if search(pattern=r"^[A-Z]+$", string=selected_segment):
selection_command = "(c. " + selected_chain + " and ps. " + selected_segment + ")"
else:
raise ValueError("Segment (" + selected_segment + ") should be a string "
+ "composed of uppercase letters!")
else:
if search(pattern=r"^[A-Z]+$", string=target):
selection_command = "(ps. " + target + ")"
else:
raise ValueError("Segment (" + target + ") should be a string "
+ "composed of uppercase letters!")
self._mol.cmd.zoom(selection=selection_command, buffer=buffer)
elif shading_type == "chain":
for target in target_information.split(","):
if "+" in target:
selected_model, selected_chain = target.split("+")
selection_command = "(m. " + selected_model + " and c. " + selected_chain + ")"
else:
selection_command = "(c. " + target + ")"
self._mol.cmd.zoom(selection=selection_command, buffer=buffer)
elif shading_type == "model":
for target in target_information.split(","):
selection_command = "(m. " + target + ")"
self._mol.cmd.zoom(selection=selection_command, buffer=buffer)
else:
raise ValueError("No such shading type! We only support "
+ "\"position\", \"range\", \"residue\", \"segment\", \"chain\" and \"model\".")
else:
raise ValueError("No such representing information! We only support one type of information, i.e. "
+ "\"shading type:target,target,...,target\"")
def set_state(self, translate: list = None, rotate: list = None, inner_align: bool = False, target: str = None,
mobile: str = None, only_rotate: bool = False):
"""
Set the state of the structure.
:param translate: translate distances with x/y/z-axis.
:type translate: list or None
:param rotate: rotate degree with x/y/z-axis.
:type rotate: list or None
:param inner_align: align multiple structures through built-in interfaces (cmd.align).
:type inner_align: bool
:param target: the target (or template) name can be specified if the inner align is executed.
:type target: str or None
:param mobile: the mobile name can be specified if the inner align is executed.
:type mobile: str or None
:param only_rotate: only rotation, no initialization.
:type only_rotate: bool
"""
if inner_align and len(self.__structure_names) > 1:
if target is not None:
if mobile is not None:
self._mol.cmd.align(mobile, target)
else:
for mobile in self.__structure_names:
if mobile != target:
self._mol.cmd.align(mobile, target)
else:
target = self.__structure_names[0]
for mobile in self.__structure_names[1:]:
self._mol.cmd.align(mobile, target)
if only_rotate:
self._mol.cmd.rotate(axis="x", angle=rotate[0])
self._mol.cmd.rotate(axis="y", angle=rotate[1])
self._mol.cmd.rotate(axis="z", angle=rotate[2])
else:
if translate is not None:
self._mol.cmd.translate(vector=translate)
else:
self._mol.cmd.center()
self._mol.cmd.orient()
self._mol.cmd.zoom(complete=1)
if rotate is not None:
self._mol.cmd.rotate(axis="x", angle=rotate[0])
self._mol.cmd.rotate(axis="y", angle=rotate[1])
self._mol.cmd.rotate(axis="z", angle=rotate[2])
def set_shape(self, representation_plan: list, initial_representation: str = "cartoon",
independent_color: bool = False, closed_surface: bool = False):
"""
Set the shape (or representation in PyMOL) of the structure.
:param representation_plan: the type of the visual structure.
:type representation_plan: list
:param initial_representation: if representation type is index, can optionally operate on the specified chain.
:type initial_representation: str
:param independent_color: if independent_color is False, colors can leak into the open surface edge.
:type independent_color: bool
:param closed_surface: if closed_surface is True, create a closed surface.
:type closed_surface: bool
"""
if initial_representation is not None:
self._mol.cmd.show(representation=initial_representation, selection="(all)")
if independent_color:
self._mol.cmd.set(name="surface_proximity", value="off")
for step, (representing_information, representation) in enumerate(representation_plan):
if type(representing_information) is not str:
raise ValueError("The format of representing information at step " + str(step + 1) + " is illegal! "
+ "We only support \"str\" format!")
if ":" in representing_information:
shading_type, target_information = representing_information.split(":")
if shading_type == "position":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_position = target.split("+")
if search(pattern=r"^[0-9]*[1-9][0-9]*$", string=selected_position):
selection_command = "(c. " + selected_chain + " and i. " + selected_position + ")"
else:
raise ValueError(
"Position (" + selected_position + ") should be a positive integer!")
else:
if search(pattern=r"^[0-9]*[1-9][0-9]*$", string=target):
selection_command = "(i. " + target + ")"
else:
raise ValueError("Position (" + target + ") should be a positive integer!")
if representation == "surface" and closed_surface:
self._mol.cmd.create("new_entity", selection_command)
self._mol.cmd.show(representation=representation, selection="new_entity")
else:
self._mol.cmd.show(representation=representation, selection=selection_command)
elif shading_type == "range":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_range = target.split("+")
if "-" in selected_range and selected_range.count("-") == 1:
former, latter = selected_range.split("-")
if int(former) < int(latter):
selection_command = "(c. " + selected_chain + " and i. " + selected_range + ")"
else:
raise ValueError(
"The former position needs to be less than the latter position "
+ "in the Range (" + selected_range + ").")
else:
raise ValueError("Range (" + selected_range + ") needs to "
+ "meet the \"number-number\" format!")
else:
if "-" in target and target.count("-") == 1:
former, latter = target.split("-")
if int(former) < int(latter):
selection_command = "(i. " + target + ")"
else:
raise ValueError(
"The former position needs to be less than the latter position "
+ "in the Range (" + target + ").")
else:
raise ValueError(
"Range (" + target + ") needs to meet the \"number-number\" format!")
if representation == "surface" and closed_surface:
self._mol.cmd.create("new_entity", selection_command)
self._mol.cmd.show(representation=representation, selection="new_entity")
else:
self._mol.cmd.show(representation=representation, selection=selection_command)
elif shading_type == "residue":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_residue = target.split("+")
selection_command = "(c. " + selected_chain + " and r. " + selected_residue + ")"
else:
selection_command = "(r. " + target + ")"
if representation == "surface" and closed_surface:
self._mol.cmd.create("new_entity", selection_command)
self._mol.cmd.show(representation=representation, selection="new_entity")
else:
self._mol.cmd.show(representation=representation, selection=selection_command)
elif shading_type == "segment":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_segment = target.split("+")
if search(pattern=r"^[A-Z]+$", string=selected_segment):
selection_command = "(c. " + selected_chain + " and ps. " + selected_segment + ")"
else:
raise ValueError("Segment (" + selected_segment + ") should be a string "
+ "composed of uppercase letters!")
else:
if search(pattern=r"^[A-Z]+$", string=target):
selection_command = "(ps. " + target + ")"
else:
raise ValueError("Segment (" + target + ") should be a string "
+ "composed of uppercase letters!")
if representation == "surface" and closed_surface:
self._mol.cmd.create("new_entity", selection_command)
self._mol.cmd.show(representation=representation, selection="new_entity")
else:
self._mol.cmd.show(representation=representation, selection=selection_command)
elif shading_type == "chain":
for target in target_information.split(","):
if representation == "surface" and closed_surface:
self._mol.cmd.create("new_entity", "(c. " + target + ")")
self._mol.cmd.show(representation=representation, selection="new_entity")
else:
self._mol.cmd.show(representation=representation, selection="(c. " + target + ")")
elif shading_type == "model":
for target in target_information.split(","):
self._mol.cmd.show(representation=representation, selection="(m. " + target + ")")
else:
raise ValueError("No such shading type! We only support "
+ "\"position\", \"range\", \"residue\", \"segment\", \"chain\" and \"model\".")
elif representing_information == "all":
self._mol.cmd.show(representation=representation, selection="(all)")
else:
raise ValueError("No such representing information! We only support two types of information: "
+ "(1) \"all\"; and (2) \"shading type:target,target,...,target\"")
def save(self, save_path: str, width: int = 640, ratio: float = 0.75, dpi: int = 1200):
"""
Save the structure image.
:param save_path: path to save file.
:type save_path: str
:param width: width of the structure image.
:type width: int
:param ratio: the ratio of width to height.
:type ratio: float
:param dpi: dots per inch.
:type dpi: int
"""
self._mol.cmd.png(filename=save_path, width=width, height=width * ratio, dpi=dpi, quiet=1)
def save_pymol(self, save_path: str):
"""
Save the PyMOL state.
:param save_path: path to save file.
:type save_path: str
"""
self._mol.cmd.save(filename=save_path)
def load_pymol(self, load_path: str):
"""
Load the PyMOL state.
:param load_path: path to save file.
:type load_path: str
"""
self.clear()
self._mol.cmd.load(filename=load_path)
def clear(self):
"""
Clear the PyMOL.
"""
self._mol.cmd.delete("all")
def close(self):
"""
Close the PyMOL.
"""
self._mol.stop()
class HighlightStructureImage(DefaultStructureImage):
def set_color(self, coloring_plan: list, initial_color: str = "0xFFFFCC", edge_color: str = None):
"""
Set colors for the structure with the coloring plan in order.
:param coloring_plan: coloring plan for the structure.
:type coloring_plan: list
:param initial_color: initial color in the structure.
:type initial_color: str
:param edge_color: edge color of the structure if required.
:type edge_color: str or None
"""
if initial_color is not None:
self._mol.cmd.color(color=initial_color, selection="(all)")
for step, (coloring_information, color) in enumerate(coloring_plan):
if type(coloring_information) is not str:
raise ValueError("The format of coloring information at step " + str(step + 1) + " is illegal! "
+ "We only support \"str\" format!")
if ":" in coloring_information:
shading_type, target_information = coloring_information.split(":")
if shading_type == "atom":
for target in target_information.split(","):
if "+" in target:
if target.count("+") > 1:
selected_model, selected_chain, selected_atom = target.split("+")
selection_command = "(m. " + selected_model + " and c. " + selected_chain
selection_command = selection_command + " and e. " + selected_atom + ")"
else:
selected_chain, selected_atom = target.split("+")
selection_command = "(c. " + selected_chain + " and e. " + selected_atom + ")"
else:
selection_command = "(e. " + target + ")"
self._mol.cmd.color(color=color, selection=selection_command)
elif shading_type == "position":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_position = target.split("+")
if search(pattern=r"^[0-9]*[1-9][0-9]*$", string=selected_position):
selection_command = "(c. " + selected_chain + " and i. " + selected_position + ")"
else:
raise ValueError("Position (" + selected_position + ") should be a positive integer!")
else:
if search(pattern=r"^[0-9]*[1-9][0-9]*$", string=target):
selection_command = "(i. " + target + ")"
else:
raise ValueError("Position (" + target + ") should be a positive integer!")
self._mol.cmd.color(color=color, selection=selection_command)
elif shading_type == "range":
for target in target_information.split(","):
if "+" in target:
if target.count("+") > 1:
selected_model, selected_chain, selected_range = target.split("+")
if "-" in selected_range and selected_range.count("-") == 1:
former, latter = selected_range.split("-")
if int(former) < int(latter):
selection_command = "(m. " + selected_model + " and c. " + selected_chain
selection_command = selection_command + " and i. " + selected_range + ")"
else:
raise ValueError(
"The former position needs to be less than the latter position "
+ "in the Range (" + selected_range + ").")
else:
raise ValueError("Range (" + selected_range + ") needs to "
+ "meet the \"number-number\" format!")
else:
selected_chain, selected_range = target.split("+")
if "-" in selected_range and selected_range.count("-") == 1:
former, latter = selected_range.split("-")
if int(former) < int(latter):
selection_command = "(c. " + selected_chain + " and i. " + selected_range + ")"
else:
raise ValueError("The former position needs to be less than the latter position"
+ " in the Range (" + selected_range + ").")
else:
raise ValueError("Range (" + selected_range + ") needs to "
+ "meet the \"number-number\" format!")
else:
if "-" in target and target.count("-") == 1:
former, latter = target.split("-")
if int(former) < int(latter):
selection_command = "(i. " + target + ")"
else:
raise ValueError("The former position needs to be less than the latter position "
+ "in the Range (" + target + ").")
else:
raise ValueError("Range (" + target + ") needs to meet the \"number-number\" format!")
self._mol.cmd.color(color=color, selection=selection_command)
elif shading_type == "residue":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_residue = target.split("+")
selection_command = "(c. " + selected_chain + " and r. " + selected_residue + ")"
else:
selection_command = "(r. " + target + ")"
self._mol.cmd.color(color=color, selection=selection_command)
elif shading_type == "segment":
for target in target_information.split(","):
if "+" in target:
selected_chain, selected_segment = target.split("+")
if search(pattern=r"^[A-Z]+$", string=selected_segment):
selection_command = "(c. " + selected_chain + " and ps. " + selected_segment + ")"
else:
raise ValueError("Segment (" + selected_segment + ") should be a string "
+ "composed of uppercase letters!")
else:
if search(pattern=r"^[A-Z]+$", string=target):
selection_command = "(ps. " + target + ")"
else:
raise ValueError("Segment (" + target + ") should be a string "
+ "composed of uppercase letters!")
self._mol.cmd.color(color=color, selection=selection_command)