-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathManifoldEM_GUI.py
9923 lines (8626 loc) · 441 KB
/
ManifoldEM_GUI.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 __future__ import print_function
import sys, os, os.path, time, errno, psutil
from PyQt5.QtWidgets import *
import csv
from subprocess import call
import multiprocessing
import optparse
time_init = time.strftime("%Y%m%d_%H%M%S")
pyDir = os.path.dirname(os.path.abspath(__file__)) #python file location
inputDir = os.path.join(pyDir, 'data_input')
modDir = os.path.join(pyDir, 'modules')
CCDir = os.path.join(modDir, 'CC')
BPDir = os.path.join(CCDir, 'BP')
sys.path.append(modDir) #link imports to 'modules' folder
sys.path.append(CCDir) #link imports to 'modules -> CC' folder
sys.path.append(BPDir) #link imports to 'modules -> CC -> BP' folder
from pyface.qt import QtGui, QtCore
os.environ['ETS_TOOLKIT'] = 'qt4'
import sip
sip.setapi('QString', 2)
import threading
import gc #garbage collection
import shutil
import re
import matplotlib
matplotlib.use('Agg') #Qt4Agg
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from matplotlib.widgets import Slider, Button
import mpl_toolkits.axes_grid1
import matplotlib.path as pltPath
import matplotlib.image as mpimg
from matplotlib.ticker import MaxNLocator
from matplotlib import rc
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
import numpy as np
from pylab import imshow, show, loadtxt, axes
from scipy import stats
import itertools
import Data
import mrcfile
from PIL import Image
import imageio
import cv2
import pickle
import p
p.init() #only initiate once
p.user_dir = pyDir #default
import myio
import GetDistancesS2
import manifoldAnalysis
import psiAnalysis
import NLSAmovie
import embedd
import clusterAvg
import projectMask
import FindConformationalCoord
import EL1D
import backup
import PrepareOutputS2
import set_params
import logging
from traits.api import HasTraits,Any,Instance,on_trait_change,List,Str,Int,Float,Range,Button,Callable,Enum
from traitsui.api import View,Item,HSplit,Group,HGroup,VGroup,ListEditor,TextEditor,RangeEditor,Handler
from mayavi import mlab
from mayavi.core.api import PipelineBase, Engine
from mayavi.core.ui.api import MayaviScene, MlabSceneModel, SceneEditor
from tvtk.api import tvtk
from tvtk.pyface.api import Scene
from tvtk.common import configure_input_data
#from enthought.pyface.api import GUI #GUI.set_busy()
import warnings
warnings.filterwarnings('ignore', '.*GUI is implemented.*')
warnings.filterwarnings('ignore', '.*Adding an axes using the same*')
warnings.filterwarnings('ignore', '.*Unable to find pixel distance*.') #TauCanvas Linux-only error
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.filterwarnings('ignore', '.*FixedFormatter.*')
'''
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) CU, Evan Seitz 2018-2020
Columbia University
Contact: [email protected]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'''
# =============================================================================
# Global assets:
# =============================================================================
progname = 'ManifoldEM'
progversion = '0.2.0-beta'
Beta = True #set to 'True' to disable 2D options; if disabled ('False') within this Beta, demo Ribosome energy landscape can be examined (only) using GUI
#0.1.0: alpha (2019)
#0.2.0: beta (2021)
Graphics = True #set to 'False' to disable 3D graphics, which may be helpful for ssh GUI use on remote workstations
if Graphics is False:
print('Mode set: 3D graphics disabled.')
font_header = QtGui.QFont('Arial', 13)
font_standard = QtGui.QFont('Arial', 12)
anchorsMin = 1 #set minimum number of anchors needed for Belief Propagation
p.resProj = 0
p.PDsizeThL = 100
p.PDsizeThH = 2000
if Beta:
p.dim = 1
else:
p.dim = 2
p.ncpu = 1
p.num_psis = 8
p.user_dir = pyDir
p.proj_name = time_init
p.temperature = 25
# as a note, the word 'ZULU' is used throughout this document as a bookmark for pending items by E. Seitz.
# =============================================================================
# Command line arguments:
# =============================================================================
parser = optparse.OptionParser()
# --resume user progress via data_inputs.txt location (string):
parser.add_option('--input',
help='Name of previous project to resume (i.e., params_<name>.pkl)',
type='str', action='store', dest='userInput')
parser.set_defaults(userInput='empty')
# --turn on Message Passing Interface (MPI) via text file location (string):
parser.add_option('--mpi',
help='Path (str) to the machinefile for initiating MPI',
type='str', action='store', dest='mpiFile')
parser.set_defaults(mpiFile='') #ZULU add to user manual; check is working
# gather command line arguments:
options, args = parser.parse_args()
global userInput
userInput = options.userInput
p.machinefile = options.mpiFile
if options.mpiFile:
print('')
print('MPI initiated...')
print('')
# =============================================================================
# OS identification (if needed):
# =============================================================================
Windows = sys.platform.lower().startswith(('win','microsoft'))
Mac = sys.platform.lower().startswith('darwin')
Linux = sys.platform.lower().startswith(('linux','linux2'))
# =============================================================================
# MayaVI viz 1 (P2):
# =============================================================================
class Mayavi_S2(HasTraits): # S2 Orientation Sphere, Electrostatic Potential Map
if Graphics is False:
def update_S2_density_all(self):
print('')
def update_S2_params(self):
print('')
def update_scene1(self):
print('')
def update_scene2(self):
print('')
else: #typical mode
scene1 = Instance(MlabSceneModel, ())
scene2 = Instance(MlabSceneModel, ())
S2_scale_all = List([.2,.4,.6,.8,1.0,1.2,1.4,1.6,1.8,2.0])
S2_scale = Enum(1.0, values='S2_scale_all')
display_angle = Button('Display Euler Angles')
phi = Str
theta = Str
display_thresh = Button('PD Thresholding')
isosurface_level = Range(2,9,3,mode='enum')
S2_rho = Int
S2_density_all = List([5,10,25,50,100,250,500,1000,10000,100000]) #needs to match P1.S2_density_all
S2_density = Enum(S2_rho, values='S2_density_all')
click_on = 0
def _phi_default(self):
return '%s%s' % (0, u"\u00b0")
def _theta_default(self):
return '%s%s' % (0, u"\u00b0")
def _S2_rho_default(self):
return 100
def update_S2_params(self):
self.isosurface_level = int(p.S2iso)
self.S2_scale = float(P1.S2rescale)
self.S2_rho = MainWindow.S2_rho
self.S2_density = int(self.S2_rho)
def update_S2_density_all(self):
self.S2_density_all = []
for i in P1.S2_density_all:
self.S2_density_all.append(int(i))
@on_trait_change('display_angle')
def view_anglesP2(self):
viewS2 = self.scene1.mlab.view(figure=Mayavi_S2.fig1)
azimuth = viewS2[0] #phi: 0-360
elevation = viewS2[1] #theta: 0-180
zoom = viewS2[2]
print_anglesP2(azimuth, elevation)
@on_trait_change('S2_scale, S2_density') #S2 Orientation Sphere
def update_scene1(self):
# store current camera info:
view = self.scene1.mlab.view()
roll = self.scene1.mlab.roll()
Mayavi_S2.fig1 = mlab.figure(1, bgcolor=(.5,.5,.5))
Mayavi_S2.fig2 = mlab.figure(2, bgcolor=(.5,.5,.5))
mlab.clf(figure=Mayavi_S2.fig1)
P1.x1,P1.y1,P1.z1 = P1.S2[0, ::self.S2_density], P1.S2[1, ::self.S2_density], P1.S2[2, ::self.S2_density]
values = np.array([P1.x1,P1.y1,P1.z1])
try:
kde = stats.gaussian_kde(values)
P1.d1 = kde(values) #density
P1.d1 /= P1.d1.max() #relative density, max=1
splot = mlab.points3d(P1.x1, P1.y1, P1.z1, P1.d1, scale_mode='none',
scale_factor=0.05, figure=Mayavi_S2.fig1)
cbar = mlab.scalarbar(title='Relative\nDensity\n', orientation='vertical', \
nb_labels=3, label_fmt='%.1f')
except:
splot = mlab.points3d(P1.x1, P1.y1, P1.z1, scale_mode='none',
scale_factor=0.05, figure=Mayavi_S2.fig1)
#####################
# align-to-grid data:
phi, theta = np.mgrid[0:np.pi:11j, 0:2*np.pi:11j]
x = np.sin(phi) * np.cos(theta)
y = np.sin(phi) * np.sin(theta)
z = np.cos(phi)
testPlot = mlab.mesh(x, y, z, representation='wireframe', color=(0, 0, 0))
testPlot.actor.actor.scale = np.array([50,50,50])
testPlot.actor.property.opacity = 0
#####################
splot.actor.actor.scale = np.multiply(self.S2_scale,
np.array([len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2))]))
splot.actor.property.backface_culling = True
splot.mlab_source.reset
splot.module_manager.scalar_lut_manager.scalar_bar_widget.repositionable = False
splot.module_manager.scalar_lut_manager.scalar_bar_widget.resizable = False
# reposition camera to previous:
self.scene1.mlab.view(*view)
self.scene1.mlab.roll(roll)
def press_callback(vtk_obj, event): #left mouse down callback
self.click_on = 1
def hold_callback(vtk_obj, event): #camera rotate callback
if self.click_on > 0:
viewS2 = self.scene1.mlab.view(figure=Mayavi_S2.fig1)
self.phi = '%s%s' % (round(viewS2[0],2), u"\u00b0")
self.theta = '%s%s' % (round(viewS2[1],2), u"\u00b0")
#self.scene2.mlab.view(viewS2[0],viewS2[1],viewS2[2],viewS2[3],figure=Mayavi_S2.fig2)
def release_callback(vtk_obj, event): #left mouse release callback
if self.click_on == 1:
self.click_on = 0
Mayavi_S2.fig1.scene.scene.interactor.add_observer('LeftButtonPressEvent', press_callback)
Mayavi_S2.fig1.scene.scene.interactor.add_observer('InteractionEvent', hold_callback)
Mayavi_S2.fig1.scene.scene.interactor.add_observer('EndInteractionEvent', release_callback)
# if display parameters have changed, store them to be grabbed by tab 4:
MainWindow.S2_scale = self.S2_scale
MainWindow.S2_iso = self.isosurface_level
p.S2iso = MainWindow.S2_iso
p.S2rescale = MainWindow.S2_scale #arcade
set_params.op(0) #send new GUI data to user parameters file
@on_trait_change('isosurface_level') #Electrostatic Potential Map
def update_scene2(self):
# store current camera info:
view = mlab.view()
roll = mlab.roll()
Mayavi_S2.fig1 = mlab.figure(1, bgcolor=(.5,.5,.5))
Mayavi_S2.fig2 = mlab.figure(2, bgcolor=(.5,.5,.5))
mlab.sync_camera(Mayavi_S2.fig1, Mayavi_S2.fig2)
mlab.sync_camera(Mayavi_S2.fig2, Mayavi_S2.fig1)
mlab.clf(figure=Mayavi_S2.fig2)
if P1.relion_data == True:
mirror = P1.df_vol[..., ::-1]
cplot = mlab.contour3d(mirror,contours=self.isosurface_level,
color=(0.9, 0.9, 0.9),
figure=Mayavi_S2.fig2)
cplot.actor.actor.orientation = np.array([0., -90., 0.])
else:
cplot = mlab.contour3d(P1.df_vol,contours=self.isosurface_level,
color=(0.9, 0.9, 0.9), figure=Mayavi_S2.fig2)
cplot.actor.actor.origin = np.array([len(P1.df_vol)/2,len(P1.df_vol)/2,len(P1.df_vol)/2])
cplot.actor.actor.position = np.array([-len(P1.df_vol)/2,-len(P1.df_vol)/2,-len(P1.df_vol)/2])
cplot.actor.property.backface_culling = True
cplot.compute_normals = False
cplot.mlab_source.reset
#####################
# align-to-grid data:
phi, theta = np.mgrid[0:np.pi:11j, 0:2*np.pi:11j]
x = np.sin(phi) * np.cos(theta)
y = np.sin(phi) * np.sin(theta)
z = np.cos(phi)
testPlot = mlab.mesh(x, y, z, representation='wireframe', color=(0, 0, 0))
testPlot.actor.actor.scale = np.array([50,50,50])
testPlot.actor.property.opacity = 0
####################
# reposition camera to previous:
mlab.view(view[0],view[1],len(P1.df_vol)*2,view[3]) #zoom out based on MRC volume dimensions
mlab.roll(roll)
def press_callback(vtk_obj, event): #left mouse down callback
self.click_on = 1
def hold_callback(vtk_obj, event): #camera rotate callback
if self.click_on > 0:
viewS2 = self.scene2.mlab.view(figure=Mayavi_S2.fig2)
self.phi = '%s%s' % (round(viewS2[0],2), u"\u00b0")
self.theta = '%s%s' % (round(viewS2[1],2), u"\u00b0")
#self.scene1.mlab.view(viewS2[0],viewS2[1],viewS2[2],viewS2[3],figure=Mayavi_S2.fig1)
def release_callback(vtk_obj, event): #left mouse release callback
if self.click_on == 1:
self.click_on = 0
Mayavi_S2.fig2.scene.scene.interactor.add_observer('LeftButtonPressEvent', press_callback)
Mayavi_S2.fig2.scene.scene.interactor.add_observer('InteractionEvent', hold_callback)
Mayavi_S2.fig2.scene.scene.interactor.add_observer('EndInteractionEvent', release_callback)
# if display parameters have changed, store them to be grabbed by tab 4:
MainWindow.S2_scale = self.S2_scale
MainWindow.S2_iso = self.isosurface_level
p.S2iso = MainWindow.S2_iso
p.S2rescale = MainWindow.S2_scale #arcade
set_params.op(0) #send new GUI data to user parameters file
titleLeft = Str
titleRight = Str
def _titleLeft_default(self):
return 'S2 Orientation Distribution'
def _titleRight_default(self):
return 'Electrostatic Potential Map'
@on_trait_change('display_thresh')
def GCsViewer(self):
global GCs_window
try:
GCs_window.close()
except:
pass
GCs_window = Thresh_Viz()
GCs_window.setMinimumSize(10, 10)
GCs_window.setWindowTitle('Projection Direction Thresholding')
GCs_window.show()
view = View(VGroup(
HGroup( #HSplit
Group(
Item('titleLeft',springy=False,show_label=False,style='readonly',
style_sheet='*{font-size:12px; qproperty-alignment:AlignCenter}'),
Item('scene1',
editor=SceneEditor(scene_class=MayaviScene),
height=1, width=1, show_label=False, springy=True,
),
),
Group(
Item('titleRight',springy=False,show_label=False,style='readonly',
style_sheet='*{font-size:12px; qproperty-alignment:AlignCenter}'),
Item('scene2',
editor=SceneEditor(scene_class=MayaviScene),
height=1, width=1, show_label=False, springy=True,
),
),
),
HGroup(
HGroup(
Item('display_thresh',springy=True,show_label=False,
tooltip='Display the occupancy of each PD.'),
Item('S2_scale',springy=True,show_label=True,
tooltip='Change the relative scale of S2 with respect to the volume map above.'),
Item('S2_density',springy=True,show_label=True,
tooltip='Density of available points displayed on S2.'),
show_border=True,orientation='horizontal'),
HGroup(
Item('phi',springy=True,show_label=True,#style='readonly',
editor=TextEditor(evaluate=float),
enabled_when='phi == float(0)', #i.e., never
),
#Item('_'),
Item('theta',springy=True,show_label=True,#style='readonly',
editor=TextEditor(evaluate=float),
enabled_when='phi == float(0)', #i.e., never
),
Item('isosurface_level',springy=True,show_label=True,
tooltip='Change the isosurface level of the volume map above.'),
show_border=True,orientation='horizontal'),
),
),
resizable=True,
)
################################################################################
# mayaVI viz 2 (Conformational Coordinates):
class Mayavi_Rho(HasTraits): #electrostatic potential map, P4
if Graphics is False:
def update_scene3(self):
print('')
def update_viewP4(self, azimuth, elevation, distance):
print('')
def view_anglesP4(self, dialog):
print('')
def update_S2(self):
print('')
def update_euler(self):
print('')
else: #standard mode
scene3 = Instance(MlabSceneModel, ())
PrD_high = 2
isosurface = Range(2,9,3, mode='enum')
volume_alpha = Enum(1.0,.8,.6,.4,.2,0.0)
S2_scale = Float
anchorsUpdate = []
trashUpdate = []
phi = Str
theta = Str
click_on = 0
click_on_Eul = 0
def _phi_default(self):
return '%s%s' % (0, u"\u00b0")
def _theta_default(self):
return '%s%s' % (0, u"\u00b0")
def _S2_scale_default(self):
return float(1)
def update_S2(self):
self.S2_scale = float(MainWindow.S2_scale)
self.isosurface = int(MainWindow.S2_iso)
def view_anglesP4(self, dialog):
viewRho = self.scene3.mlab.view(figure=Mayavi_Rho.fig3)
azimuth = viewRho[0] #phi: 0-360
elevation = viewRho[1] #theta: 0-180
zoom = viewRho[2]
if dialog is True:
print_anglesP4(azimuth, elevation)
else:
return zoom
def update_viewP4(self, azimuth, elevation, distance):
self.scene3.mlab.view(azimuth=azimuth,
elevation=elevation,
distance=distance,
reset_roll=False,
figure=Mayavi_Rho.fig3)
def update_euler(self):
self.phi = '%s%s' % (round(float(P3.phi[(P4.user_PrD)-1]), 2), u"\u00b0")
self.theta = '%s%s' % (round(float(P3.theta[(P4.user_PrD)-1]), 2), u"\u00b0")
@on_trait_change('S2_scale,volume_alpha,isosurface')
def update_scene3(self):
# store current camera info:
view = self.scene3.mlab.view()
roll = self.scene3.mlab.roll()
Mayavi_Rho.fig3 = mlab.figure(3)
self.scene3.background = (0.0, 0.0, 0.0)
if P3.dictGen == False: #if P3 dictionaries not yet created (happens once on P3)
mlab.clf(figure=Mayavi_Rho.fig3)
# =================================================================
# Volume (contour):
# =================================================================
mirror = P1.df_vol[..., ::-1]
cplot = mlab.contour3d(mirror,contours=self.isosurface,
color=(0.5, 0.5, 0.5),
figure=Mayavi_Rho.fig3)
cplot.actor.actor.orientation = np.array([0., -90., 0.]) #ZULU?
cplot.actor.actor.origin = np.array([len(P1.df_vol)/2,len(P1.df_vol)/2,len(P1.df_vol)/2])
cplot.actor.actor.position = np.array([-len(P1.df_vol)/2,-len(P1.df_vol)/2,-len(P1.df_vol)/2])
cplot.actor.property.backface_culling = True
cplot.compute_normals = False
cplot.actor.property.opacity = self.volume_alpha
# =================================================================
# Align-to-grid data:
# =================================================================
phi, theta = np.mgrid[0:np.pi:11j, 0:2*np.pi:11j]
x = np.sin(phi) * np.cos(theta)
y = np.sin(phi) * np.sin(theta)
z = np.cos(phi)
testPlot = mlab.mesh(x, y, z, representation='wireframe', color=(1, 1, 1))
testPlot.actor.actor.scale = np.multiply(self.S2_scale,
np.array([len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2))]))
testPlot.actor.property.opacity = 0
# =================================================================
# S2 Distribution (scatter):
# =================================================================
splot = mlab.points3d(P1.x2,P1.y2,P1.z2,P3.col, scale_mode='none',
scale_factor=0.05, figure=Mayavi_Rho.fig3)
splot.actor.property.backface_culling = True
splot.actor.actor.scale = np.multiply(self.S2_scale,
np.array([len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2))]))
splot.actor.actor.origin = np.array([0,0,0])
splot.actor.actor.position = np.array([0,0,0])
# =================================================================
# S2 Anchors (sparse scatter):
# =================================================================
aplot = mlab.points3d(P1.x3,P1.y3,P1.z3, scale_mode='none',
scale_factor=0.06, figure=Mayavi_Rho.fig3)
aplot.actor.property.backface_culling = True
aplot.glyph.color_mode = 'no_coloring'
aplot.actor.property.color = (1.0, 1.0, 1.0)
aplot.actor.actor.scale = np.multiply(self.S2_scale,
np.array([len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2))]))
aplot.actor.actor.origin = np.array([0,0,0])
aplot.actor.actor.position = np.array([0,0,0])
self.anchorsUpdate = aplot.mlab_source
# =================================================================
# S2 Trash (sparse scatter):
# =================================================================
tplot = mlab.points3d(P1.x4,P1.y4,P1.z4, scale_mode='none',
scale_factor=0.06, figure=Mayavi_Rho.fig3)
tplot.actor.property.backface_culling = True
tplot.glyph.color_mode = 'no_coloring'
tplot.actor.property.color = (0.0, 0.0, 0.0)
tplot.actor.actor.scale = np.multiply(self.S2_scale,
np.array([len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2)),
len(P1.df_vol)/float(np.sqrt(2))]))
tplot.actor.actor.origin = np.array([0,0,0])
tplot.actor.actor.position = np.array([0,0,0])
self.trashUpdate = tplot.mlab_source
else: #only update anchors
self.anchorsUpdate.reset(x=P1.x3, y=P1.y3, z=P1.z3)
self.trashUpdate.reset(x=P1.x4, y=P1.y4, z=P1.z4)
# =====================================================================
# reposition camera to previous:
# =====================================================================
mlab.view(*view)
mlab.roll(roll)
def press_callback(vtk_obj, event): #left mouse down callback
self.click_on = 1
def release_callback(vtk_obj, event): #left mouse release callback
if self.click_on == 1:
self.click_on = 0
# =============================================================
# magnetize to nearest PrD:
# =============================================================
# CONVENTIONS:
# =============================================================
# mayavi angle 0 -> [-180, 180]: azimuth, phi, longitude
# mayavi angle 1 -> [0, 180]: elevation/inclination, theta, latitude
# =============================================================
angles = self.scene3.mlab.view(figure=Mayavi_Rho.fig3)
phi0 = angles[0]*np.pi/180
theta0 = angles[1]*np.pi/180
r0 = 1
x0 = (r0*np.sin(theta0)*np.cos(phi0))
y0 = (r0*np.sin(theta0)*np.sin(phi0))
z0 = (r0*np.cos(theta0))
# read points from tesselated sphere:
fname = os.path.join(P1.user_directory,'outputs_{}/topos/Euler_PrD/PrD_map.txt'.format(p.proj_name))
data = []
with open(fname) as values:
for column in zip(*[line for line in csv.reader(values, dialect="excel-tab")]):
data.append(column)
prds = data[0]
thetas = data[1]
phis = data[2]
psis = data[3]
xs = data[4]
ys = data[5]
zs = data[6]
xyz = np.column_stack((xs,ys,zs))
angs = np.column_stack((thetas,phis))
dists = [] #distances between current and all tesselated points
indexes = []
idx = 0
# find nearest neighbor (pythagorean):
for i,j,k in xyz:
x1 = float(i)
y1 = float(j)
z1 = float(k)
d = np.sqrt( (x1-x0)**2 + (y1-y0)**2 + (z1-z0)**2 )
if not dists:
dists.append(d)
indexes.append(idx)
if dists:
if d < np.amin(dists):
dists.append(d)
indexes.append(idx)
idx += 1
# update view:
current = self.scene3.mlab.view(figure=Mayavi_Rho.fig3) #grab current distance
self.scene3.mlab.view(azimuth=float(phis[indexes[-1]]),
elevation=float(thetas[indexes[-1]]),
distance=current[2],
roll=float(phis[indexes[-1]])+270,
#reset_roll=False, #ZULU: still need to correct volume in-plane rotation to match image's
figure=Mayavi_Rho.fig3)
P4.entry_PrD.setValue(indexes[-1]+1) #update PrD and thus topos
self.phi = '%s%s' % (round(float(phis[indexes[-1]]),2), u"\u00b0")
self.theta = '%s%s' % (round(float(thetas[indexes[-1]]),2), u"\u00b0")
Mayavi_Rho.fig3.scene.scene.interactor.add_observer('LeftButtonPressEvent', press_callback)
Mayavi_Rho.fig3.scene.scene.interactor.add_observer('EndInteractionEvent', release_callback)
# live update of Euler angles:
def press_callback_Eul(vtk_obj, event): #left mouse down callback
self.click_on_Eul = 1
def hold_callback_Eul(vtk_obj, event): #camera rotate callback
if self.click_on_Eul > 0:
viewS2 = self.scene3.mlab.view(figure=Mayavi_Rho.fig3)
self.phi = '%s%s' % (round(viewS2[0],2), u"\u00b0")
self.theta = '%s%s' % (round(viewS2[1],2), u"\u00b0")
def release_callback_Eul(vtk_obj, event): #left mouse release callback
if self.click_on_Eul == 1:
self.click_on_Eul = 0
Mayavi_Rho.fig3.scene.scene.interactor.add_observer('LeftButtonPressEvent', press_callback_Eul)
Mayavi_Rho.fig3.scene.scene.interactor.add_observer('InteractionEvent', hold_callback_Eul)
Mayavi_Rho.fig3.scene.scene.interactor.add_observer('EndInteractionEvent', release_callback_Eul)
title = Str
def _title_default(self):
return 'Electrostatic Potential Map'
view = View(VGroup(
Group(
Item('title',springy=False,show_label=False,style='readonly',
style_sheet='*{font: "Arial"; font-size:12px; qproperty-alignment:AlignCenter}'),
Item('scene3', editor = SceneEditor(scene_class=MayaviScene),
height=1, width=1, show_label=False, springy=True),
),
VGroup(
HGroup(
Item('phi',springy=True,show_label=True,#style='readonly',
editor=TextEditor(evaluate=float),
enabled_when='phi == float(0)', #i.e., never
),
Item('theta',springy=True,show_label=True,#style='readonly',
editor=TextEditor(evaluate=float),
enabled_when='phi == float(0)', #i.e., never
),
),
show_border=False, orientation='vertical'
),
),
resizable=True,
)
# =============================================================================
# GUI tab 1:
# =============================================================================
class P1(QtGui.QWidget):
# user inputs:
user_volume = ''
user_mask = ''
df_vol = ''
user_stack = ''
user_alignment = ''
user_name = time_init
user_directory = pyDir
# full S2 angles:
x1 = []
y1 = []
z1 = []
d1 = []
# thresholded S2 angles:
x2 = []
y2 = []
z2 = []
# S2 anchor nodes:
x3 = []
y3 = []
z3 = []
a3 = []
# S2 trash nodes:
x4 = []
y4 = []
z4 = []
a4 = []
# remaining parameters:
user_pixel = 0.01
user_diameter = 0.01
user_resolution = 0.01
user_aperture = 1
user_shannon = 0.0
user_width = 0.0
S2rescale = 1.0
relion_data = True #True for .star (ZULU: need to update this to instead correspond to different RELION versions; 'False' no longer used)
q = []
S2 = []
df = []
CG = []
shifts = []
all_PrDs = []
all_occ = []
all_phi = []
all_theta = []
all_psi = []
S2_density_all = [5,10,25,50,100,250,500,1000,10000,100000] #needs to match Mayavi_S2.S2_density_all!
def __init__(self, parent=None):
super(P1, self).__init__(parent)
layout = QtGui.QGridLayout(self)
layout.setContentsMargins(20,20,20,20) #W,N,E,S
layout.setSpacing(10)
# average volume input:
def choose_avgVol():
fileName = QtGui.QFileDialog.getOpenFileName(self, 'Choose Data File', '',
('Data Files (*.mrc)'))[0]
#('MRC (*.mrc);;SPI (*.spi)'))
#('All files (*.*);;
if fileName:
P1.entry_avgVol.setDisabled(False)
P1.entry_avgVol.setText(fileName)
P1.entry_avgVol.setDisabled(True)
# change volume data:
P1.user_volume = fileName
with mrcfile.open(P1.user_volume, mode='r+') as mrc:
mrc.header.mapc = 1
mrc.header.mapr = 2
mrc.header.maps = 3
P1.df_vol = mrc.data
else:
P1.entry_avgVol.setDisabled(False)
P1.entry_avgVol.setText('Filename')
P1.entry_avgVol.setDisabled(True)
P1.user_volume = ''
p.avg_vol_file = P1.user_volume
self.label_edge1 = QtGui.QLabel('')
self.label_edge1.setMargin(0)
self.label_edge1.setLineWidth(1)
self.label_edge1.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)
layout.addWidget(self.label_edge1, 0, 0, 1, 6)
self.label_edge1.show()
self.label_edge1a = QtGui.QLabel('')
self.label_edge1a.setMargin(0)
self.label_edge1a.setLineWidth(1)
self.label_edge1a.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Sunken)
layout.addWidget(self.label_edge1a, 0, 0, 1, 1)
self.label_edge1a.show()
self.label_avgVol = QtGui.QLabel('Average Volume')
self.label_avgVol.setFont(font_standard)
self.label_avgVol.setMargin(20)
self.label_avgVol.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)
layout.addWidget(self.label_avgVol, 0, 0, 1, 1)
self.label_avgVol.show()
P1.entry_avgVol = QtGui.QLineEdit('Filename')
P1.entry_avgVol.setDisabled(True)
layout.addWidget(P1.entry_avgVol, 0, 1, 1, 4)
P1.entry_avgVol.show()
self.button_browse1 = QtGui.QPushButton(' Browse ', self)
self.button_browse1.clicked.connect(choose_avgVol)
self.button_browse1.setToolTip('Accepted format: <i>.mrc</i>')
layout.addWidget(self.button_browse1, 0, 5, 1, 1, QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.button_browse1.show()
# alignment input:
def choose_align():
fileName = QtGui.QFileDialog.getOpenFileName(self, 'Choose Data File', '',
('Data Files (*.star)'))[0]
#('All files (*.*)'))
if fileName:
if fileName.endswith('.star'):
P1.relion_data = True
else:
P1.relion_data = False
p.relion_data = P1.relion_data
P1.entry_align.setDisabled(False)
P1.entry_align.setText(fileName)
P1.entry_align.setDisabled(True)
P1.user_alignment = fileName
else:
P1.entry_align.setDisabled(False)
P1.entry_align.setText('Filename')
P1.entry_align.setDisabled(True)
P1.user_alignment = ''
p.align_param_file = P1.user_alignment
self.label_edge3 = QtGui.QLabel('')
self.label_edge3.setMargin(20)
self.label_edge3.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)
layout.addWidget(self.label_edge3, 1, 0, 1, 6)
self.label_edge3.show()
self.label_edge3a = QtGui.QLabel('')
self.label_edge3a.setMargin(20)
self.label_edge3a.setLineWidth(1)
self.label_edge3a.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Sunken)
layout.addWidget(self.label_edge3a, 1, 0, 1, 1)
self.label_edge3a.show()
self.label_align = QtGui.QLabel('Alignment File')
self.label_align.setFont(font_standard)
self.label_align.setMargin(20)
self.label_align.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)
layout.addWidget(self.label_align, 1, 0, 1, 1)
self.label_align.show()
P1.entry_align = QtGui.QLineEdit('Filename')
P1.entry_align.setDisabled(True)
layout.addWidget(P1.entry_align, 1, 1, 1, 4)
P1.entry_align.show()
self.button_browse3 = QtGui.QPushButton(' Browse ', self)
self.button_browse3.clicked.connect(choose_align)
self.button_browse3.setToolTip('Accepted format: <i>.star</i>')
layout.addWidget(self.button_browse3, 1, 5, 1, 1, QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.button_browse3.show()
# image stack input:
def choose_imgStack():
fileName = QtGui.QFileDialog.getOpenFileName(self, 'Choose Data File', '',
('Data Files (*.mrcs)'))[0]
if fileName:
P1.entry_imgStack.setDisabled(False)
P1.entry_imgStack.setText(fileName)
P1.entry_imgStack.setDisabled(True)
P1.user_stack = fileName
if fileName.endswith('.mrcs'): #relion file format
P1.relion_data = True
mrc = mrcfile.mmap(fileName, mode='r+')
mrc.set_image_stack()
p.nPix = np.shape(mrc.data[0])[0]
else:
P1.entry_imgStack.setDisabled(False)
P1.entry_imgStack.setText('Filename')
P1.entry_imgStack.setDisabled(True)
P1.user_stack = ''
p.img_stack_file = P1.user_stack
self.label_edge2 = QtGui.QLabel('')
self.label_edge2.setMargin(20)
self.label_edge2.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)
layout.addWidget(self.label_edge2, 2, 0, 1, 6)
self.label_edge2.show()
self.label_edge2a = QtGui.QLabel('')
self.label_edge2a.setMargin(20)
self.label_edge2a.setLineWidth(1)
self.label_edge2a.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Sunken)
layout.addWidget(self.label_edge2a, 2, 0, 1, 1)
self.label_edge2a.show()
self.label_imgStack = QtGui.QLabel('Image Stack')
self.label_imgStack.setFont(font_standard)
self.label_imgStack.setMargin(5)
self.label_imgStack.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)
layout.addWidget(self.label_imgStack, 2, 0, 1, 1)
self.label_imgStack.show()
P1.entry_imgStack = QtGui.QLineEdit('Filename')
P1.entry_imgStack.setDisabled(True)
layout.addWidget(P1.entry_imgStack, 2, 1, 1, 4)
P1.entry_imgStack.show()
self.button_browse2 = QtGui.QPushButton(' Browse ', self)
self.button_browse2.clicked.connect(choose_imgStack)
self.button_browse2.setToolTip('Accepted format: <i>.mrcs</i>')
layout.addWidget(self.button_browse2, 2, 5, 1, 1, QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.button_browse2.show()
# mask volume input:
def choose_maskVol():
fileName = QtGui.QFileDialog.getOpenFileName(self, 'Choose Data File', '',
('Data Files (*.mrc)'))[0]
if fileName:
P1.entry_maskVol.setDisabled(False)
P1.entry_maskVol.setText(fileName)
P1.entry_maskVol.setDisabled(True)
# change volume data:
P1.user_mask = fileName
else:
P1.entry_maskVol.setDisabled(False)
P1.entry_maskVol.setText('Filename')
P1.entry_maskVol.setDisabled(True)
P1.user_mask = ''
p.mask_vol_file = P1.user_mask
self.label_edgeM = QtGui.QLabel('')
self.label_edgeM.setMargin(0)
self.label_edgeM.setLineWidth(1)
self.label_edgeM.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Sunken)
layout.addWidget(self.label_edgeM, 3, 0, 1, 6)
self.label_edgeM.show()
self.label_edgeMa = QtGui.QLabel('')
self.label_edgeMa.setMargin(0)
self.label_edgeMa.setLineWidth(1)
self.label_edgeMa.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Sunken)
layout.addWidget(self.label_edgeMa, 3, 0, 1, 1)
self.label_edgeMa.show()
self.label_maskVol = QtGui.QLabel('Mask Volume')
self.label_maskVol.setFont(font_standard)
self.label_maskVol.setMargin(20)
self.label_maskVol.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)
layout.addWidget(self.label_maskVol, 3, 0, 1, 1)
self.label_maskVol.show()
P1.entry_maskVol = QtGui.QLineEdit('Filename')
P1.entry_maskVol.setDisabled(True)
layout.addWidget(P1.entry_maskVol, 3, 1, 1, 4)
P1.entry_maskVol.show()
self.button_browseM = QtGui.QPushButton(' Browse ', self)
self.button_browseM.clicked.connect(choose_maskVol)
self.button_browseM.setToolTip('Accepted format: <i>.mrc</i>')
layout.addWidget(self.button_browseM, 3, 5, 1, 1, QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.button_browseM.show()
def choose_name():
text, ok = QtGui.QInputDialog.getText(self, 'ManifoldEM Project Name', 'Enter project name:')
if ok: