-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlightGridCommands.py
3131 lines (2862 loc) · 135 KB
/
lightGridCommands.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
"""
Copyright (C) <2010> Autin L.
This file ePMV_git/lightGridCommands.py is part of ePMV.
ePMV 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.
ePMV 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 ePMV. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>.
"""
# -*- coding: utf-8 -*-
"""
Created on Mon May 17 22:53:21 2010
@author: -
"""
########################################################################
#
# Authors: Sargis Dallakyan, Michel Sanner
#
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: Sargis Dallakyan, Michel Sanner and TSRI
#
#########################################################################
#
# $Header: /opt/cvs/python/packages/share1.5/Pmv/hostappInterface/lightGridCommands.py,v 1.4 2010/07/22 18:16:09 autin Exp $
# $Id: lightGridCommands.py,v 1.4 2010/07/22 18:16:09 autin Exp $
"""This module integrates Volume.Grid3D with ViewerFramework for rendering 3D Grids.
It includes Add/Remove, Isocontour, OrthoSlice and VolRender commands, and a
table widget for navigating between grids.
See http://mgltools.scripps.edu/documentation/tutorial/volume-rendering for more info.
"""
import sys
import re, types, os, math, pickle
try :
import tkinter
import tkinter.filedialog
import tkinter.messagebox
from tkinter.colorchooser import askcolor
except :
import Tkinter as tkinter
import tkFileDialog
tkinter.filedialog = tkFileDialog
import tkMessageBox
tkinter.messagebox = tkMessageBox
#import Pmw
Pmw = None
#from PIL import Image, ImageTk
from PIL import Image
from PIL import ImageTk
from DejaVu.Geom import Geom
from ViewerFramework.VFCommand import Command, CommandGUI
from mglutil.gui import widgetsOnBackWindowsCanGrabFocus
#from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser
from mglutil.gui.InputForm.Tk.gui import InputFormDescr, InputForm
#from mglutil.gui.BasicWidgets.Tk.multiListbox import MultiListbox
from mglutil.util.misc import ensureFontCase
from Volume.IO.volReaders import ReadMRC, ReadCCP4, ReadCNS, ReadGRD, ReadBRIX,\
ReadSPIDER, ReadRawiv, ReadEM, ReadFLDBinary
from Volume.IO.volWriters import WriteCCP4
from Volume.IO.UHBDGridReader import UHBDReaderASCII
from Volume.IO.DelphiReader import DelphiReaderBin
from Volume.IO.dxReader import ReadDX
from Volume.IO.AutoGridReader import ReadAutoGrid
from Volume.IO.gamessOrbitalsReader import ReadGamessOrbitals
from Volume.Grid3D import Grid3D, Grid3DD, Grid3DF, Grid3DI, \
Grid3DSI, Grid3DUI, Grid3DUSI, Grid3DUC, ArrayTypeToGrid, GridTypeToArray
#from Volume.Renderers.UTVolumeLibrary.DejaVu.UTVolRenGeom import UTVolRenGeom
UTVolRenGeom = None
#thi was broking maya
from mglutil.util.packageFilePath import findFilePath
from DejaVu.extendedSlider import ExtendedSlider
try:
from UTpackages.UTisocontour import isocontour
isocontour.setVerboseLevel(0)
except ImportError:
isocontour = None
from DejaVu.IndexedPolygons import IndexedPolygons
from DejaVu.Box import Box
from DejaVu.Textured2DArray import textured2DArray
import numpy.oldnumeric as Numeric
import numpy
from DejaVu.colorMap import ColorMap
#from DejaVu.ColormapGui import ColorMapGUI
from opengltk.OpenGL import GL
from Pmv.moleculeViewer import DeleteGeomsEvent, AddGeomsEvent, EditGeomsEvent
def getSupportedFormat():
return '\.mrc$|\.MRC$|\.cns$|\.xplo*r*$|\.ccp4*$|\.grd$|\.fld$|\.map$|\.omap$|\.brix$|\.dsn6$|\.dn6$|\.rawiv$|\.d*e*l*phi$|\.uhbd$|\.dx$|\.spi$'
ICONPATH = findFilePath('Icons', 'ViewerFramework')
Grid_ICONPATH = os.path.join(ICONPATH, 'Grid3D')
if sys.platform == 'darwin':
rightClick = "Apple-Click"
else:
rightClick = "Right-Click"
def get_icon(icon, master):
iconfile = os.path.join(Grid_ICONPATH, icon)
head, ext = os.path.splitext(iconfile)
if ext == '.gif':
if master is None:
Icon = tkinter.PhotoImage(file=iconfile)
else:
Icon = tkinter.PhotoImage(file=iconfile, master=master)
else:
image = Image.open(iconfile)
if master is None:
Icon = ImageTk.PhotoImage(image=image)
else:
Icon = ImageTk.PhotoImage(image=image, master=master)
return Icon
class addGridCommand(Command):
"""
\nPackage : ViewerFramework
\nModule : grid3DCommands
\nClass : addGridCommand
\nCommand : addGrid
\ndoit(self, grid3D, name=None):\n
"""
def doit(self, grid3D, name=None):
sys.stderr.write('doit addGrid')
grid3D.origin_copy = grid3D.origin
grid3D.stepSize_copy = grid3D.stepSize
mini, maxi, mean, std = grid3D.stats()
sys.stderr.write('doit addGrid')
grid3D.mini = mini
grid3D.maxi = maxi
grid3D.mean = mean
grid3D.std = std
if name == None:
name = str(grid3D)
if name in self.vf.grids3D:
name += "_"
def returnStringRepr():
return None, "\"" + name + "\""
grid3D.returnStringRepr = returnStringRepr
if not hasattr(grid3D,'geomContainer'):
grid3D.geomContainer = {}
g = Geom(name)
grid3D.master_geom = g
if self.vf.hasGui : self.vf.GUI.VIEWER.AddObject(g)
grid3D.geomContainer['IsoSurf'] = {}
grid3D.geomContainer['OrthoSlice'] = {}
IsoSurf = Geom('IsoSurf')
OrthoSlice = Geom('OrthoSlice')
box = Box('BoundingBox')
pt1 = grid3D.origin
dims = grid3D.data.shape
pt2 = [pt1[0]+(grid3D.stepSize[0]*(dims[0]-1)),
pt1[1]+(grid3D.stepSize[1]*(dims[1]-1)),
pt1[2]+(grid3D.stepSize[2]*(dims[2]-1))]
if grid3D.crystal:
ptList=((pt2[0],pt2[1],pt1[2]),
(pt1[0],pt2[1],pt1[2]),
(pt1[0],pt1[1],pt1[2]),
(pt2[0],pt1[1],pt1[2]),
(pt2[0],pt2[1],pt2[2]),
(pt1[0],pt2[1],pt2[2]),
(pt1[0],pt1[1],pt2[2]),
(pt2[0],pt1[1],pt2[2]))
coords = grid3D.crystal.toCartesian(ptList)
box.Set(vertices=coords)
else:
coords = (pt1, pt2)
box.Set(cornerPoints=coords)
grid3D.geomContainer['Box'] = box
if self.vf.hasGui :
self.vf.GUI.VIEWER.AddObject(box,parent=g)
self.vf.GUI.VIEWER.AddObject(IsoSurf,parent=g)
self.vf.GUI.VIEWER.AddObject(OrthoSlice,parent=g)
grid3D.IsoSurf = IsoSurf
grid3D.OrthoSlice = OrthoSlice
self.vf.grids3D[name] = grid3D
sys.stderr.write('doit addGridDone')
if self.vf.hasGui :
if self.vf.Grid3DCommands.root:
grid_name = name
grid_type = grid3D.data.dtype
self.vf.Grid3DCommands.mlb.insert(tkinter.END, (grid_name,
grid3D.dimensions, grid_type ))
#self.vf.Grid3DCommands.mlb.selection_clear(0, Tkinter.END)
#self.vf.Grid3DCommands.mlb.selection_set(Tkinter.END)
#self.vf.Grid3DAddRemove.select()
class readAnyGrid(Command):
""" The readAnyGrid reads any of the grids supported by Volume.IO and
saves Grid3D object in self.vf.grids3D[gridFile] where gridFile can be provided
by Grid3D-->Read GUI
\nPackage : ViewerFramework
\nModule : grid3DCommands
\nClass : readAnyGrid
\nCommand : readAnyGrid
\nSynopsis:\n
grid3D<-readAnyGrid(gridFile)\n
\nRequired Arguments:\n
gridFile : location of the grid file\n
"""
def __init__(self, func=None):
Command.__init__(self)
mapItems = [('AutoGrid',None),
('BRIX/DSN6',None),
('CCP4',None),
('CNS/XPLOR',None),
('Data Explorer(DX)',None),
('Delphi',None),
('GRD',None),
('MRC',None),
('Rawiv',None),
('SPIDER',None),
('UHBD/GRID',None),
('AVS/FLD Binary',None),
]
try:
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser
self.ifd=InputFormDescr(title='Map Types')
self.ifd.append({'name':'listchooser',
'widgetType':ListChooser,
'wcfg':{'title':'Select a Map Type:',
'entries':mapItems,
'lbwcfg':{'width':20,'height':12},
'mode':'single',
},
'gridcfg':{'sticky':'w','row':-1}
})
except:
pass
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'grids3D'):
self.vf.grids3D={}
def __call__(self, gridFile, **kw):
"""Grid3D object<-readAnyGrid(gridFile)\n
\nRequired Arguments:\n
gridFile : location of the grid file\n
"""
return self.doitWrapper(*(gridFile,), **kw)
def doit(self, gridFile, name=None, show=True, normalize=True):
"""Reads gridFile and adds it to Control Panel
Optoinal Arguments:
name : name of the grid file used as a key in self.vf.grid3d
if None os.path.basename(gridFile) is used
show : if True show Control panel
normalize : if true calls Normalize the Viewer
"""
if not gridFile: return
if not os.path.exists(gridFile):
print(gridFile, " not exists")
else:
if(re.search('\.mrc$',gridFile,re.I)):
reader = ReadMRC()
elif(re.search('\.ccp4*$',gridFile,re.I)):
reader = ReadCCP4()
elif(re.search('\.cns$|\.xplo*r*$',gridFile,re.I)):
reader = ReadCNS()
elif(re.search('\.grd$',gridFile,re.I)):
reader = ReadGRD()
elif(re.search('\.fld$',gridFile,re.I)):
reader = ReadFLDBinary()
elif(re.search('\.map$',gridFile,re.I)):
reader = ReadAutoGrid()
elif(re.search('\.omap$|\.brix$|\.dsn6$|\.dn6$',gridFile,re.I)):
reader = ReadBRIX()
elif(re.search('\.rawiv$',gridFile,re.I)):
reader = ReadRawiv()
elif(re.search('\.d*e*l*phi$',gridFile,re.I)):
reader = DelphiReaderBin()
elif(re.search('\.uhbd$',gridFile,re.I)):
reader = UHBDReaderASCII()
elif(re.search('\.dx$',gridFile,re.I)):
reader = ReadDX()
elif(re.search('\.spi$',gridFile,re.I)):
reader = ReadSPIDER()
else:
if not show: return
if self.vf.hasGui :
reader = self.askMapType()
if not reader:
return
print (reader)
try:
grid3D = reader.read(gridFile, normalize=True)
except Exception :
print("Error reading Grid")
if not show: return
if self.vf.hasGui :
reader = self.askMapType()
if not reader:
return
try:
grid3D = reader.read(gridFile, normalize=True)
except Exception :
# print(inst)
tkinter.messagebox.showerror("Error: in choosing a map",
"Could not parse %s. Please open Python shell for Traceback"%gridFile)
return
else : return
if not grid3D:
print("Error reading Grid")
if not show: return
if self.vf.hasGui :
reader = self.askMapType()
if not reader:
return
try:
grid3D = reader.read(gridFile, normalize=True)
except Exception:
# print(inst)
tkinter.messagebox.showerror("Error: in choosing a map",
"Could not parse %s. Please open Python shell for Traceback"%gridFile)
return
else : return
if name:
grid_basename = name
else:
grid_basename = os.path.basename(gridFile)
if grid3D:
grid3D.path = gridFile
self.vf.addGrid(grid3D, grid_basename,log=0)
if self.vf.hasGui :
if normalize:
self.vf.GUI.VIEWER.Normalize_cb()
if show:
self.vf.Grid3DCommands.show()
elif self.vf.embeded and self.vf.host == 'chimera':
import VolumeViewer
v=VolumeViewer.open_volume_file(gridFile)[-1]
grid3D.ch_vol = v
grid3D.master_geom.obj = v
return grid3D
def askMapType(self):
from mglutil.gui.BasicWidgets.Tk.customizedWidgets import ListChooser
"""Opens Select Map Type widget"""
f = InputForm(master=tkinter._default_root,
root=tkinter.Toplevel(),
descr=self.ifd, blocking=1, modal=1)
maptype=f.go()
if not maptype:
return False
choice=maptype['listchooser'][0]
if choice=='AutoGrid': reader=ReadAutoGrid()
elif choice=='BRIX/DSN6': reader=ReadBRIX()
elif choice=='CCP4': reader=ReadCCP4()
elif choice=='CNS/XPLOR': reader=ReadCNS()
elif choice=='Data Explorer(DX)': reader=ReadDX()
elif choice=='Delphi': reader=DelphiReaderBin()
elif choice=='GRD':reader=ReadGRD()
elif choice=='MRC':reader=ReadMRC()
elif choice=='Rawiv':reader=ReadRawiv()
elif choice=='SPIDER':reader=ReadSPIDER()
elif choice=='UHBD/GRID':reader=UHBDReaderASCII()
elif choice=='AVS/FLD Binary':self.reader=ReadFLDBinary()
else:
tkinter.messagebox.showerror("Error: in choosing a map",
"Error: in choosing" + choice)
return False
return reader
def guiCallback(self, parent = None):
"""called each time the 'Grid3D -> Import...' sequence is pressed"""
fileTypes = [('All supported files', '*.map *.ccp4 *.dx *.grd '+
'*.omap *.brix* *.dsn6* *.cns *.xplo*r* *.d*e*l*phi *.mrc *.rawiv *.spi *.uhbd'),
('AutoGrid', '*.map'),
('AVS/FLD Binary', '*.fld'),
('BRIX/DSN6', '*.omap *.brix* *.dsn6*'),
('CCP4', '*.ccp4'),
('CNS/XPLOR', '*.cns *.xplo*r*'),
('Data Explorer(DX)', '*.dx'),
('Delphi', '*.d*e*l*phi'),
('GRD', '*.grd'),
('MRC', '*.mrc'),
('Rawiv', '*.rawiv'),
('SPIDER', '*.spi'),
('UHBD/GRID', '*.uhbd'),
('all', '*')]
gridFile = tkinter.filedialog.askopenfilename(parent = parent,
filetypes=fileTypes, title = 'Grid File:')
if gridFile is not None and len(gridFile):
self.doitWrapper(gridFile, redraw=0)
readAnyGridGUI = CommandGUI()
readAnyGridGUI.addMenuCommand('menuRoot', 'Grid3D', 'Read...')
try:
class GridMultiListbox(MultiListbox):
"""Extends MultiListbox from mglutil.gui.BasicWidgets.Tk.multiListbox"""
def __init__(self, master, lists, **kw):
MultiListbox.__init__(self, master, lists, **kw)
self.girdName = ''
def _select(self, y):
self.Grid3DCommands.root.config(cursor='watch')
self.Grid3DCommands.root.update()
row = self.lists[0].nearest(y)
self.selection_clear(0, tkinter.END)
self.selection_set(row)
if row != -1:
girdName = self.Grid3DCommands.get_grid_name()
if girdName != self.girdName:
self.Grid3DCommands.current_cmd.select()
self.girdName = girdName
self.Grid3DCommands.root.config(cursor='')
return 'break'
except:
pass
width = 440 #width of the GUI
height = 200 #height of the GUI
class Grid3DCommands(Command):
"""This is the main class that adds GridMultiListbox widget with
Add/Remove, Isocontour and OrthoSlice icons and widgets
"""
def __init__(self, func=None):
Command.__init__(self)
self.root = None
self.Icons = []
self.Checkbuttons = {}
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'grids3D'):
self.vf.grids3D={}
def get_grid_name(self):
select = self.mlb.curselection()
if not select:
return None
grid_name = self.mlb.get(select[0])
return grid_name[0]
def select(self, name):
"Selects Listbox by Grid Name"
grids = self.mlb.lists[0].get(0,tkinter.END)
grids = list(grids)
index = grids.index(name)
self.mlb.selection_clear(0,tkinter.END)
self.mlb.selection_set(index)
def doit(self, show = True, **kw):
if show:
self.show()
else:
self.hide()
def guiCallback(self, **kw):
if not self.root:
self.root = tkinter.Toplevel()
self.root.title('3D Grid Rendering Control Panel')
self.root.protocol("WM_DELETE_WINDOW", self.hide)
menu = tkinter.Menu(self.root)
self.root.config(menu=menu)
self.root.minsize(width+5,width-5)
file = tkinter.Menu(menu)
file.add_command(label='Open Grid...',
command=self.vf.Grid3DAddRemove.add)
file.add_command(label='Load Settings...', command=self.open)
file.add_command(label='Save Settings...', command=self.save)
menu.add_cascade(label='File', menu=file)
self.PanedWindow = tkinter.PanedWindow(self.root, handlepad=0,
handlesize=0, orient=tkinter.VERTICAL, bd=1,
width=width,height=2*height)
self.PanedWindow.pack(fill=tkinter.BOTH, expand=1)
self.mlb = GridMultiListbox(self.PanedWindow, ((' Grid Name', 33),
('Dimensions ', 15),
('Type', 6)),
hull_height = 100,
usehullsize = 1,
hull_width = width)
self.mlb.pack(expand=tkinter.NO, fill=tkinter.X)
self.mlb.Grid3DCommands = self
for grid in self.vf.grids3D:
grid_name = grid
# if len(grid_name) > 40:
# grid_name = grid_name[-37:]
# grid_name = '...'+grid_name
grid_type = self.vf.grids3D[grid].data.dtype.name
self.vf.Grid3DCommands.mlb.insert(tkinter.END, (grid_name,
self.vf.grids3D[grid].dimensions, grid_type ))
self.PanedWindow.add(self.mlb)
main_frame = tkinter.Frame(self.PanedWindow)
main_frame.pack(expand=tkinter.YES, fill=tkinter.BOTH)
self.PanedWindow.add(main_frame, height=height+90)
self.main_frame = main_frame
toolbar_frame = tkinter.Frame(main_frame, bg='white',
relief=tkinter.RIDGE, bd=2)
toolbar_frame.pack(expand=tkinter.NO, fill=tkinter.X)
self.toolbar_frame = toolbar_frame
widget_frame = tkinter.Frame(main_frame)
widget_frame.pack(expand=tkinter.YES, fill=tkinter.BOTH)
self.widget_frame = widget_frame
cmd_list = [
('Add/Remove', 'add_rem.png', self.Add_Remove, 'Add/Remove 3D Gird')]
if isocontour:
cmd_list.append(('Isocontour', 'iso.png', self.Isocontour,
'Isocontouring Widget'))
cmd_list.append(('OrthoSlice', 'ortho.png', self.OrthoSlice,
'Orthogonal Slices'))
from Volume.Renderers.UTVolumeLibrary import UTVolumeLibrary
test = UTVolumeLibrary.VolumeRenderer()
flag = test.initRenderer()
if flag:
cmd_list.append(('VolRen', 'VolRen.png', self.VolRen,
'3D Texture-Based Volume Renderer'))
else:
print("Volume Renderer is Disabled")
#font LucidaTypewriter Marumoji, MiscFixed 14
for name, icon, func, txt in cmd_list:
Icon = get_icon(icon, master=self.root)
self.Icons.append(Icon)
Checkbutton = tkinter.Checkbutton(toolbar_frame, image=Icon,
indicatoron=0, command=func,
bg='white')
Checkbutton.ballon = Pmw.Balloon()
Checkbutton.ballon.bind(Checkbutton, txt)
self.Checkbuttons[name] = Checkbutton
Checkbutton.pack(side=tkinter.LEFT)
idf = self.vf.Grid3DAddRemove.ifd
self.add_remove_form = InputForm(main_frame,self.widget_frame,idf,
okcancel=0,closeWithWindow=0,
width=width, height=height)
self.add_remove_form.mf.config(bd =0)
self.add_remove_form.mf.pack_forget()
idf = self.vf.Grid3DIsocontour.ifd
self.isocontour_form = InputForm(main_frame,self.widget_frame,idf,
okcancel=0,closeWithWindow=0,
width=width, height=height)
self.isocontour_form.mf.config(bd =0)
self.isocontour_form.mf.pack_forget()
idf = self.vf.Grid3DOrthoSlice.ifd
self.OrthoSlice_form = InputForm(main_frame,self.widget_frame,idf,
okcancel=0,closeWithWindow=0,
width=width, height=height)
self.OrthoSlice_form.mf.config(bd =0)
self.OrthoSlice_form.mf.pack_forget()
idf = self.vf.Grid3DVolRen.ifd
self.VolRen_form = InputForm(main_frame,self.widget_frame,idf,
okcancel=0,closeWithWindow=0,
width=width, height=height)
self.VolRen_form.mf.config(bd =0)
self.VolRen_form.mf.pack_forget()
self.add_remove_form.mf.pack(expand=tkinter.YES, fill=tkinter.BOTH)
self.current_obj = self.add_remove_form
self.current_cmd = self.vf.Grid3DAddRemove
bottom_frame = tkinter.Frame(main_frame)
bottom_frame.pack(fill=tkinter.X)
self.close_b = tkinter.Button(bottom_frame, text=" Dismiss ",
command=self.hide)
self.close_b.pack(expand=tkinter.NO)
self.current_checkbutton = self.Checkbuttons['Add/Remove']
self.current_checkbutton.toggle()
self.vf.GUI.toolbarCheckbuttons['Grid3D']['Variable'].set(1)
self.GUI.menuButton.menu.entryconfig(3, label='Hide Control Panel',
command=self.hide)
h = self.root.winfo_reqheight()
w = self.mlb.interior().winfo_reqwidth()
if w > self.root.winfo_width():
self.root.geometry('%dx%d' % (w,h))
elif self.vf.GUI.toolbarCheckbuttons['Grid3D']['Variable'].get() == 0 \
and self.root:
self.root.withdraw()
self.GUI.menuButton.menu.entryconfig(3,label='Show Control Panel',
command=self.show)
elif self.vf.GUI.toolbarCheckbuttons['Grid3D']['Variable'].get() == 1 \
and self.root:
self.root.deiconify()
self.GUI.menuButton.menu.entryconfig(3,label='Hide Control Panel',
command=self.hide)
def show(self, event=None):
if self.root is None:
self.guiCallback()
else:
self.root.deiconify()
self.vf.GUI.toolbarCheckbuttons['Grid3D']['Variable'].set(1)
self.GUI.menuButton.menu.entryconfig(3, label='Hide Control Panel',
command=self.hide)
def hide(self, event=None):
if self.root:
self.root.withdraw()
self.vf.GUI.toolbarCheckbuttons['Grid3D']['Variable'].set(0)
self.GUI.menuButton.menu.entryconfig(3,label='Show Control Panel',
command=self.show)
def Add_Remove(self):
if self.current_cmd == self.vf.Grid3DVolRen:
self.current_cmd.ifd.entryByName['VolRen']['widget'].merge_function()
self.current_cmd.saveLUT_Dict()
self.current_checkbutton.config(state='normal')
self.current_checkbutton.toggle()
self.current_obj.mf.pack_forget()
self.add_remove_form.mf.pack(expand=tkinter.YES, fill=tkinter.BOTH)
self.current_obj = self.add_remove_form
self.Checkbuttons['Add/Remove'].config(state='disabled')
self.current_checkbutton = self.Checkbuttons['Add/Remove']
self.current_cmd = self.vf.Grid3DAddRemove
self.current_cmd.select()
def Isocontour(self):
self.root.configure(cursor='watch')
self.root.update()
if self.current_cmd == self.vf.Grid3DVolRen:
self.current_cmd.ifd.entryByName['VolRen']['widget'].merge_function()
self.current_cmd.saveLUT_Dict()
self.current_checkbutton.config(state='normal')
self.current_checkbutton.toggle()
self.current_obj.mf.pack_forget()
self.isocontour_form.mf.pack(expand=tkinter.YES, fill=tkinter.BOTH)
self.current_obj = self.isocontour_form
self.Checkbuttons['Isocontour'].config(state='disabled')
self.current_checkbutton = self.Checkbuttons['Isocontour']
self.current_cmd = self.vf.Grid3DIsocontour
self.current_cmd.select()
def OrthoSlice(self):
self.root.configure(cursor='watch')
self.root.update()
#This in needed to save the VolRen
if self.current_cmd == self.vf.Grid3DVolRen:
self.current_cmd.ifd.entryByName['VolRen']['widget'].merge_function()
self.current_cmd.saveLUT_Dict()
self.current_checkbutton.config(state='normal')
self.current_checkbutton.toggle()
self.current_obj.mf.pack_forget()
self.OrthoSlice_form.mf.pack(expand=tkinter.YES, fill=tkinter.BOTH)
self.current_obj = self.OrthoSlice_form
self.Checkbuttons['OrthoSlice'].config(state='disabled')
self.current_checkbutton = self.Checkbuttons['OrthoSlice']
self.current_cmd = self.vf.Grid3DOrthoSlice
self.current_cmd.select()
def VolRen(self):
self.root.configure(cursor='watch')
self.root.update()
self.current_checkbutton.config(state='normal')
self.current_checkbutton.toggle()
self.current_obj.mf.pack_forget()
self.VolRen_form.mf.pack(expand=tkinter.YES, fill=tkinter.BOTH)
self.current_obj = self.VolRen_form
self.Checkbuttons['VolRen'].config(state='disabled')
self.current_checkbutton = self.Checkbuttons['VolRen']
self.current_cmd = self.vf.Grid3DVolRen
self.current_cmd.select()
def save(self):
outFile = tkinter.filedialog.asksaveasfile(parent=self.root,
filetypes=[('Grid settings',
'*.pkl')],
title='Save Grid Control Panel File As:')
if not outFile:
return
self.vf.Grid3DCommands.root.config(cursor='watch')
settings = []
for gridName in self.vf.grids3D:
gridSettings = {}
gridSettings['name'] = gridName
grid = self.vf.grids3D[gridName]
gridSettings['path'] = grid.path
gridSettings['origin'] = grid.origin
gridSettings['stepSize'] = grid.stepSize
gridSettings['boxVisible'] = grid.geomContainer['Box'].visible
gridSettings['masterVisible'] = grid.master_geom.visible
if hasattr(grid,'isoBarNumber'): #saves Isocontour attributes
gridSettings['isoBarNumber'] = grid.isoBarNumber
gridSettings['isoBarTags'] = grid.isoBarTags
gridSettings['isoLastColor'] = grid.isoLastColor
gridSettings['isoLastX'] = grid.isoLastX
if hasattr(grid,'_X_Slice'): #saves OrthSlice attributes
gridSettings['_X_Slice'] = grid._X_Slice
gridSettings['_X_Vis'] = grid._X_Vis
if hasattr(grid,'_Y_Slice'):
gridSettings['_Y_Slice'] = grid._Y_Slice
gridSettings['_Y_Vis'] = grid._Y_Vis
if hasattr(grid,'_Z_Slice'):
gridSettings['_Z_Slice'] = grid._Z_Slice
gridSettings['_Z_Vis'] = grid._Z_Vis
if hasattr(grid,'volRenGrid'): #saves volRenGrid attributes
gridSettings['LUTintervals_list'] = grid.LUT_data.intervals_list
gridSettings['LUTshapes'] = grid.LUT_data.shapes
gridSettings['LUTvalues'] = grid.LUT_data.values
gridSettings['LUTcolor_arr'] = grid.LUT_data.color_arr
gridSettings['LUTalpha_arr'] = grid.LUT_data.alpha_arr
settings.append(gridSettings)
pickle.dump(settings, outFile)
outFile.close()
self.vf.Grid3DCommands.root.config(cursor='')
self.vf.Grid3DCommands.PanedWindow.config(cursor='')
def open(self):
inFile = tkinter.filedialog.askopenfile(parent=self.root,
filetypes=[('Grid settings',
'*.pkl'),
('all', '*') ],
title='Open Grid Control Panel File:')
if not inFile:
return
self.vf.Grid3DCommands.root.config(cursor='watch')
settings = pickle.load(inFile)
for gridSettings in settings:
self.vf.Grid3DReadAny.doit(gridSettings['path'],
name=gridSettings['name'])
grid = self.vf.grids3D[gridSettings['name']]
grid.origin = gridSettings['origin']
grid.stepSize = gridSettings['stepSize']
grid.geomContainer['Box'].visible = gridSettings['boxVisible']
grid.master_geom.visible = gridSettings['masterVisible']
if 'isoBarNumber' in gridSettings:
grid.isoBarNumber = gridSettings['isoBarNumber']
grid.isoBarTags = gridSettings['isoBarTags']
grid.isoLastColor = gridSettings['isoLastColor']
grid.isoLastX = gridSettings['isoLastX']
origin = Numeric.array(grid.origin).astype('f')
stepsize = Numeric.array(grid.stepSize).astype('f')
data = grid.data
if data.dtype.char!=Numeric.Float32:
data = data.astype('f')
self.vf.Grid3DIsocontour.newgrid3D = Numeric.reshape(
Numeric.transpose(data),
(1, 1)+tuple(data.shape) )
if self.vf.Grid3DIsocontour.iso_data:
isocontour.delDatasetReg(self.vf.Grid3DIsocontour.iso_data)
self.vf.Grid3DIsocontour.iso_data = isocontour.\
newDatasetRegFloat3D(self.vf.Grid3DIsocontour.newgrid3D,
origin, stepsize)
for i in range(1, grid.isoBarNumber+1):
tag = grid.isoBarTags[i-1]
if grid.isoLastX[tag]<0:
invertNormals = True
else:
invertNormals = False
color = grid.isoLastColor[tag]
r = int(color[1:3], 16)
g = int(color[3:5], 16)
b = int(color[5:7], 16)
self.vf.Grid3DIsocontour.doit(grid, name=tag,
isovalue=grid.isoLastX[tag],
invertNormals=invertNormals,
material=(r/255., g/255., b/255, 0.5))
if '_X_Slice' in gridSettings:
grid._X_Slice = gridSettings['_X_Slice']
grid._X_Vis = gridSettings['_X_Vis']
geom = textured2DArray('OrthoSlice_X',
inheritLighting=False,
lighting=False)
self.vf.GUI.VIEWER.AddObject(geom, parent=grid.OrthoSlice)
grid.geomContainer['OrthoSlice']['X'] = geom
data, vertices = grid.get2DOrthoSlice('x', grid._X_Slice)
geom.Set(vertices=vertices, array=data, visible=grid._X_Vis)
if '_Y_Slice' in gridSettings:
grid._Y_Slice = gridSettings['_Y_Slice']
grid._Y_Vis = gridSettings['_Y_Vis']
geom = textured2DArray('OrthoSlice_Y',
inheritLighting=False,
lighting=False)
self.vf.GUI.VIEWER.AddObject(geom, parent=grid.OrthoSlice)
grid.geomContainer['OrthoSlice']['Y'] = geom
data, vertices = grid.get2DOrthoSlice('y', grid._Y_Slice)
geom.Set(vertices=vertices, array=data, visible=grid._Y_Vis)
if '_Z_Slice' in gridSettings:
grid._Z_Slice = gridSettings['_Z_Slice']
grid._Z_Vis = gridSettings['_Z_Vis']
geom = textured2DArray('OrthoSlice_Z',
inheritLighting=False,
lighting=False)
self.vf.GUI.VIEWER.AddObject(geom, parent=grid.OrthoSlice)
grid.geomContainer['OrthoSlice']['Z'] = geom
data, vertices = grid.get2DOrthoSlice('z', grid._Z_Slice)
geom.Set(vertices=vertices, array=data, visible=grid._Z_Vis)
if 'LUTintervals_list' in gridSettings:
from Volume.Operators.MapData import MapGridData
datamap = {}
datamap['src_min'] = grid.mini
datamap['src_max'] = grid.maxi
datamap['dst_min'] = 0
datamap['dst_max'] = 255
datamap['map_type'] = 'linear'
mapper = MapGridData()
result = mapper(grid.data, datatype=Numeric.UInt8, datamap=datamap,
powerOf2=True)
gtype = ArrayTypeToGrid[result.dtype.char]
if grid.crystal:
from mglutil.math.crystal import Crystal
crystal = Crystal( grid.crystal.length, grid.crystal.angles)
else:
crystal = None
newgrid = gtype(result, grid.origin, grid.stepSize,
grid.header.copy(), crystal)
newgrid.dataDims = grid.data.shape[:]
grid.volRenGrid = newgrid
geom = UTVolRenGeom('VolRender')
grid.geomContainer['VolRender'] = geom
self.vf.GUI.VIEWER.AddObject(geom, parent=grid.master_geom)
geom.AddGrid3D(newgrid)
self.vf.GUI.VIEWER.OneRedraw()
grid.LUT_data = LUT_data()
grid.LUT_data.intervals_list = gridSettings['LUTintervals_list']
grid.LUT_data.shapes = gridSettings['LUTshapes']
grid.LUT_data.values = gridSettings['LUTvalues']
grid.LUT_data.color_arr = gridSettings['LUTcolor_arr']
grid.LUT_data.alpha_arr = gridSettings['LUTalpha_arr']
geom.setVolRenAlpha([0,grid.LUT_data.alpha_arr])
geom.setVolRenColors([0,grid.LUT_data.color_arr])
inFile.close()
self.vf.Grid3DCommands.root.config(cursor='')
self.vf.Grid3DCommands.PanedWindow.config(cursor='')
Grid3DGUI = CommandGUI()
msg = '3D Grid/Volume Rendering'
Grid3DGUI.addToolBar('Grid3D', icon1='vol.png', balloonhelp=msg, index=13.,
icon_dir=ICONPATH)
Grid3DGUI.addMenuCommand('menuRoot', 'Grid3D', 'Show Control Panel')
"""
class AddRemove(Command):
def __init__(self, func=None):
if hasattr(self, 'root') is True:
master = self.root
else:
master = None
Command.__init__(self)
self.boundingBoxVisible = Tkinter.BooleanVar()
self.boundingBoxVisible.set(1)
self.childGeomVisible = Tkinter.BooleanVar()
self.childGeomVisible.set(1)
self.Icons = []
self.ifd = InputFormDescr(title = "Add Ion")
self.ifd.append({'name':'step_size_label',
'widgetType':Tkinter.Label,
'wcfg':{'text':''},
'gridcfg':{'row':0, 'column':1, 'sticky':'w'}
})
Icon = get_icon('add.png', master=master)
self.Icons.append(Icon)
self.ifd.append({'name':'Add',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Add', 'image':Icon, 'command':self.add},
'gridcfg':{'row':1, 'column':0, 'sticky':'we'}
})
self.ifd.append({'name':'Name',
'widgetType':Pmw.EntryField,
'wcfg':{'labelpos':'w', 'label_text':'Grid Name:',
'command':self.apply},
'gridcfg':{'row':1, 'column':1, 'columnspan':4,'sticky':'we'}
})
self.ifd.append({'name':'l_add',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Add'},
'gridcfg':{'row':2, 'column':0, 'sticky':'we'}
})
self.ifd.append({'name':'origin_label',
'widgetType':Tkinter.Label,
'wcfg':{'text':' Origin:'},
'gridcfg':{'row':3, 'column':1, 'sticky':'w'}
})
self.ifd.append({'name':'X_origin',
'widgetType':Pmw.EntryField,
'wcfg':{'labelpos':'e', 'label_text':'X', 'entry_width':8,
'validate':{'validator' : 'real'},'sticky':'w',
'command':self.apply},
'gridcfg':{'row':3, 'column':2, 'sticky':'w'}
})
self.ifd.append({'name':'Y_origin',
'widgetType':Pmw.EntryField,
'wcfg':{'labelpos':'e', 'label_text':'Y', 'entry_width':8,
'validate':{'validator' : 'real'},'sticky':'w',
'command':self.apply},
'gridcfg':{'row':3, 'column':3, 'sticky':'w'}
})
self.ifd.append({'name':'Z_origin',
'widgetType':Pmw.EntryField,
'wcfg':{'labelpos':'e', 'label_text':'Z', 'entry_width':8,
'validate':{'validator' : 'real'},'sticky':'w',
'command':self.apply},
'gridcfg':{'row':3, 'column':4, 'sticky':'w'}
})
Icon = get_icon('rem.png', master=master)
self.Icons.append(Icon)
self.ifd.append({'name':'Remove',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Remove','image':Icon,'command':self.remove},
'gridcfg':{'row':3, 'column':0, 'sticky':'we'}
})
self.ifd.append({'name':'l_remove',
'widgetType':Tkinter.Label,
'wcfg':{'text':'Remove'},
'gridcfg':{'row':4, 'column':0, 'sticky':'we'}
})
self.ifd.append({'name':'step_size_label',
'widgetType':Tkinter.Label,
'wcfg':{'text':' Step Size:'},
'gridcfg':{'row':4, 'column':1, 'sticky':'w'}
})
self.ifd.append({'name':'dX',
'widgetType':Pmw.EntryField,
'wcfg':{'labelpos':'e', 'label_text':'dX', 'entry_width':8,
'validate':{'validator' : 'real'},'sticky':'w',
'command':self.apply},
'gridcfg':{'row':4, 'column':2, 'sticky':'w'}
})
self.ifd.append({'name':'dY',
'widgetType':Pmw.EntryField,
'wcfg':{'labelpos':'e', 'label_text':'dY', 'entry_width':8,
'validate':{'validator' : 'real'},'sticky':'w',
'command':self.apply},
'gridcfg':{'row':4, 'column':3, 'sticky':'w'}
})
self.ifd.append({'name':'dZ',
'widgetType':Pmw.EntryField,
'wcfg':{'labelpos':'e', 'label_text':'dZ', 'entry_width':8,
'validate':{'validator' : 'real'},'sticky':'w',
'command':self.apply},
'gridcfg':{'row':4, 'column':4, 'sticky':'w'}
})
self.ifd.append({'name':'Apply',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Apply', 'command':self.apply},
'gridcfg':{'row':5, 'column':3,'sticky':'we'}
})
self.ifd.append({'name':'Reset',
'widgetType':Tkinter.Button,
'wcfg':{'text':'Reset', 'command':self.reset},
'gridcfg':{'row':5, 'column':4, 'sticky':'we'}
})
self.ifd.append({'name':'childGeomVisible',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Show/Hide Volume',
'command':self.changeChildrenVisible,
'variable':self.childGeomVisible},
'gridcfg':{'row':6, 'column':0,'columnspan':3, 'sticky':'w'}
})
self.ifd.append({'name':'boundingBoxVisible',
'widgetType':Tkinter.Checkbutton,
'wcfg':{'text':'Show Bounding Box','command':self.changeBox,
'variable':self.boundingBoxVisible},
'gridcfg':{'row':6, 'column':3,'columnspan':3}
})
def onAddCmdToViewer(self):
if not hasattr(self.vf, 'grids3D'):
self.vf.grids3D={}