-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqt_gui.py
1113 lines (791 loc) · 35.1 KB
/
qt_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
#!/usr/bin/env python2.5
#
# Written (W) 2011-2014 Christian Widmer
# Copyright (C) 2011-2014 Max-Planck-Society, MSKCC, TU-Berlin
"""
@author: Christian Widmer
@summary: Visualization of the fitted ellipses using PySide and mayavi2
"""
# First, and before importing any Enthought packages, set the ETS_TOOLKIT
# environment variable to qt4, to tell Traits that we will use Qt.
import os
import cPickle
os.environ['ETS_TOOLKIT'] = 'qt4'
# To be able to use PySide or PySide and not run in conflicts with traits,
# we need to import QtGui and QtCore from pyface.qt
#from pyface.qt import QtGui, QtCore
# Alternatively, you can bypass this line, but you need to make sure that
# the following lines are executed before the import of PyQT:
#import sip
#sip.setapi('QString', 1)
from PySide import QtGui, QtCore
import scipy.stats
from collections import namedtuple
from traits.api import HasTraits, Instance, on_trait_change, Tuple, Dict #List, Int, Array
from traitsui.api import View, Item
from mayavi.core.ui.api import MayaviScene, MlabSceneModel, SceneEditor
import fit_ellipse_stack
import fit_ellipse_stack_conic
#import fit_cone_stack_cvxpy
from fit_sphere import fit_sphere_stack
from data_processing import artificial_data, load_tif, threshold_volume #, generate_sphere_full
from volume_slicer_simple import SimpleSlicerQWidget
from histogram_widget import HistogramQWidget
from batch_dialog import BatchDialog
from preproc_dialog import PreprocDialog
################################################################################
#The actual visualization
class Visualization(HasTraits):
scene = Instance(MlabSceneModel, ())
data = Tuple()
#data = Array()
ellipse_stack = Dict() #List()
data_plot = None
stack_plot = None
@on_trait_change('scene.activated')
def update_plot(self):
# This function is called when the view is opened. We don't
# populate the scene when the view is not yet open, as some
# VTK features require a GLContext.
print "init stuff"
# init data plot
self.data_plot = self.scene.mlab.test_contour3d()
#self.scene.mlab.points3d(x,y,z,v,colormap="copper", scale_factor=.0025, opacity=0.4)
#v = numpy.ones((3,3,3))
#self.data_plot = self.scene.mlab.contour3d(v, opacity=0.2)
# init ellipse stack plot
#dx = dy = dz = dv = []
#self.stack_plot = self.scene.mlab.points3d(dx,dy,dz,dv,colormap="copper", scale_factor=.01, opacity=0.6)
@on_trait_change('ellipse_stack')
def update_ellipse_stack(self):
"""
plot ellipse stack
"""
print "updating ellipse stack"
n = 50
# sample data
for e in self.ellipse_stack.values():
dat = e.sample_equidistant(n)
dx = dat[0]
dy = dat[1]
dz = [e.cz]*(n+1)
dv = [25]*(n+1)
self.scene.mlab.points3d(dx,dy,dz,dv,colormap="copper", scale_factor=.015, opacity=0.5)
print "updating ellipse stack DONE."
# update data source
# TODO keep list of plots
#self.stack_plot.mlab_source.set(x=dx, y=dy, z=dz, s=dv)
@on_trait_change('data')
def update_data(self):
"""
update ellipse stack
list of available colormaps (http://github.enthought.com/mayavi/mayavi/mlab.html):
accent flag hot pubu set2
autumn gist_earth hsv pubugn set3
black-white gist_gray jet puor spectral
blue-red gist_heat oranges purd spring
blues gist_ncar orrd purples summer
bone gist_rainbow paired rdbu winter
brbg gist_stern pastel1 rdgy ylgnbu
bugn gist_yarg pastel2 rdpu ylgn
bupu gnbu pink rdylbu ylorbr
cool gray piyg rdylgn ylorrd
copper greens prgn reds
dark2 greys prism set1
"""
print "updating data"
self.scene.mlab.clf()
# update data source
#self.data_plot = self.scene.mlab.contour3d(self.data[0], self.data[1], self.data[2], self.data[3], opacity=0.2)
#self.data_plot = self.scene.mlab.contour3d(self.data[0], self.data[1], self.data[2], self.data[3], opacity=0.2)
#self.data_plot = self.scene.mlab.contour3d(self.data, opacity=0.2)
# look at: http://github.enthought.com/mayavi/mayavi/mlab_changing_object_looks.html
#from mayavi import mlab
#self.data_plot = mlab.pipeline.volume(mlab.pipeline.scalar_field(self.volume))
self.data_plot = self.scene.mlab.points3d(self.data[0], self.data[1], self.data[2], self.data[3], colormap="Reds", scale_factor=.001, opacity=0.2, scale_mode="scalar")
#self.data_plot.mlab_source.set(scalars=self.data, opacity=0.1)
print "updating data done."
#TODO fix
#@on_trait_change('ellipsoid')
def plot_ellipsoid(self, cx, cy, cz, rx, ry, rz):
"""
plot ellispoid given three center coordinates (cx, cy, cz)
and three radii (rx, ry, rz)
"""
n = 15
# debug
#######################################
x = [cx]
y = [cy]
z = [cz]
v = [100]
print "x,y,z=%f,%f,%f" % (cx, cy, cz)
self.scene.mlab.points3d(x,y,z,v,colormap="copper", scale_factor=.025, opacity=0.4)
#######################################
pi = numpy.pi
theta = numpy.linspace (0, 2 * pi, n + 1);
phi = numpy.linspace (-pi / 2, pi / 2, n + 1);
[theta, phi] = numpy.meshgrid (theta, phi);
lx = rx * numpy.cos(phi) * numpy.cos(theta) + cx;
ly = ry * numpy.cos(phi) * numpy.sin(theta) + cy;
lz = rz * numpy.sin(phi) + cz;
lv = numpy.ones(lz.shape)
#self.scene.mlab.plot3d(lx.flatten(), ly.flatten(), lz.flatten(), lv.flatten(), opacity=0.3)
#self.scene.mlab.contour3d(lx, ly, lz, lv, opacity=0.3)
self.scene.mlab.mesh(lx, ly, lz, scalars=lv, opacity=0.2, representation="wireframe", line_width=1.0)
# the layout of the dialog screated
view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene),
height=450, width=500, show_label=False),
resizable=True # We need this to resize with the parent widget
)
################################################################################
# The QWidget containing the visualization, this is pure PySide code.
class VolumeSlicerQWidget(QtGui.QWidget):
"""
QT wrapper for mayavi2
"""
def __init__(self, parent=None):
"""
setup GUI
"""
QtGui.QWidget.__init__(self, parent)
self.my_layout = QtGui.QVBoxLayout(self)
#self.my_layout.setMargin(0)
self.my_layout.setSpacing(0)
x, y, z, i, volume = artificial_data()
self.slicer = VolumeSlicer(data=volume)
# The edit_traits call will generate the widget to embed.
self.ui = self.slicer.edit_traits(parent=self, kind='subpanel').control
self.my_layout.addWidget(self.ui)
self.ui.setParent(self)
def update_dataset(self, dataset):
"""
update plot
"""
#TODO it would be preferable to just update the data
self.slicer.data = dataset.volume
return ""
self.ui.setParent(None)
print "VolumeSlicerQWidget: update dataset"
self.slicer = VolumeSlicer(data=dataset.volume)
# The edit_traits call will generate the widget to embed.
self.ui = self.slicer.edit_traits(parent=self, kind='subpanel').control
#layout.addWidget(self.ui)
self.ui.setParent(self)
self.my_layout.addWidget(self.ui)
self.ui.setParent(self)
#if dataset.volume != None:
# self.slicer.data = dataset.volume
#if dataset.stack != None:
# self.slicer.ellipse_stack = dataset.stack
def update_ellipse_stack(self, dataset):
"""
dedicated method to update stack fit
"""
if dataset.stack != None:
self.slicer.ellipse_stack = dataset.stack
class MayaviQWidget(QtGui.QWidget):
"""
QT wrapper for 3d plot
"""
def __init__(self, parent=None):
"""
setup GUI
"""
QtGui.QWidget.__init__(self, parent)
layout = QtGui.QVBoxLayout(self)
#layout.setMargin(0)
layout.setSpacing(0)
self.visualization = Visualization()
# If you want to debug, beware that you need to remove the Qt
# input hook.
#QtCore.pyqtRemoveInputHook()
#import pdb ; pdb.set_trace()
#QtCore.pyqtRestoreInputHook()
# The edit_traits call will generate the widget to embed.
self.ui = self.visualization.edit_traits(parent=self,
kind='subpanel').control
layout.addWidget(self.ui)
self.ui.setParent(self)
def update_dataset(self, dataset):
"""
update plot
"""
print "MayaviQWidget: update dataset"
if dataset.volume != None:
self.visualization.data = tuple(dataset.points)
#self.visualization.data = dataset.volume
self.visualization.ellipse_stack = dataset.stack
class ControlWidget(QtGui.QWidget):
"""
widget to hold control buttons
"""
# new style signals
directoryChanged = QtCore.Signal(str)
superDirectoryChanged = QtCore.Signal(str)
def __init__(self):
super(ControlWidget, self).__init__()
self.initUI()
self.directory = None
self.super_directory = None
def initUI(self):
"""
set up gui elements and layout
"""
# set up layout
self.layout = QtGui.QVBoxLayout(self)
self.layout.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignLeading)
#self.layout.setMargin(0)
self.layout.setSpacing(0)
# add buttons
self.button_preproc = QtGui.QPushButton('Preprocess', self)
self.button_preproc.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_preproc)
self.button_dat = QtGui.QPushButton('Add Dataset', self)
self.button_dat.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_dat)
self.button_all_dat = QtGui.QPushButton('Add all Datasets', self)
self.button_all_dat.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_all_dat)
self.button_load = QtGui.QPushButton('Load', self)
self.button_load.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_load)
self.button_save = QtGui.QPushButton('Save', self)
self.button_save.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_save)
#self.button_fit = QtGui.QPushButton('Fit ellipsoid', self)
#self.button_fit.setFocusPolicy(QtCore.Qt.NoFocus)
#self.layout.addWidget(self.button_fit)
self.button_fit_stack = QtGui.QPushButton('Fit ellipse stack (squared)', self)
self.button_fit_stack.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_fit_stack)
self.button_fit_insensitive = QtGui.QPushButton('Fit ellipse stack (abs)', self)
self.button_fit_insensitive.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_fit_insensitive)
self.button_fit_sphere_stack = QtGui.QPushButton('Fit circle stack (abs)', self)
self.button_fit_sphere_stack.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_fit_sphere_stack)
self.button_batch = QtGui.QPushButton('Batch process', self)
self.button_batch.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_batch)
self.button_eval = QtGui.QPushButton('Evaluate', self)
self.button_eval.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_eval)
self.button_export = QtGui.QPushButton('Export', self)
self.button_export.setFocusPolicy(QtCore.Qt.NoFocus)
self.layout.addWidget(self.button_export)
#'Adapt Radius',
self.spin_radius_label = QtGui.QLabel("Radius Offset", self)
self.layout.addWidget(self.spin_radius_label)
self.spin_radius = QtGui.QDoubleSpinBox(self)
self.spin_radius.setMinimum(-10.0)
self.spin_radius.setMaximum(10.0)
self.spin_radius.setFocusPolicy(QtCore.Qt.NoFocus)
self.spin_radius.setSingleStep(0.2)
self.layout.addWidget(self.spin_radius)
# connect signals
self.connect(self.button_dat, QtCore.SIGNAL('clicked()'), self.showDialog)
self.connect(self.button_all_dat, QtCore.SIGNAL('clicked()'), self.select_super_dir)
self.setFocus()
self.setWindowTitle('Select Files')
#self.setGeometry(300, 300, 350, 80)
def showDialog(self):
self.directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory")
self.directoryChanged.emit(str(self.directory))
def select_super_dir(self):
self.super_directory = QtGui.QFileDialog.getExistingDirectory(self, "Select Directory")
self.superDirectoryChanged.emit(self.super_directory)
def update_dataset(self, dataset):
"""
wrapper for updated dataset
"""
# set silent
self.spin_radius.blockSignals(True)
self.spin_radius.setValue(dataset.radius_offset)
self.spin_radius.blockSignals(False)
class TableWidget(QtGui.QTableWidget):
"""
widget class to hold table information (including the data directories)
"""
directoryChanged = QtCore.Signal(object)
def __init__(self):
super(TableWidget, self).__init__()
self.datasets = []
self.id_to_row = {}
self.initUI()
# provide clean interface to outside world
self.connect(self, QtCore.SIGNAL('itemClicked(QTableWidgetItem*)'), self.emit_dataset)
def initUI(self):
"""
set up GUI
"""
self.setColumnCount(7)
self.setHorizontalHeaderLabels(["file name", "radius", "threshold", "num pixels", "area (micro m^2)", "total intensity", "intensity per area"]);
self.horizontalHeader().setResizeMode(0, QtGui.QHeaderView.Stretch);
self.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) #select only rows
self.setShowGrid(1)
def add_dataset(self, dat):
"""
appends dat to dataset and adds new table item
"""
fn = dat.split("/")[-1]
item = QtGui.QTableWidgetItem(fn)
item.dataset = dat
row = self.rowCount()
# save mapping
self.id_to_row[dat] = row
self.insertRow(row)
self.setItem(row, 0, item)
self.setItem(row, 1, QtGui.QTableWidgetItem("-"))
self.setItem(row, 2, QtGui.QTableWidgetItem("-"))
self.setItem(row, 3, QtGui.QTableWidgetItem("-"))
self.setItem(row, 4, QtGui.QTableWidgetItem("-"))
self.setItem(row, 5, QtGui.QTableWidgetItem("-"))
self.setItem(row, 6, QtGui.QTableWidgetItem("-"))
self.datasets.append(dat)
self.selectRow(row)
def emit_dataset(self, item):
"""
re-emit only the directory name
"""
print "item", item
self.directoryChanged.emit(self.datasets[item.row()])
def update_evaluation(self, dataset):
"""
set new eval data
"""
print "table widget: update evaluation"
evaluation = dataset.evaluation
if evaluation:
row = self.id_to_row[dataset.tif_dir]
print "current row", row
self.item(row, 1).setText("%.2f" % dataset.radius_offset)
self.item(row, 2).setText("%.2f" % dataset.threshold)
self.item(row, 3).setText("%d" % evaluation.total_num_pixels)
self.item(row, 4).setText("%.2f" % evaluation.total_area_in_micro_m)
self.item(row, 5).setText("%.2f" % evaluation.total_intensity)
self.item(row, 6).setText("%.2f" % evaluation.total_intensity_per_area)
class MainWidget(QtGui.QTreeWidget):
"""
main widget
"""
# define signals
newKey = QtCore.Signal(str)
activeDatasetChanged = QtCore.Signal(object)
activeDatasetEvaluated = QtCore.Signal(object)
def __init__(self):
"""
setup up main gui layout
"""
#####
# non-gui variables
#####
self.datasets = {}
self.active_dataset = None
#
super(MainWidget, self).__init__()
self.setWindowTitle("Cell tracker")
# define a "complex" layout to test the behaviour
layout = QtGui.QGridLayout(self)
# set up gui
label_slicer = QtGui.QLabel(self)
label_slicer.setText("Volume Slicer")
label_slicer.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
layout.addWidget(label_slicer, 0, 0)
slicer_widget = SimpleSlicerQWidget(self)
layout.addWidget(slicer_widget, 1, 0)
label_view = QtGui.QLabel(self)
label_view.setText("Volume View")
label_view.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter)
layout.addWidget(label_view, 0, 1)
mayavi_widget = MayaviQWidget(self)
layout.addWidget(mayavi_widget, 1, 1)
table_widget = TableWidget()
layout.addWidget(table_widget, 2, 0)
hist_widget = HistogramQWidget()
layout.addWidget(hist_widget, 2, 1)
control_widget = ControlWidget()
layout.addWidget(control_widget, 2, 2)
#control_widget.show()
control_widget.directoryChanged.connect(self.add_dataset)
self.activeDatasetChanged.connect(mayavi_widget.update_dataset)
self.activeDatasetChanged.connect(slicer_widget.update_dataset)
self.activeDatasetChanged.connect(hist_widget.update_dataset)
self.activeDatasetChanged.connect(control_widget.update_dataset)
self.newKey.connect(table_widget.add_dataset)
table_widget.directoryChanged.connect(self.change_active_dataset)
#table_widget.direc
self.connect(hist_widget, QtCore.SIGNAL('thresholdChanged(double)'), self.update_threshold)
self.activeDatasetEvaluated.connect(table_widget.update_evaluation)
# create deep links to control widget (simple)
#self.connect(control_widget.button_fit, QtCore.SIGNAL('clicked()'), mayavi_widget.update_ellipsoid)
self.connect(control_widget.button_fit_sphere_stack, QtCore.SIGNAL('clicked()'), self.update_stack)
self.connect(control_widget.button_fit_stack, QtCore.SIGNAL('clicked()'), self.update_ellipse_stack)
self.connect(control_widget.button_fit_insensitive, QtCore.SIGNAL('clicked()'), self.update_ellipse_stack_eps)
self.connect(control_widget.button_load, QtCore.SIGNAL('clicked()'), self.load)
self.connect(control_widget.button_eval, QtCore.SIGNAL('clicked()'), self.evaluate)
self.connect(control_widget.button_export, QtCore.SIGNAL('clicked()'), self.export)
self.connect(control_widget.button_batch, QtCore.SIGNAL('clicked()'), self.batch)
self.connect(control_widget.button_preproc, QtCore.SIGNAL('clicked()'), self.preproc)
self.connect(control_widget.button_save, QtCore.SIGNAL('clicked()'), self.save)
self.connect(control_widget.spin_radius, QtCore.SIGNAL('valueChanged(double)'), self.update_radius_offset)
control_widget.superDirectoryChanged.connect(self.add_all_datasets)
#self.add_all_datasets(super_dir)
self.show()
def add_all_datasets(self, super_dir):
"""
appends all directories in super_dir
"""
# path will come with forward slashes from PyQT
super_dir = str(super_dir)
directories = [super_dir + "/" + dat for dat in os.listdir(super_dir) if os.path.isdir(super_dir + "/" + dat)]
directories.sort()
for dat in directories:
contains_tiffs = False
for f in os.listdir(dat):
if f.endswith("tif"):
contains_tiffs = True
break
if contains_tiffs:
self.add_dataset(dat)
else:
print "directorty %s does not contain tiffs, skipping" % (dat)
def add_dataset(self, tif_dir):
"""
slot add_dataset
"""
print "adding dataset", tif_dir
dataset = Dataset(tif_dir)
dataset.load_data()
self.datasets[tif_dir] = dataset
self.newKey.emit(tif_dir)
# notify observers
self.change_active_dataset(tif_dir)
def change_active_dataset(self, key):
"""
emits signal that indicates that the currently active dataset was changed
"""
self.active_dataset = self.datasets[key]
self.activeDatasetChanged.emit(self.active_dataset)
def update_stack(self):
"""
invoke fit, call update
"""
print "updating stack"
self.active_dataset.fit_stack("circle")
self.activeDatasetChanged.emit(self.active_dataset)
def update_ellipse_stack(self):
"""
invoke fit, call update
"""
print "updating stack"
self.active_dataset.fit_stack("squared")
self.activeDatasetChanged.emit(self.active_dataset)
def update_ellipse_stack_eps(self):
"""
invoke fit, call update
"""
print "updating stack"
self.active_dataset.fit_stack("eps")
self.activeDatasetChanged.emit(self.active_dataset)
def update_threshold(self, thres):
"""
emits signal that indicates that the currently active dataset was changed
"""
print "updating threshold"
self.active_dataset.update_threshold(thres)
self.activeDatasetChanged.emit(self.active_dataset)
def update_radius_offset(self, offset):
"""
emits signal that indicates that the currently active dataset was changed
"""
print "updating threshold"
self.active_dataset.update_radius_offset(offset)
self.activeDatasetChanged.emit(self.active_dataset)
def evaluate(self):
"""
emits signal that indicates that the currently active dataset was changed
"""
self.active_dataset.evaluate()
self.activeDatasetEvaluated.emit(self.active_dataset)
def export(self):
"""
emits signal that indicates that the currently active dataset was changed
"""
dialog = QtGui.QFileDialog()
#dialog.setFileMode(QtGui.QFileDialog.ShowDirsOnly)
dir_name = str(dialog.getExistingDirectory(self, 'Select Directory'))
file_name = dir_name + "/" + "export.csv"
f = file(file_name, "w")
f.write("file name, radius, threshold, num pixels, area (micro m^2), total intensity, intensity per area\n")
for dataset_path, dataset in self.datasets.items():
#dat_name = dataset_path.split(os.sep)[-1]
dat_name = dataset_path.split("/")[-1]
line = dat_name + ", "
line += str(dataset.radius_offset) + ", "
line += str(dataset.threshold) + ", "
if dataset.evaluation != None:
line += str(dataset.evaluation.total_num_pixels) + ", "
line += str(dataset.evaluation.total_area_in_micro_m) + ", "
line += str(dataset.evaluation.total_intensity) + ", "
line += str(dataset.evaluation.total_intensity_per_area)
# write separate file
#inner_file_name = dir_name + os.sep + dat_name + ".csv"
inner_file_name = dir_name + "/" + dat_name + ".csv"
inner_f = file(inner_file_name, "w")
inner_f.write("layer_id, area_micro_m, intensity\n")
print "writing file", inner_file_name
for layer in xrange(dataset.evaluation.num_layers):
area = dataset.evaluation.layer_area_in_micro_m[layer]
intensity = dataset.evaluation.layer_intensity[layer]
inner_f.write("%i, %f, %f\n" % (layer + 1, area, intensity))
inner_f.close()
line += "\n"
f.write(line)
f.close()
print "file successfully written to", file_name
def save(self):
"""
emits signal that indicates that the currently active dataset was changed
"""
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.AnyFile)
file_name = str(dialog.getSaveFileName(self, 'Save project', "cell_fit.proj")[0])
if not file_name == "":
try:
f = file(file_name, "w")
self.datasets = cPickle.dump(self.datasets, f)
f.close()
except Exception, detail:
print "error on saving file", file_name
print detail
print "successfully saved project to", file_name
def load(self):
"""
emits signal that indicates that the currently active dataset was changed
"""
dialog = QtGui.QFileDialog()
file_name = str(dialog.getOpenFileName(self, 'Load project')[0])
if not file_name == "":
try:
f = file(file_name)
#self.datasets = fix_legacy_paths(cPickle.load(f))
self.datasets = cPickle.load(f)
for tif_dir, dataset in self.datasets.items():
self.newKey.emit(tif_dir)
self.active_dataset = dataset
self.activeDatasetChanged.emit(self.active_dataset)
self.activeDatasetEvaluated.emit(self.active_dataset)
f.close()
except Exception, detail:
print "error on loading file", file_name
print detail
print "successfully loaded project from", file_name
def batch(self):
"""
performs batch processing with settings from batch_dialog
"""
dlg = BatchDialog()
if dlg.exec_():
values = dlg.getValues()
print "batch processing %i files" % (len(self.datasets))
print "parameters:", values
for key, d in self.datasets.items():
print "batch processing", key
try:
# preproc data
d.threshold = scipy.stats.scoreatpercentile(d.red_channel.flatten(), values["percentile"])
d.std_cut = values["std_cut"]
d.volume_to_points()
# do actual processing
d.fit_stack(values["method"])
# update plots
self.active_dataset = d
self.activeDatasetChanged.emit(self.active_dataset)
self.active_dataset.update_radius_offset(values["radius_offset"])
self.active_dataset.evaluate()
# update eval
self.activeDatasetEvaluated.emit(self.active_dataset)
except Exception, detail:
print "problem encountered when when analyzing", key
print detail
print "batch processing done."
def preproc(self):
"""
performs preproc processing with settings from preproc_dialog
"""
dlg = PreprocDialog()
if dlg.exec_():
values = dlg.getValues()
def fix_legacy_paths(dataset):
"""
removes backslashes from file names
"""
new_dat = {}
for key, dat in dataset.items():
if "\\" in key:
print "replacing \\ with / in", key
new_key = key.replace("\\","/")
new_dat[new_key] = dat
return new_dat
# define class Data
Data = namedtuple("Data", ["x", "y", "z", "i"])
class EvaluationData(object):
"""
class to hold information about evaluation
"""
def __init__(self):
# evaluation
self.total_num_pixels = 0
self.total_area_in_micro_m = 0.0
self.total_intensity = 0.0
self.total_intensity_per_area = 0.0
self.layer_num_pixels = []
self.layer_area_in_micro_m = []
self.layer_intensity = []
self.layer_intensity_per_area = []
self.num_layers = 0
def add_layer(self, num_pixels, intensity):
area = float(num_pixels) * 0.04626801
self.layer_num_pixels.append(num_pixels)
self.layer_area_in_micro_m.append(area)
self.layer_intensity.append(intensity)
self.layer_intensity_per_area.append(float(intensity)/float(area))
# update totals
self.total_num_pixels += num_pixels
self.total_area_in_micro_m += area
self.total_intensity += intensity
self.total_intensity_per_area = float(self.total_intensity) / float(self.total_area_in_micro_m)
self.num_layers += 1
class Dataset(object):
"""
class to hold information about one dataset
"""
def __init__(self, tif_dir):
"""
set up dataset
"""
self.tif_dir = tif_dir
self.threshold = 255
self.std_cut = 3.0
# set defaults
self.clear()
def clear(self):
"""
set defaults
"""
self.red_channel = None
self.green_channel = None
self.points = None
self.volume = None
self.is_loaded = False
self.stack = {}
self.ellipsoid = None
self.radius_offset = 0
self.evaluation = None
def load_data(self):
"""
load raw data
"""
self.red_channel = load_tif(self.tif_dir, "w617")
self.green_channel = load_tif(self.tif_dir, "w528")
#x, y, z, i, vol = generate_sphere_full()
#print "WARNING: DEBUG"
#self.green_channel = vol
# set threshold to some high percentile by default
self.threshold = scipy.stats.scoreatpercentile(self.red_channel.flatten(), 93)
self.volume_to_points()
return self
def volume_to_points(self):
"""
convert volume to points
"""
x, y, z, i, vol = threshold_volume(self.red_channel, self.threshold, self.std_cut)
#print "WARNING DEBUGGIN"
#x, y, z, i, vol = artificial_data() #artificial_data()
self.points = Data(x, y, z, i)
self.volume = vol
self.is_loaded = True
print "new thresholding done"
def update_std_cut(self, cut):
"""
update std_cut
"""
self.std_cut = cut
self.volume_to_points()