-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMolecularViewer.py
2390 lines (2147 loc) · 109 KB
/
MolecularViewer.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
# python imports
import sys
import os
import os.path
sys.path.append(os.getcwd())
import copy
import math
import time
import random
from Tkinter import *
# tool imports
import SPADE
sys.path.append('./Tools/DetectDomains')
import DetectDomains
sys.path.append('./Tools/Selection')
import SystemSelectionDialog
sys.path.append('./Tools/Aligner')
import SequenceAligner
sys.path.append('./Tools/ConservationTools')
import ConservationTools
# handle command line the lame way
homedir = '.'
from sys import argv
#if len(argv) == 2:
homedir = 'C:\Users\Dude\Desktop\SPADE'
sys.path.append(homedir)
# dependency imports
#from vtk import *
import vtk.tk.vtkTkRenderWidget
import tkFileDialog
#from vtk.tk.vtkTkRenderWindowInteractor import *
from MolecularComponents.classFutamuraHash import FutamuraHash
import vtk
# internal imports
sys.path.append(os.getcwd())
sys.path.append(os.path.join(homedir, './Dependencies'))
import Pmw
import MolecularSystem
import parms
import SystemMemory
#sys.path.append(os.path.join(homedir, './Tools/SequenceFetcher'))
#import SequenceFetcher
verbose = 0
import string
class MolecularViewer(Frame): # Molecular Viewer
def __init__(self, parent, system, ht=400, wd=500, menu=1, skip_update=1, undoredo=1):
Frame.__init__(self, parent)
self.system = system
self.parent = parent
self.undoredo_toggle = undoredo # if 1, undo/redo activated... slow but useful
self.axes_visible = 0
self.axes_actor = 'None'
self.menuBar = Pmw.MenuBar(self.parent, hull_relief = 'raised',hull_borderwidth = 4)
self.has_menu = 0
if menu == 1:
self.has_menu = 1
self._build_menu()
#self.screen = vtk.tk.vtkTkRenderWindowInteractor(parent, width=wd, height=ht)
self.screen = vtk.tk.vtkTkRenderWidget.vtkTkRenderWidget(parent, width=wd, height=ht)
win = self.screen.GetRenderWindow()
# these look interesting, but I didn't see any difference with them
#win.PointSmoothingOn()
#win.LineSmoothingOn()
#win.PolygonSmoothingOn()
# add a busy signal
self.busy_text = StringVar()
self.busy_text.set('Loading')
self.busy_label = Label(parent, textvariable=self.busy_text, width=10, height=1)
#
self.renderer = vtk.vtkRenderer()
self.renderer.GetActiveCamera().GlobalWarningDisplayOff()
self.screen.GetRenderWindow().AddRenderer(self.renderer)
self.menuBar.pack(fill='x', side='top', expand=NO)
self.screen.pack(side=TOP, expand=YES, fill=BOTH)
self.busy_label.pack(side=TOP, anchor=W, expand=NO)
start_time = time.clock()
print 'creating the view ',
self.visitor = GraphicsVisitor(None, self)
self.renderer.ResetCamera()
self.screen.Render()
#self._set_lights()
if self.undoredo_toggle:
if self.system and self.system != 'None':
self.graphics_memories = [SystemMemory.GraphicsMemory(self.system)]
self.selection_memories = [SystemMemory.SelectionMemory(self.system)]
end_time = time.clock()
self.graphics_memories = []
self.selection_memories = []
self.graphics_memory_index = 0
self.selection_memory_index = 0
self.has_icon_file = 0
print 'done creating view%5.3f seconds'%(end_time - start_time)
if self.system and self.system != 'None':
self.loadSystem(self.system, skip_update)
self.busy_text.set('Ready')
self.cb = None # codebox
self.menu_select_mode = 0
self.white_background = 0
def _set_lights(self):
cam = self.renderer.GetActiveCamera()
light_collection = self.renderer.GetLights()
light_collection.RemoveAllItems()
red_light = vtk.vtkLight()
red_light.SetColor(1.0,0.5,0.5)
red_light.SetPosition(1000,25,25)
red_light.SetFocalPoint(25,25,25)
red_light.SetIntensity(0.5)
green_light = vtk.vtkLight()
green_light.SetColor(0.5,1.0,0.5)
green_light.SetPosition(25,1000,25)
green_light.SetFocalPoint(25,25,25)
green_light.SetIntensity(0.5)
blue_light = vtk.vtkLight()
blue_light.SetColor(0.5,0.5,1.0)
blue_light.SetPosition(25,25,1000)
blue_light.SetFocalPoint(25,25,25)
blue_light.SetIntensity(0.5)
#light1.PositionalOn()
#light1.SetLightTypeToCameraLight()
#light1.SetConeAngle(20)
self.renderer.AddLight(red_light)
self.renderer.AddLight(green_light)
self.renderer.AddLight(blue_light)
#self.renderer.LightFollowCameraOn()
def close_system(self):
self.closeSystem()
def closeSystem(self):
# first remove any actors previously created
actors = self.renderer.GetActors()
cnt = actors.GetNumberOfItems()
for i in range(0,cnt):
self.renderer.RemoveActor(actors.GetLastActor())
self.renderer.ResetCamera()
self.screen.Render()
def load_system(self, system, skip_update=0):
self.loadSystem(system, skip_update)
def loadSystem(self, system, skip_update=0):
self.system = system
# first remove any actors previously created
actors = self.renderer.GetActors()
cnt = actors.GetNumberOfItems()
for i in range(0,cnt):
self.renderer.RemoveActor(actors.GetLastActor())
print 'graphics visitor'
#self.visitor = GraphicsVisitor(system, self)
self.visitor.load_system(system, 0)
print 'done visitor'
self.renderer.ResetCamera()
# if no icon has been created, create now
icon_filename = self.system.get_filename_by_extension('jpg')
if not os.path.exists(icon_filename):
self.create_icon()
# the viewer needs a memory for surfaces
self.graphics_memories = [SystemMemory.GraphicsMemory(self.system)]
self.selection_memories = [SystemMemory.SelectionMemory(self.system)]
self.graphics_memory_index = 0
self.selection_memory_index = 0
if skip_update == 0:
self.update_view()
if self.has_menu:
self.rebuild_color_menu()
def update_view(self, graphics_state=None):
if graphics_state:
graphics_state.restore_system()
start_time = time.clock()
self.busy_text.set('Busy')
self.busy_label.update()
last_selection_memory = self.selection_memories[self.selection_memory_index]
last_graphics_memory = self.graphics_memories[self.graphics_memory_index]
print 'updating the view ',
self.visitor.visit(last_selection_memory, last_graphics_memory)
if self.undoredo_toggle:
# undo/redo stuff can be disabled because of its slowness
self.graphics_memories = self.graphics_memories[:self.graphics_memory_index+1] # erase any forward memories
self.selection_memories = self.selection_memories[:self.selection_memory_index+1]
new_graphics_memory = SystemMemory.GraphicsMemory(self.system)
new_selection_memory = SystemMemory.SelectionMemory(self.system)
self.graphics_memories.append(new_graphics_memory)
self.selection_memories.append(new_selection_memory)
self.graphics_memory_index += 1
self.selection_memory_index += 1
self.screen.Render()
end_time = time.clock()
print 'done %5.3f seconds'%(end_time - start_time)
self.busy_text.set('Ready')
self.busy_label.update()
def restore_initial_graphics_state(self):
self.undo(1)
def undo(self, load_initial=0):
if self.graphics_memory_index == 0:
print 'out of do\'s to undo'
return
else:
# don't erase the first memory -- that's the initial state
if load_initial==1:
self.graphics_memory_index=1
self.selection_memory_index=1
# save the current graphic and selection images
current_graphics_snap = SystemMemory.GraphicsMemory(self.system)
current_selection_snap = SystemMemory.SelectionMemory(self.system)
# select all of the molecular objects so that the graphics image is right
SystemMemory.ObjectSelectionVisitor(self.system)
# restore the last graphics image
reload_graphics_memory = self.graphics_memories[self.graphics_memory_index-1]
reload_graphics_memory.restore_system()
reload_selection_memory = self.selection_memories[self.selection_memory_index-1]
reload_selection_memory.restore_system()
self.visitor.visit(current_selection_snap, current_graphics_snap)
self.graphics_memory_index -= 1
self.selection_memory_index -= 1
self.screen.Render()
def redo(self):
if len(self.graphics_memories) > self.graphics_memory_index+1:
current_graphics_snap = SystemMemory.GraphicsMemory(self.system)
current_selection_snap = SystemMemory.SelectionMemory(self.system)
reload_graphics_memory = self.graphics_memories[self.graphics_memory_index + 1]
reload_selection_memory = self.selection_memories[self.selection_memory_index + 1]
reload_graphics_memory.restore_system()
reload_selection_memory.restore_system()
self.visitor.visit(current_selection_snap, current_graphics_snap)
self.graphics_memory_index += 1
self.selection_memory_index += 1
self.screen.Render()
def _build_menu(self):
self.menuBar.addmenu('Viewer', 'Viewer Controls')
self.menuBar.addmenuitem('Viewer', 'command', 'Undo', command=self.undo, label='Undo')
self.menuBar.addmenuitem('Viewer', 'command', 'Redo', command=self.redo, label='Redo')
c_lambda = lambda: self.undo(1)
self.menuBar.addmenuitem('Viewer', 'command', 'Restore Initial Memory', command=c_lambda, label='Restore Initial Memory')
self.menuBar.addmenuitem('Viewer', 'command', 'Save Image', command=self.save_image, label='Save Image')
self.menuBar.addmenuitem('Viewer', 'command', 'Toggle Axes', command=self.toggle_axes, label='View Axes')
self.menuBar.addmenuitem('Viewer', 'command', 'Update View', command=self.update_view, label='Update View')
self.menuBar.addmenuitem('Viewer', 'command', 'Update Icon', command=self.create_icon, label='Update Icon')
self.menuBar.addmenuitem('Viewer', 'command', 'Toggle Prompt', command=self.toggle_codebox, label='Toggle Prompt')
self.menuBar.addmenuitem('Viewer', 'command', 'Toggle Undo/Redo Ability', command=self.toggle_undoredo, label='Toggle Undo/Redo Ability')
self.menuBar.addmenuitem('Viewer', 'command', 'Toggle Background', command=self.toggle_background, label='Toggle Background')
self.menuBar.addmenuitem('Viewer', 'command', 'Toggle Hydrogens', command=self.toggle_hydrogens, label='Toggle Hydrogens')
self.menuBar.addmenu('Calculate', 'Calculate Features')
self.menuBar.addmenuitem('Calculate', 'command', 'Calculate Accessibility', command=self.calculate_accessibility, label='Calculate SA')
self.menuBar.addmenuitem('Calculate', 'command', 'Calculate Shielding', command=self.calculate_shielding, label='Calculate Shielding')
self.menuBar.addmenuitem('Calculate', 'command', 'Calculate Atomic Densities', command=self.calculate_atomic_densities, label='Calculate Atomic Densities')
self.menuBar.addmenuitem('Calculate', 'command', 'Calculate Domains', command=self.calculate_domains, label='Calculate Domains')
self.menuBar.addmenuitem('Calculate', 'command', 'Calculate Conservation', command=self.calculate_conservation, label='Calculate Conservation')
self.menuBar.addmenuitem('Calculate', 'command', 'Calculate Interface Stats', command=self.calculate_interface_statistics, label='Calculate Interface Stats')
self.menuBar.addmenu('Display', 'Change display')
self.menuBar.addmenuitem('Display', 'command', 'toggle select mode', command=self.toggle_menu_select_mode, label='toggle select mode')
self.menuBar.addcascademenu('Display', 'Display Atoms')
c_lambda = lambda: self.display('atoms', 1)
self.menuBar.addmenuitem('Display Atoms','command','Atoms display on', command=c_lambda, label='on')
c_lambda = lambda: self.display('atoms', 0)
self.menuBar.addmenuitem('Display Atoms','command','Atoms display off', command=c_lambda, label='off')
self.menuBar.addcascademenu('Display', 'Display Trace')
c_lambda = lambda: self.display('trace', 1)
self.menuBar.addmenuitem('Display Trace','command','Trace display on', command=c_lambda, label='on')
c_lambda = lambda: self.display('trace', 0)
self.menuBar.addmenuitem('Display Trace','command','Trace display off', command=c_lambda, label='off')
self.menuBar.addcascademenu('Display', 'Display Volumes')
c_lambda = lambda: self.display('volume', 1)
self.menuBar.addmenuitem('Display Volumes','command','Volumes display on', command=c_lambda, label='on')
c_lambda = lambda: self.display('volume', 0)
self.menuBar.addmenuitem('Display Volumes','command','Volumes display off', command=c_lambda, label='off')
self.menuBar.addcascademenu('Display', 'Display HBonds')
c_lambda = lambda: self.display('hbonds', 1)
self.menuBar.addmenuitem('Display HBonds','command','Hbonds display on', command=c_lambda, label='on')
c_lambda = lambda: self.display('hbonds', 0)
self.menuBar.addmenuitem('Display HBonds','command','Hbonds display off', command=c_lambda, label='off')
self.menuBar.addmenu('Color', 'Apply coloring scheme')
self._add_color_menu()
self.menuBar.addmenu('Options', 'Change Options')
self.menuBar.addmenuitem('Options', 'command', 'toggle select mode', command=self.toggle_menu_select_mode, label='toggle select mode')
self.menuBar.addcascademenu('Options', 'Atoms Options')
self.menuBar.addmenuitem('Atoms Options', 'command', 'Show wireframe representation', command=self.represent_atoms_as_wireframe, label='wireframe')
self.menuBar.addmenuitem('Atoms Options', 'command', 'Show sticks representation', command=self.represent_atoms_as_sticks, label='sticks')
self.menuBar.addmenuitem('Atoms Options', 'command', 'Show sphere representation', command=self.represent_atoms_as_spheres, label='spheres')
self.menuBar.addcascademenu('Options', 'Trace Options')
self.menuBar.addmenuitem('Trace Options', 'command', 'Show line representation', command=self.represent_trace_as_line, label='line')
self.menuBar.addmenuitem('Trace Options', 'command', 'Show tube representation', command=self.represent_trace_as_tube, label='tube')
self.menuBar.addmenuitem('Trace Options', 'command', 'Toggle trace transparency', command=self.toggle_trace_transparency, label='transparency')
self.menuBar.addcascademenu('Options', 'Volume Options')
self.menuBar.addmenuitem('Volume Options', 'command', 'Show surface representation', command=self.represent_volumes_as_surface, label='surface')
self.menuBar.addmenuitem('Volume Options', 'command', 'Show wireframe representation', command=self.represent_volumes_as_wireframe, label='wireframe')
self.menuBar.addmenuitem('Volume Options', 'command', 'Show points representation', command=self.represent_volumes_as_points, label='points')
self.menuBar.addmenuitem('Volume Options', 'command', 'Toggle volume transparency', command=self.toggle_volume_transparency, label='transparency')
self.menuBar.addcascademenu('Options', 'H Bond Options')
self.menuBar.addmenuitem('H Bond Options', 'command', 'Show lines representation', command=self.represent_hbonds_as_lines, label='lines')
self.menuBar.addmenuitem('H Bond Options', 'command', 'Show tubes representation', command=self.represent_hbonds_as_tubes, label='tubes')
def toggle_hydrogens(self):
self.visitor.toggle_hydrogens()
viewer.update_view()
def toggle_background(self):
if self.white_background:
self.renderer.SetBackground([0.0,0.0,0.0])
else:
self.renderer.SetBackground([1.0,1.0,1.0])
def toggle_menu_select_mode(self):
if self.menu_select_mode:
self.menu_select_mode=0
else:
self.menu_select_mode=1
def toggle_trace_transparency(self):
# define a function to pass to the selection dialog
def exit_function(viewer, parms, top=None, snap=None):
print 'executing exit function'
for pchain in viewer.system.ProteinList:
for res in pchain.residues:
if res.selected:
print 'res %s %s selected for opacity'%(res.res_type1, res.res_number)
res.vtk_arg_list['trace']['opacity'] = 0.2
else:
res.vtk_arg_list['trace']['opacity'] = 1.0
graphics_state = SystemMemory.GraphicsMemory(viewer.system)
viewer.update_view(graphics_state)
if snap:
#snap.restore_system()
top.destroy()
if self.menu_select_mode:
# create a selection dialog to handle selection for transparency
for pol in self.system.PolymerList:
for res in pol.residues:
res.deselect()
for pol in self.system.PolymerList:
for res in pol.residues:
if res.vtk_arg_list['trace']['opacity'] < 1.0:
print 'opaque residue %s'%(res.res_number)
res.select()
selection_top = Toplevel()
geometry_string = "%dx%d%+d%+d" %(440,300,1,220) # width,height,x-offset,y-offset
selection_top.geometry(geometry_string)
selection_top.title('Select to toggle transparency')
selection_top.wm_transient(self.parent) # transient to the System window
current_selection_snap = SystemMemory.SelectionMemory(self.system)
c_lambda = lambda v=self, p=parms, t=selection_top, s=current_selection_snap:exit_function(v, p, t, s)
selection_dialog = SystemSelectionDialog.SystemSelectionDialog(self,
selection_top,
self.system,
0,
[],
0,
c_lambda)
selection_dialog.pack(expand='yes', fill='both')
else:
for pchain in self.system.ProteinList:
for res in pchain.residues:
if res.vtk_arg_list['trace']['opacity'] == 1.0:
res.vtk_arg_list['trace']['opacity'] = 0.2
else:
res.vtk_arg_list['trace']['opacity'] = 1.0
self.update_view()
def toggle_volume_transparency(self):
# define a function to pass to the selection dialog
def exit_function(viewer, parms, top=None, snap=None):
print 'executing exit function'
for pchain in viewer.system.ProteinList:
for atom in pchain.atoms:
if atom.selected:
print 'atom %s %s selected for opacity'%(atom.atom_type, atom.atom_number)
atom.vtk_arg_list['volume']['opacity'] = 0.1
else:
atom.vtk_arg_list['volume']['opacity'] = 1.0
graphics_state = SystemMemory.GraphicsMemory(viewer.system)
viewer.update_view(graphics_state)
if snap:
#snap.restore_system()
top.destroy()
if self.menu_select_mode:
# create a selection dialog to handle selection for transparency
for pol in self.system.PolymerList:
for atom in pol.atoms:
atom.deselect()
for pol in self.system.PolymerList:
for atom in pol.atoms:
if atom.vtk_arg_list['volume']['opacity'] < 1.0:
print 'opaque atom %s'%(atom.atom_number)
atom.select()
selection_top = Toplevel()
geometry_string = "%dx%d%+d%+d" %(440,300,1,220) # width,height,x-offset,y-offset
selection_top.geometry(geometry_string)
selection_top.title('Select to toggle transparency')
selection_top.wm_transient(self.parent) # transient to the System window
current_selection_snap = SystemMemory.SelectionMemory(self.system)
c_lambda = lambda v=self, p=parms, t=selection_top, s=current_selection_snap:exit_function(v, p, t, s)
selection_dialog = SystemSelectionDialog.SystemSelectionDialog(self,
selection_top,
self.system,
0,
[],
0,
c_lambda)
selection_dialog.pack(expand='yes', fill='both')
else:
for pchain in self.system.ProteinList:
for atom in pchain.atoms:
if atom.vtk_arg_list['volume']['opacity'] == 1.0:
atom.vtk_arg_list['volume']['opacity'] = 0.1
else:
atom.vtk_arg_list['volume']['opacity'] = 1.0
self.update_view()
def toggle_codebox(self):
if self.cb == None:
self.cb = SPADE.CodeBox(self.parent, self.system, self)
sys.stdout = self.cb
sys.stderr = self.cb
else:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
self.cb.destroy()
self.cb = None
def rebuild_color_menu(self):
self.menuBar.deletemenu('Color Atoms')
self.menuBar.deletemenu('Color Trace')
self.menuBar.deletemenu('Color Volumes')
self._add_color_menu()
def _add_color_menu(self):
""" Automatically color by value
All residues or atoms in each protein need to have the value. The value should
be a digit. If not normalized, a new feature will be added which appends '_normalized'
to the key """
print 'adding color menu'
self.menuBar.addcascademenu('Color', 'Color Atoms');
c_lambda = lambda: self.color_wireframe('cpk');
self.menuBar.addmenuitem('Color Atoms','command','Color wireframes cpk', command=c_lambda, label='cpk')
c_lambda = lambda: self.color_wireframe('type');
self.menuBar.addmenuitem('Color Atoms','command','Color wireframes by type', command=c_lambda, label='type')
c_lambda = lambda: self.color_wireframe('chain');
self.menuBar.addmenuitem('Color Atoms','command','color wireframes by chain', command=c_lambda, label='chain')
c_lambda = lambda: self.color_wireframe('hydrogen_type');
self.menuBar.addmenuitem('Color Atoms','command','color wireframes by H type', command=c_lambda, label='H Type')
self.menuBar.addcascademenu('Color', 'Color Trace')
self.menuBar.addmenuitem('Color Trace','command','Color tubes by secondary', command=self.color_trace_by_secondary,label='secondary')
self.menuBar.addmenuitem('Color Trace','command','Color tubes by type', command=self.color_tubes_type,label='type')
self.menuBar.addmenuitem('Color Trace','command','Color tubes by chain', command=self.color_tubes_chain,label='chain')
self.menuBar.addcascademenu('Color', 'Color Volumes')
self.menuBar.addmenuitem('Color Volumes','command','Color volumes cpk', command=self.color_volumes_cpk,label='cpk')
self.menuBar.addmenuitem('Color Volumes','command','Color volumes by type', command=self.color_volumes_type,label='type')
self.menuBar.addmenuitem('Color Volumes','command','Color volumes by chain', command=self.color_volumes_chain,label='chain')
# create menu items for .features keys for atoms and residues
if self.system != 'None' and self.system != None:
key_store = {}
key_store['atom'] = self.system.ProteinList[0].atoms[0].features.keys()
key_store['residue'] = self.system.ProteinList[0].residues[0].features.keys()
for run_type in ['atom', 'residue']:
broken = 0
for key in key_store[run_type]:
for pol in self.system.ProteinList:
if key == 'domain':
self.print_domain_info(pol)
normalized = 1
# if the feature includes non-digits, pass. if it is all digits, see if
# it is normalized
if run_type == 'atom':
item_list = pol.atoms
elif run_type == 'residue':
item_list = pol.residues
same_val_count = 0
try:
item_list[0].features[key]
except KeyError:
continue
else:
first_val = item_list[0].features[key]
for item in item_list:
try:
feature = item.features[key]
except KeyError:
print 'key error on %s, breaking'%(key)
broken = 1
break
try:
int(feature)
except ValueError:
print '%s not digit, breaking'%(feature)
broken = 1
break
else:
if feature != -1 and (feature < 0.0 or feature > 1.0):
normalized = 0
if feature == first_val:
same_val_count += 1
if same_val_count == len(item_list):
print '%s all the same value; breaking'%(key)
broken = 1
break
if key == 'domain':
if item.features[key] == 0.0:
item.features[key] = -1
else:
# if not normalized, make a new key called key+'_normalized', and swap the old
# key with the new key to color by it
old_key = copy.copy(key)
if not normalized and (key+'_normalized' not in item.features.keys()):
min_f = 1000000
max_f = -1000000
for item2 in item_list:
feature = item2.features[key]
if feature != -1:
if feature < min_f:
min_f = feature
if feature > max_f:
max_f = feature
key = key + '_normalized'
for item2 in item_list:
if item2.features[old_key] != -1.0:
d = (item2.features[old_key]-min_f) / (max_f-min_f+0.0)
item2.features[key] = d
else:
item2.features[key] = -1.0
if run_type == 'residue':
c_lambda1 = lambda p=pol, k=key: self.color_trace_by_residue_feature(p, k)
self.menuBar.addmenuitem('Color Trace','command','Color trace by res '+key, command=c_lambda1, label='%s %s'%(pol.chain_name, key))
c_lambda2 = lambda p=pol, k=key: self.color_volume_by_residue_feature(p, k)
self.menuBar.addmenuitem('Color Volumes','command','Color volumes by res '+key, command=c_lambda2, label='%s %s'%(pol.chain_name, key))
c_lambda3 = lambda p=pol, k=key: self.color_atoms_by_residue_feature(p, k)
self.menuBar.addmenuitem('Color Atoms','command','Color atoms by res '+key, command=c_lambda3, label='%s %s'%(pol.chain_name, key))
elif run_type == 'atom':
c_lambda1 = lambda p=pol, k=key: self.color_trace_by_atom_feature(p, k)
self.menuBar.addmenuitem('Color Trace','command','Color trace by atom '+key, command=c_lambda1, label='%s %s'%(pol.chain_name, key))
c_lambda2 = lambda p=pol, k=key: self.color_volume_by_atom_feature(p, k)
self.menuBar.addmenuitem('Color Volumes','command','Color volumes by atom '+key, command=c_lambda2, label='%s %s'%(pol.chain_name, key))
c_lambda3 = lambda p=pol, k=key: self.color_atoms_by_atom_feature(p, k)
self.menuBar.addmenuitem('Color Atoms','command','Color atoms by atom '+key, command=c_lambda3, label='%s %s'%(pol.chain_name, key))
key = old_key
#broken = 1
#break
if broken:
break
def print_domain_info(self, pchain):
last_domain = -2
domains = []
starts = []
ends = []
last_res_number = -1
for res in pchain.residues:
domain = res.features['domain']
if domain > 0:
if domain != last_domain:
starts.append(res.res_number)
if last_res_number != -1:
ends.append(last_res_number)
domains.append(domain)
last_res_number = res.res_number
last_domain = domain
ends.append(len(pchain.residues))
if len(domains) > 1:
print 'chain %s has %s domains'%(pchain.chain_name, len(domains))
else:
print 'chain %s has 1 domain'%(pchain.chain_name)
for i in range(len(domains)):
print 'd%s %s - %s'%(domains[i], starts[i], ends[i])
def toggle_undoredo(self):
if self.undoredo_toggle:
self.undoredo_toggle = 0
else:
self.undoredo_toggle = 1
def draw_label(self, text, x, y, z):
pass
def color_atoms_by_atom_feature(self, pol, feature):
for atom in pol.atoms:
if atom.features[feature] == -1:
color = [1.0,0.0,0.0]
else:
color = [0.0+atom.features[feature], 0.0+atom.features[feature], 1.0]
atom.vtk_arg_list['atoms']['color'] = color
self.update_view()
def color_trace_by_atom_feature(self, pol, feature):
averages_list = []
for res in pol.residues:
sum_feature = 0.0
num = 0.0
for atom in res.atoms:
if atom.features[feature] == -1:
continue
else:
sum_feature += atom.features[feature]
num += len(res.atoms)
averages_list.append(sum_feature/num)
# normalize
maxval = 0.0
minval = 100000.0
for avg in averages_list:
if avg > maxval:
maxval = avg
if avg < minval:
minval = avg
for ind in range(len(pol.residues)):
val = (averages_list[ind] - minval)/(maxval - minval)
color = [0.0+(val), 0.0+(val), 1.0]
pol.residues[ind].vtk_arg_list['trace']['color'] = color
self.update_view()
def color_volume_by_atom_feature(self, pol, feature):
for atom in pol.atoms:
if atom.features[feature] == -1:
color = [1.0,0.0,0.0]
else:
color = [0.0+atom.features[feature], 0.0+atom.features[feature], 1.0]
atom.vtk_arg_list['volume']['color'] = color
self.update_view()
def color_atoms_by_residue_feature(self, pol, feature):
for res in pol.residues:
if res.features[feature] == -1:
color = [1.0,0.0,0.0]
else:
color = [0.0+res.features[feature], 0.0+res.features[feature], 1.0]
for atom in res.atoms:
atom.vtk_arg_list['atoms']['color'] = color
self.update_view()
def color_trace_by_residue_feature(self, pol, feature):
for res in pol.residues:
if res.features[feature] == -1:
color = [1.0,0.0,0.0]
else:
color = [0.0+res.features[feature], 0.0+res.features[feature], 1.0]
res.vtk_arg_list['trace']['color'] = color
self.update_view()
def color_volume_by_residue_feature(self, pol, feature):
for res in pol.residues:
if res.features[feature] == -1:
color = [1.0,0.0,0.0]
else:
color = [0.0+res.features[feature], 0.0+res.features[feature], 1.0]
for atom in res.atoms:
atom.vtk_arg_list['volume']['color'] = color
self.update_view()
def color_wireframe(self, style):
if style == 'hydrogen_type':
if len(self.system.HBonds) == 0:
self.system.create_hbonds(None, None, True)
chain_colors = parms.get('atom_color_list')
if style == 'cpk' or style == 'type' or style == 'hydrogen_type':
for mol in self.system.MoleculeList:
if mol.selected:
for atom in mol.atoms:
atom.vtk_arg_list['atoms']['color'] = self.visitor.get_atom_color(atom, style)
elif style == 'chain':
for mol in self.system.MoleculeList:
if mol.selected:
color = self.visitor.get_atom_color(mol.atoms[0], 'chain')
for atom in mol.atoms:
atom.vtk_arg_list['atoms']['color'] = color
self.update_view()
def color_tubes_type(self):
for pchain in self.system.ProteinList:
for res in pchain.residues:
res.vtk_arg_list['trace']['color'] = self.visitor.get_residue_color(res, 'type')
self.update_view()
def color_trace_by_secondary(self):
for pchain in self.system.ProteinList:
# first make sure secondary is assigned
for res in pchain.residues:
try:
res.features['secondary']
except KeyError:
pchain.assign_ss()
break
for res in pchain.residues:
if res.features['secondary'] == 'A':
res.vtk_arg_list['trace']['color'] = [1.0,0.1,0.1]
elif res.features['secondary'] == 'B':
res.vtk_arg_list['trace']['color'] = [0.1,0.1,1.0]
elif res.features['secondary'] == 'C':
res.vtk_arg_list['trace']['color'] = [0.8,0.8,0.8]
self.update_view()
def color_tubes_chain(self):
for pchain in self.system.ProteinList:
color = self.visitor.get_residue_color(pchain.residues[0], 'chain')
for res in pchain.residues:
res.vtk_arg_list['trace']['color'] = color
for nchain in self.system.NucleotideChainList:
color = self.visitor.get_residue_color(nchain.residues[0], 'chain')
for res in nchain.residues:
res.vtk_arg_list['trace']['color'] = color
self.update_view()
def color_volumes_chain(self):
for pol in self.system.PolymerList:
for atom in pol.atoms:
atom.vtk_arg_list['volume']['color'] = self.visitor.get_atom_color(atom, 'chain')
self.update_view()
def color_volumes_type(self):
for pol in self.system.PolymerList:
for atom in pol.atoms:
atom.vtk_arg_list['volume']['color'] = self.visitor.get_atom_color(atom, 'volume_type')
self.update_view()
def color_volumes_cpk(self):
for pol in self.system.PolymerList:
for atom in pol.atoms:
atom.vtk_arg_list['volume']['color'] = self.visitor.get_atom_color(atom, 'cpk')
self.update_view()
def display(self, type, onoff):
# define a function to pass to the selection dialog
def exit_function(viewer, parms, top=None, snap=None):
print 'executing exit function'
listdict = {'system':self.system,
'trace':self.system.PolymerList,
'atoms':self.system.MoleculeList,
'volume':self.system.MoleculeList}
for x in listdict[type]:
if x.selected:
x.vtk_arg_list[type]['visualize'] = onoff
graphics_state = SystemMemory.GraphicsMemory(viewer.system)
viewer.update_view(graphics_state)
if snap:
snap.restore_system()
top.destroy()
listdict = {'system':self.system,
'trace':self.system.PolymerList,
'atoms':self.system.MoleculeList,
'volume':self.system.MoleculeList}
if self.menu_select_mode:
# create a selection dialog to handle selection for transparency
current_selection_snap = SystemMemory.SelectionMemory(self.system)
for x in listdict[type]:
x.deselect()
for x in listdict[type]:
if x.vtk_arg_list[type]['visualize'] == 1.0:
x.select()
selection_top = Toplevel()
geometry_string = "%dx%d%+d%+d" %(440,300,1,220) # width,height,x-offset,y-offset
selection_top.geometry(geometry_string)
selection_top.title('Select to toggle %s display'%(type))
selection_top.wm_transient(self.parent) # transient to the System window
c_lambda = lambda v=self, p=parms, t=selection_top, s=current_selection_snap:exit_function(v, p, t, s)
selection_dialog = SystemSelectionDialog.SystemSelectionDialog(self,
selection_top,
self.system,
0,
[],
0,
c_lambda)
selection_dialog.pack(expand='yes', fill='both')
else:
listdict = {'hbonds':self.system,
'trace':self.system.PolymerList,
'atoms':self.system.MoleculeList,
'volume':self.system.MoleculeList}
if type == 'hbonds':
if len(self.system.HBonds) == 0:
self.system.create_hbonds(None, None, True)
self.system.vtk_arg_list[type]['visualize'] = onoff
else:
for x in listdict[type]:
if x.selected:
x.vtk_arg_list[type]['visualize'] = onoff
self.update_view()
def represent_hbonds_as_lines(self):
# caluclate hbonds if nec.
if len(self.system.HBonds) == 0:
self.system.create_hbonds(None, None, True)
if self.system.selected:
self.system.vtk_arg_list['hbonds']['representation'] = 'lines'
self.update_view()
def represent_hbonds_as_tubes(self):
# calculate hbonds if nec.
if len(self.system.HBonds) == 0:
self.system.create_hbonds(None, None, True)
if self.system.selected:
self.system.vtk_arg_list['hbonds']['representation'] = 'tubes'
self.update_view()
def represent_atoms_as_wireframe(self):
for mol in self.system.MoleculeList:
if mol.selected:
mol.vtk_arg_list['atoms']['representation'] = 'wireframe'
self.update_view()
def represent_atoms_as_sticks(self):
for mol in self.system.MoleculeList:
if mol.selected:
mol.vtk_arg_list['atoms']['representation'] = 'sticks'
self.update_view()
def represent_atoms_as_spheres(self):
for mol in self.system.MoleculeList:
if mol.selected:
mol.vtk_arg_list['atoms']['representation'] = 'spheres'
self.update_view()
def represent_trace_as_line(self):
for mol in self.system.PolymerList:
if mol.selected:
mol.vtk_arg_list['trace']['representation'] = 'line'
self.update_view()
def represent_trace_as_tube(self):
for mol in self.system.PolymerList:
if mol.selected:
mol.vtk_arg_list['trace']['representation'] = 'tube'
self.update_view()
def represent_trace_as_ribbon(self):
for mol in self.system.PolymerList:
if mol.selected:
mol.vtk_arg_list['trace']['representation'] = 'ribbon'
self.update_view()
def represent_volumes_as_surface(self):
for mol in self.system.MoleculeList:
if mol.selected:
mol.vtk_arg_list['volume']['representation'] = 'surface'
self.update_view()
def represent_volumes_as_wireframe(self):
for mol in self.system.MoleculeList:
if mol.selected:
mol.vtk_arg_list['volume']['representation'] = 'wireframe'
self.update_view()
def represent_volumes_as_points(self):
for mol in self.system.MoleculeList:
if mol.selected:
mol.vtk_arg_list['volume']['representation'] = 'points'
self.update_view()
def save_image(self):
strg = tkFileDialog.asksaveasfilename(title = 'Save as', defaultextension='.jpg', filetypes=[("JPEG", "*.jpg"),
("PostScript", "*.ps"),
("PNG", "*.png"),
("BMP", "*.bmp"),
("TIFF", "*.tif"),
("all files", "*")])
if len(strg) > 0:
tokens = string.split(strg, '.')
if tokens[-1] == "jpg":
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(self.screen.GetRenderWindow())
writer = vtk.vtkJPEGWriter()
writer.SetInput(w2i.GetOutput())
writer.SetFileName(strg)
writer.Write()
def toggle_axes(self):
if self.axes_visible == 0:
# first figure out what the bounds are; ignore waters
bounds = self.system.get_bounds()
if self.axes_actor == 'None':
self.axes_actor = vtk.vtkCubeAxesActor2D()
self.axes_actor.SetCamera(self.renderer.GetActiveCamera())
self.renderer.AddActor(self.axes_actor)
self.axes_actor.SetFlyMode(0)
self.axes_actor.SetInertia(10)
self.axes_actor.SetNumberOfLabels(5)
self.axes_actor.ScalingOff()
self.axes_actor.GetProperty().SetColor([0.2,1.0,0.2])
self.axes_actor.GetProperty().SetOpacity(0.6)
self.axes_actor.SetBounds(bounds[0],bounds[1],bounds[2],bounds[3],bounds[4],bounds[5])
self.axes_visible = 1
self.axes_actor.XAxisVisibilityOn()
self.axes_actor.YAxisVisibilityOn()
self.axes_actor.ZAxisVisibilityOn()
else:
self.axes_visible = 0
self.axes_actor.XAxisVisibilityOff()
self.axes_actor.YAxisVisibilityOff()
self.axes_actor.ZAxisVisibilityOff()
self.screen.Render()
def create_icon(self):
icon_filename = self.system.get_filename_by_extension('jpg')
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(self.screen.GetRenderWindow())
writer = vtk.vtkJPEGWriter()
writer.SetInput(w2i.GetOutput())
writer.SetFileName(icon_filename)
writer.Write()
def calculate_accessibility(self):
# i dont see any use in calculating this for nucleotide chains or small molecules,
# but similar code will apply
self.system.calculate_differential_system_asa(1.4, 1000)
self.rebuild_color_menu()
def calculate_interface_statistics(self):
ConservationTools.calculate_conservation(self.system, 'sidechain_asa')
self.system.calculate_interface_significance('sidechain_asa')
#a = SequenceAligner.SequenceAligner(0, 'local')
#a.add_target(self.system.ProteinList[0])
#a.add_template(self.system.ProteinList[1])
#pid = a.align_sequences()
#print '%5.3f percent identity between chains %s and %s'%(pid, self.system.ProteinList[0].chain_name, self.system.ProteinList[1].chain_name)
self.rebuild_color_menu()
def calculate_shielding(self):
for pchain in self.system.ProteinList:
pchain.fill_pseudo_sidechains()
pchain.fill_neighbors_lists()
self.rebuild_color_menu()
def calculate_atomic_densities(self):
for pchain in self.system.ProteinList:
pchain.fill_densities()
self.rebuild_color_menu()
def calculate_domains(self):
#fetcher = SequenceFetcher.SequenceFetcher(self.system)
#fetcher.fetch()
#fetcher.normalize_domain_labels()
for pchain in self.system.ProteinList:
DetectDomains.auto_decompose(pchain, self)
self.rebuild_color_menu()
def calculate_conservation(self):
""" currently designed to read Molnir .msq files,
through the Protein object's calculate_conservation function
"""
for pchain in self.system.ProteinList:
ConservationTools.fetch_msq_conservation(pchain)
ConservationTools.calculate_conservation(self.system)
self.rebuild_color_menu()
class GraphicsVisitor:
""" GraphicsVisitor visits the structure, using vtk to create actors """
def __init__(self, system, parent):
self.renderer = parent.renderer
self.screen = parent.screen
self.parent = parent
self.polymer_actors = {} # append lists of atom_actors, one for each chain
self.small_molecule_actors = {}
self.polymer_splines = {}
self.system = system
self.hydrogens_on = 0
if system != 'None' and system != None:
self.load_system(system, 1)
""" System tools: load, visits """
def toggle_hydrogens(self):
if self.hydrogens_on:
self.hydrogens_on = 0
else:
self.hydrogens_on = 1