-
Notifications
You must be signed in to change notification settings - Fork 0
/
visu_stack.py
1992 lines (1593 loc) · 65.9 KB
/
visu_stack.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
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2019-2020 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ############################################################################*/
"""Prototype of online 3D stack visualization"""
# TODOs
# - Add some constraint on the 3D ROI to represent the limit of the sample stage displacement
# - Improve scan description: take into account radius being able to change
# - Rework scan selection to allow modifying it and to have both auto-mode and defined scan from parameters
# - Benchmark access 3 slices in 2k**3 dataset: hdf5, zarr, caterva... disk, ssd, ram, memcached
# - Support live update of the 3D stack
# - When dragging line markers, they are not exactly synchronized
# - Issue of zoom level upon resize, it seems to need an extra sync
# - Handle the colormap correctly with the min/max of the stack, not of the image
# - Add a tool to set the colormap from a ROI (should go into silx)
# - When volume is loading, add a mode showing the latest slice in the top view
# - Use status bar to document mode and modifier keys (e.g., for pan constraint)
# - 2nd widget for huge 2D data images + photo layer
# From feedbacks
# - Select the right detector when drawing a ROI
# - Check usage of float16
# - Change up/down of the volume (??)
# - colormap: add per-slice autoscale
# - Option to have one slice as full screen
# From feedbacks, optional
# - 3D view with isosurface
# - Reload at full resolution (or make an extra view with it)
# Ideas/Question
# - Idea: Mode to draw a rectangle on a slide to select the right scan and create the proper ROI
# silx
# - Make silx plot action work for multiple plots at once
from collections import namedtuple
import functools
import io
import logging
import os
import sys
import threading
import typing
import time
import weakref
import numpy
import h5py
from silx.utils.proxy import docstring
from silx.utils.weakref import WeakMethodProxy, WeakList
from silx.gui import qt, plot, icons
from silx.gui.colors import Colormap, rgba
from silx.gui.utils import blockSignals
from silx.gui.utils.concurrent import submitToQtMainThread
from silx.gui.widgets.FrameBrowser import HorizontalSliderWithBrowser
from silx.gui.plot.ColorBar import ColorBarWidget
from silx.gui.plot.utils.axis import SyncAxes
from silx.gui.plot import actions as plot_actions
from silx.gui.plot import items
from silx.gui.plot.items import roi
from silx.gui.plot.tools.roi import RegionOfInterestManager
if sys.version_info < (3, 6):
# Require dict being ordered
class NonSenseError(BaseException):
pass
raise NonSenseError("Python >= 3.6 is required!")
logger = logging.getLogger(__name__)
# Define scan parameters
class Scan:
"""Description of a tomo scan with a detector.
It gives the constraints of the size of the reconstructed volume.
:param List[float] bin_resolution: Size of a pixel in meters (vertical, horizontal)
:param int slice_size: Size in pixels of the reconstructed slices
:param height_range: Range in pixels of the height of the reconstructed volume (min, max)
:param str name: name of the scan
"""
def __init__(
self, bin_resolution=(0.0, 0.0), slice_size=0, height_range=(1, None), name=""
):
self.__bin_resolution = float(bin_resolution[0]), float(bin_resolution[1])
self.__slice_size = int(slice_size)
min_, max_ = height_range
self.__height_range = int(min_), None if max_ is None else int(max_)
self.__name = str(name)
def name(self):
"""Returns the name of the scan.
:rtype: str
"""
return self.__name
def bin_resolution(self):
"""Returns bin resolution (in meters) (vertical, horizontal)
:rtype: List[float]
"""
return self.__bin_resolution
def slice_size(self, unit="pixel"):
"""Returns the size of a horizontal slice.
:param str unit: Unit of the returned value, either 'pixel' or 'meter'
:rtype: Union[int,float]
:raises ValueError: If unit is not supported
"""
if unit == "pixel":
return self.__slice_size
elif unit == "meter":
return self.__slice_size * self.bin_resolution()[1]
else:
raise ValueError("Unsupported unit")
def height_range(self, unit="pixel"):
"""Returns the range of height of the reconstructed volume (min, max)
:param str unit: Unit of the returned values, either 'pixel' or 'meter'
:rtype: List[Union[int,float,None]]
:raises ValueError: If unit is not supported
"""
if unit == "pixel":
return self.__height_range
elif unit == "meter":
res = self.bin_resolution()[0]
min_, max_ = self.__height_range
return min_ * res, None if max_ is None else max_ * res
else:
raise ValueError("Unsupported unit")
# ROI
class RectangleROI2(roi.HandleBasedROI, items.LineMixIn):
"""A ROI identifying a rectangle in a 2D plot.
This ROI provides 1 anchor for each edge, plus an anchor in the
center to translate the full ROI.
"""
ICON = "add-shape-rectangle"
NAME = "rectangle ROI"
SHORT_NAME = "rectangle"
"""Metadata for this kind of ROI"""
_plotShape = "rectangle"
"""Plot shape which is used for the first interaction"""
sigHandleDragged = qt.Signal(float, float)
"""Signal emitted when a handle is dragged by the use
It provides the (x, y) position of the dragged anchor.
"""
def __init__(self, parent=None):
roi.HandleBasedROI.__init__(self, parent=parent)
items.LineMixIn.__init__(self)
self.__size = 0.0, 0.0
self.__center = 0.0, 0.0
self.__subRegionWidth = None
self._handleLeft = self.addHandle()
self._handleLeft._setConstraint(WeakMethodProxy(self.__leftConstraint))
self._handleRight = self.addHandle()
self._handleRight._setConstraint(WeakMethodProxy(self.__rightConstraint))
self._handleTop = self.addHandle()
self._handleTop._setConstraint(WeakMethodProxy(self.__topConstraint))
self._handleBottom = self.addHandle()
self._handleBottom._setConstraint(WeakMethodProxy(self.__bottomConstraint))
self._handleCenter = self.addTranslateHandle()
self._handleCenter._setConstraint(WeakMethodProxy(self.__centerConstraint))
self._handleLabel = self.addLabelHandle()
shape = items.Shape("rectangle")
shape.setPoints([[0, 0], [0, 0]])
shape.setFill(False)
shape.setOverlay(True)
shape.setLineStyle(self.getLineStyle())
shape.setLineWidth(self.getLineWidth())
shape.setColor(rgba(self.getColor()))
self.__shape = shape
self.addItem(shape)
shape = items.Shape("rectangle")
shape.setPoints([[0, 0], [0, 0]])
shape.setFill(False)
shape.setOverlay(True)
shape.setLineStyle(self.getLineStyle())
shape.setLineWidth(self.getLineWidth())
shape.setColor(rgba(self.getColor()))
self.__subShape = shape
self.addItem(shape)
def handleDragUpdated(self, handle, origin, previous, current):
"""Called when an handle drag position changed"""
super().handleDragUpdated(handle, origin, previous, current)
if handle != self._handleCenter:
self.sigHandleDragged.emit(*current)
def __centerConstraint(self, x: float, y: float) -> None:
"""Constraint center anchor depending on modifier keys"""
application = qt.QGuiApplication.instance()
modifiers = application.keyboardModifiers()
if modifiers != qt.Qt.NoModifier:
cx, cy = self.getCenter()
if modifiers & qt.Qt.ShiftModifier:
x = cx # Vertical constraint
elif modifiers & qt.Qt.ControlModifier:
y = cy # Horizontal constraint
return x, y
def __topConstraint(self, x: float, y: float) -> None:
"""Constraint applied on the top anchor"""
cx, cy = self.getCenter()
return cx, max(y, cy)
def __bottomConstraint(self, x: float, y: float) -> None:
"""Constraint applied on the bottom anchor"""
cx, cy = self.getCenter()
return cx, min(y, cy)
def __leftConstraint(self, x: float, y: float) -> None:
"""Constraint applied on the left anchor"""
cx, cy = self.getCenter()
return min(x, cx), cy
def __rightConstraint(self, x: float, y: float) -> None:
"""Constraint applied on the right anchor"""
cx, cy = self.getCenter()
return max(x, cx), cy
def _updated(self, event=None, checkVisibility=True):
if event in [items.ItemChangedType.VISIBLE]:
self._updateItemProperty(event, self, self.__shape)
self._updateItemProperty(event, self, self.__subShape)
super(RectangleROI2, self)._updated(event, checkVisibility)
def _updatedStyle(self, event, style):
super(RectangleROI2, self)._updatedStyle(event, style)
self.__shape.setColor(style.getColor())
self.__shape.setLineStyle(style.getLineStyle())
self.__shape.setLineWidth(style.getLineWidth())
self.__subShape.setColor(style.getColor())
self.__subShape.setLineStyle(style.getLineStyle())
self.__subShape.setLineWidth(style.getLineWidth())
def setFirstShapePoints(self, points):
"""Initialize the rectangle from a bunch of points"""
assert len(points) == 2
ymin, ymax = min(points[:, 1]), max(points[:, 1])
xmin, xmax = min(points[:, 0]), max(points[:, 0])
self.setCenter((0.5 * (xmin + xmax), 0.5 * (ymin + ymax)))
self.setSize((xmax - xmin, ymax - ymin))
def _updateText(self, text):
self._handleLabel.setText(text)
def getOrigin(self):
"""Returns the corner point with the smallest coordinates
:rtype: numpy.ndarray([float,float])
"""
center = self.getCenter()
size = self.getSize()
return center - 0.5 * size
def setOrigin(self, position):
"""Set the origin position of this ROI
:param numpy.ndarray position: Location of the smaller corner of the ROI
"""
self.setCenter(numpy.array(position) + 0.5 * self.getSize())
def getSize(self):
"""Returns the size of this rectangle
:rtype: numpy.ndarray([float,float])
"""
return numpy.array(self.__size)
def setSize(self, size):
"""Set the size of this ROI
:param size: Size of the center of the ROI
"""
size = float(size[0]), float(size[1])
if size != self.__size:
self.__size = size
self.__updateHandles()
def getCenter(self):
"""Returns the central point of this rectangle
:rtype: numpy.ndarray([float,float])
"""
return numpy.array(self.__center)
def setCenter(self, position):
"""Set the size of this ROI
:param numpy.ndarray position: Location of the center of the ROI
"""
position = float(position[0]), float(position[1])
if position != self.__center:
self.__center = position
with blockSignals(self._handleCenter):
self._handleCenter.setPosition(*self.__center)
self.__updateHandles()
def setSubRegionWidth(self, width):
"""Set the width of the sub-region of the ROI.
:param Union[float,None] width:
"""
self.__subRegionWidth = width
self.__updateHandles()
def getSubRegionWidth(self):
"""Returns the width of the sub region.
:rtype: Union[float,None]
"""
return self.__subRegionWidth
def __updateHandles(self):
"""Update handles"""
size = self.getSize()
center = self.getCenter()
origin = self.getOrigin()
with blockSignals(self._handleLeft):
self._handleLeft.setPosition(origin[0], center[1])
with blockSignals(self._handleRight):
self._handleRight.setPosition(origin[0] + size[0], center[1])
with blockSignals(self._handleBottom):
self._handleBottom.setPosition(center[0], origin[1])
with blockSignals(self._handleTop):
self._handleTop.setPosition(center[0], origin[1] + size[1])
with blockSignals(self._handleLabel):
self._handleLabel.setPosition(*origin)
self.__shape.setPoints(numpy.array([origin, origin + size]))
subwidth = self.getSubRegionWidth()
if subwidth is None:
self.__subShape.setPoints(numpy.array([origin, origin + size]))
else:
suboffset = subwidth / 2.
self.__subShape.setPoints(numpy.array([
(center[0] - suboffset, origin[1]),
(center[0] + suboffset, origin[1] + size[1])]))
self.sigRegionChanged.emit()
@docstring(roi.HandleBasedROI)
def contains(self, position):
assert isinstance(position, (tuple, list, numpy.array))
points = self.__shape.getPoints()
bb1 = _BoundingBox.from_points(points)
return bb1.contains(position)
def handleDragUpdated(self, handle, origin, previous, current):
if handle is self._handleCenter:
self.setCenter(current)
elif handle in (self._handleLeft, self._handleRight):
self.setSize(
(
2.0 * abs(self.getCenter()[0] - handle.getPosition()[0]),
self.getSize()[1],
)
)
else: # handleTop of _handleBottom
xcenter = self.getCenter()[0]
width = self.getSize()[0]
bottom = self._handleBottom.getPosition()[1]
top = self._handleTop.getPosition()[1]
self.setCenter((xcenter, 0.5 * (bottom + top)))
self.setSize((width, abs(top - bottom)))
def __str__(self):
origin = self.getOrigin()
w, h = self.getSize()
params = origin[0], origin[1], w, h
params = "origin: %f %f; width: %f; height: %f" % params
return "%s(%s)" % (self.__class__.__name__, params)
class ROI3D(qt.QObject):
SCAN_CHANGED = "scanChanged"
"""Event emitted when the scan info has changed"""
sigItemChanged = qt.Signal(object)
"""Signal emitted when the ROI has changed"""
sigMarkerDragged = qt.Signal(float)
"""Signal emitted when a marker was dragged"""
def __init__(self, parent=None):
super().__init__(parent)
self.__currentSlices = 0, 0, 0
self.__name = ""
self.__visible = True
self.__scan = None
self.__width = 0
self.__height = 0
self.__center = 0.0, 0.0, 0.0
self.__rois = {}
self.__rois["axial"] = roi.CircleROI()
self.__rois["axial"].sigRegionChanged.connect(self.__axialChanged)
self.__rois["front"] = RectangleROI2()
self.__rois["front"].sigRegionChanged.connect(self.__frontChanged)
self.__rois["front"].sigHandleDragged.connect(self.__markerDragged)
self.__rois["side"] = RectangleROI2()
self.__rois["side"].sigRegionChanged.connect(self.__sideChanged)
self.__rois["side"].sigHandleDragged.connect(self.__markerDragged)
for roiItem in self.__rois.values():
roiItem.setName(self.getName())
roiItem.setColor("pink")
roiItem.setLineWidth(2)
roiItem.setEditable(True)
self.__update()
self.setScan(Scan())
def __del__(self):
for roiItem in self.__rois.values():
manager = roiItem.parent()
if manager is not None:
manager.removeRoi(roiItem)
def getName(self):
return self.__name
def setName(self, name):
name = str(name)
if name != self.__name:
self.__name = name
for roiItem in self.__rois.values():
roiItem.setName(self.getName())
self.sigItemChanged.emit(items.ItemChangedType.NAME)
def isVisible(self):
return self.__visible
def setVisible(self, visible):
visible = bool(visible)
if visible != self.__visible:
self.__visible = visible
for rect in self.__rois.values():
rect.setVisible(visible)
self.sigItemChanged.emit(items.ItemChangedType.VISIBLE)
def getScan(self):
return self.__scan
def setScan(self, scan):
if scan != self.__scan:
self.__scan = scan
# Update ROI3D
self.setWidth(scan.slice_size(unit="meter"))
self.setHeight(
numpy.clip(self.getHeight(), *scan.height_range(unit="meter"))
)
self.sigItemChanged.emit(self.SCAN_CHANGED)
def getROI(self, face):
return self.__rois[face]
def setLineWidth(self, width):
for roi in self.__rois.values():
roi.setLineWidth(width)
def setCurrentSlicePosition(self, x, y, z):
self.__currentSlices = x, y, z
ox, oy, oz = self.getOriginCorner()
fx, fy, fz = self.getFarthestCorner()
in_color = "pink"
out_color = rgba(in_color)[:3] + (0.75,)
in_style = "-"
out_style = "--"
cx, cy, cz = self.getCenter()
width = self.getWidth()
xwidth, ywidth = None, None
if width > 0.:
if oy <= y <= fy:
xwidth = width * numpy.sqrt(1 - ((y - cy) / (0.5 * width))**2)
if ox <= x <= fx:
ywidth = width * numpy.sqrt(1 - ((x - cx) / (0.5 * width))**2)
self.__rois["side"].setColor(in_color if ox <= x <= fx else out_color)
self.__rois["side"].setLineStyle(in_style if ox <= x <= fx else out_style)
self.__rois["side"].setSubRegionWidth(ywidth)
self.__rois["front"].setColor(in_color if oy <= y <= fy else out_color)
self.__rois["front"].setLineStyle(in_style if oy <= y <= fy else out_style)
self.__rois["front"].setSubRegionWidth(xwidth)
self.__rois["axial"].setColor(in_color if oz <= z <= fz else out_color)
self.__rois["axial"].setLineStyle(in_style if oz <= z <= fz else out_style)
def getCurrentSlicePosition(self):
return self.__currentSlices
def __axialChanged(self):
cx, cy = self.__rois["axial"].getCenter()
cz = self.getCenter()[2]
self.setWidth(2 * self.__rois["axial"].getRadius())
self.setCenter(cx, cy, cz)
def __frontChanged(self):
cx, cz = self.__rois["front"].getCenter()
cy = self.getCenter()[1]
width, height = self.__rois["front"].getSize()
self.setHeight(height)
self.setWidth(width)
self.setCenter(cx, cy, cz)
def __sideChanged(self):
cy, cz = self.__rois["side"].getCenter()
cx = self.getCenter()[0]
width, height = self.__rois["side"].getSize()
self.setHeight(height)
self.setWidth(width)
self.setCenter(cx, cy, cz)
def __markerDragged(self, x, y):
self.sigMarkerDragged.emit(y)
def __update(self):
cx, cy, cz = self.getCenter()
self.__rois["axial"].setRadius(self.getWidth() / 2)
self.__rois["axial"].setCenter((cx, cy))
self.__rois["front"].setSize((self.getWidth(), self.getHeight()))
self.__rois["front"].setCenter((cx, cz))
self.__rois["side"].setSize((self.getWidth(), self.getHeight()))
self.__rois["side"].setCenter((cy, cz))
self.setCurrentSlicePosition(*self.getCurrentSlicePosition()) # sync color
self.sigItemChanged.emit(items.ItemChangedType.POSITION)
def getWidth(self):
return self.__width
def setWidth(self, width):
if width != self.__width:
self.__width = width
self.__update()
def getHeight(self):
return self.__height
def setHeight(self, height):
if height != self.__height:
self.__height = height
self.__update()
def getCenter(self):
return self.__center
def setCenter(self, cx, cy, cz):
center = cx, cy, cz
if not numpy.array_equal(center, self.__center):
self.__center = center
self.__update()
def getOriginCorner(self):
cx, cy, cz = self.getCenter()
width, height = self.getWidth(), self.getHeight()
return cx - width / 2.0, cy - width / 2.0, cz - height / 2.0
def getFarthestCorner(self):
cx, cy, cz = self.getCenter()
width, height = self.getWidth(), self.getHeight()
return cx + width / 2.0, cy + width / 2.0, cz + height / 2.0
# 3D ROI table widget
class ROI3DTableWidgetTypeItemDelegate(qt.QStyledItemDelegate):
def __init__(self, parent=None, items={}):
super().__init__(parent)
self.__items = items
def createEditor(self, parent, option, index):
combobox = qt.QComboBox(parent)
combobox.setAutoFillBackground(True)
for text, item in self.__items.items():
combobox.addItem(text, item)
roi = index.data(qt.Qt.UserRole)
itemIndex = combobox.findData(roi.getScan())
if itemIndex == -1: # Add an item
text = index.data(qt.Qt.EditRole)
combobox.addItem(text, data)
itemIndex = combobox.count() - 1
combobox.setCurrentIndex(itemIndex)
combobox.currentIndexChanged.connect(self._commit)
return combobox
def _commit(self, *args):
"""Commit data to the model from editors"""
sender = self.sender()
self.commitData.emit(sender)
class ROI3DTableWidget(qt.QTableWidget):
"""Table widget of 3D ROIs"""
NAME_COL, TYPE_COL, Z_COL, CENTER_COL, WIDGETS_COL = range(5)
sigCenter = qt.Signal(float, float, float)
def __init__(self, parent=None, types={}):
super().__init__(parent)
self._types = types
headers = ["Name", "Type", "Vertical Range", "Rotation Center", ""]
self.setColumnCount(len(headers))
self.setHorizontalHeaderLabels(headers)
horizontalHeader = self.horizontalHeader()
horizontalHeader.setDefaultAlignment(qt.Qt.AlignLeft)
horizontalHeader.setSectionResizeMode(self.NAME_COL, qt.QHeaderView.Interactive)
horizontalHeader.setSectionResizeMode(
self.TYPE_COL, qt.QHeaderView.ResizeToContents
)
horizontalHeader.setSectionResizeMode(self.Z_COL, qt.QHeaderView.Stretch)
horizontalHeader.setSectionResizeMode(self.CENTER_COL, qt.QHeaderView.Stretch)
horizontalHeader.setSectionResizeMode(
self.WIDGETS_COL, qt.QHeaderView.ResizeToContents
)
verticalHeader = self.verticalHeader()
verticalHeader.setVisible(False)
self.setSelectionBehavior(qt.QAbstractItemView.SelectRows)
self.setSelectionMode(qt.QAbstractItemView.SingleSelection)
self.setFocusPolicy(qt.Qt.NoFocus)
self.__delegate = ROI3DTableWidgetTypeItemDelegate(items=self._types)
self.setItemDelegateForColumn(self.TYPE_COL, self.__delegate)
self.itemChanged.connect(self.__itemChanged)
self.currentCellChanged.connect(self.__currentCellChanged)
def __currentCellChanged(
self, currentRow, currentColumn, previousRow, previousColumn
):
if previousRow != -1:
roi = self.getROI3D()[previousRow]
roi.setLineWidth(2)
if currentRow != -1:
roi = self.getROI3D()[currentRow]
roi.setLineWidth(4)
def __itemChanged(self, item):
"""Handle item updates"""
column = item.column()
roi = item.data(qt.Qt.UserRole)
if roi is None:
return # Only item with user role are handled
if column == self.NAME_COL:
roi.setVisible(item.checkState() == qt.Qt.Checked)
roi.setName(item.text())
elif column == self.TYPE_COL:
scanName = item.data(qt.Qt.EditRole)
scan = self._types.get(scanName)
if scan is not None:
roi.setScan(scan)
else:
logger.error("Unhandled column %d", column)
def _updateDescription(self, roi):
cx, cy, cz = roi.getCenter()
height = roi.getHeight()
z_min = cz - height / 2.0
z_max = z_min + height
row = self.getROI3D().index(roi)
item = self.item(row, self.Z_COL)
item.setText("[%g, %g]" % (z_min, z_max))
item = self.item(row, self.CENTER_COL)
item.setText("(%g, %g)" % (cx, cy))
def setCurrentSlicePosition(self, x, y, z):
for roi in self.getROI3D():
roi.setCurrentSlicePosition(x, y, z)
def __roiChanged(self, event):
"""Handle 3D ROI updates"""
roi = self.sender()
if event == items.ItemChangedType.POSITION:
self._updateDescription(roi)
elif event == items.ItemChangedType.NAME:
row = self.getROI3D().index(roi)
item = self.item(row, self.NAME_COL)
item.setText(roi.getName())
elif event == ROI3D.SCAN_CHANGED:
row = self.getROI3D().index(roi)
item = self.item(row, self.TYPE_COL)
item.setText(roi.getScan().name())
elif event == items.ItemChangedType.VISIBLE:
row = self.getROI3D().index(roi)
item = self.item(row, self.NAME_COL)
item.setCheckState(qt.Qt.Checked if roi.isVisible() else qt.Qt.Unchecked)
def getROI3D(self):
"""Returns the list of 3D ROIs in the table.
:rtype: List[ROI3D]
"""
items = (self.item(row, self.NAME_COL) for row in range(self.rowCount()))
return [item.data(qt.Qt.UserRole) for item in items if item is not None]
def removeROI3D(self, roi):
"""Remove the given 3D ROI from the table.
:param ROI3D roi:
"""
row = self.getROI3D().index(roi)
self.removeRow(row)
roi.sigItemChanged.disconnect(self.__roiChanged)
def __centerROI3D(self, roi):
"""Center plots on roi center
:param ROI3D roi:
"""
cx, cy, cz = roi.getCenter()
self.sigCenter.emit(cx, cy, cz)
def addROI3D(self, roi):
"""Append a 3D ROI to the table.
:param ROI3D roi:
:raises ValueError: If the ROI is already in the table
"""
if roi in self.getROI3D():
raise ValueError("ROI already in the table")
# Create row
row = self.rowCount()
self.insertRow(row)
baseFlags = qt.Qt.ItemIsSelectable | qt.Qt.ItemIsEnabled
# Populate row
# Name and visible
item = qt.QTableWidgetItem(roi.getName())
item.setFlags(baseFlags | qt.Qt.ItemIsEditable | qt.Qt.ItemIsUserCheckable)
item.setData(qt.Qt.UserRole, roi)
item.setCheckState(qt.Qt.Checked if roi.isVisible() else qt.Qt.Unchecked)
self.setItem(row, self.NAME_COL, item)
# Type
item = qt.QTableWidgetItem(roi.getScan().name())
item.setFlags(baseFlags | qt.Qt.ItemIsEditable)
item.setData(qt.Qt.UserRole, roi)
self.setItem(row, self.TYPE_COL, item)
self.openPersistentEditor(item)
# Info
item = qt.QTableWidgetItem()
item.setFlags(baseFlags)
self.setItem(row, self.Z_COL, item)
item = qt.QTableWidgetItem()
item.setFlags(baseFlags)
self.setItem(row, self.CENTER_COL, item)
self._updateDescription(roi)
# Buttons: Pointing and delete
centerBtn = qt.QToolButton()
centerBtn.setIcon(icons.getQIcon("normal"))
centerBtn.setToolTip("Center the plots on the center of the ROI")
centerBtn.clicked.connect(functools.partial(self.__centerROI3D, roi))
delBtn = qt.QToolButton()
delBtn.setIcon(icons.getQIcon("remove"))
delBtn.setToolTip("Remove this ROI")
delBtn.clicked.connect(functools.partial(self.removeROI3D, roi))
self.__addWidget(row, self.WIDGETS_COL, centerBtn, delBtn)
# Here to update the size of the columns
horizontalHeader = self.horizontalHeader()
horizontalHeader.reset()
# Using queued connection to avoid sender() returning the table model
roi.sigItemChanged.connect(self.__roiChanged, qt.Qt.QueuedConnection)
def __addWidget(self, row, column, *widgets):
cellWidget = qt.QWidget(self)
layout = qt.QHBoxLayout()
layout.setContentsMargins(2, 2, 2, 2)
layout.setSpacing(0)
cellWidget.setLayout(layout)
layout.addStretch(1)
for widget in widgets:
layout.addWidget(widget)
layout.addStretch(1)
self.setCellWidget(row, column, cellWidget)
# Main window
class SliceModel(qt.QObject):
"""Handle current state of a slice"""
sigCurrentIndexChanged = qt.Signal(int)
"""Signal emitted when slice index changed"""
AXIAL = dict(title="Axial", axis="Z", xaxis="X", yaxis="Y")
FRONT = dict(title="Front", axis="Y", xaxis="X", yaxis="Z")
SIDE = dict(title="Side", axis="X", xaxis="Y", yaxis="Z")
def __init__(
self,
title="Slice",
axis="Index",
xaxis="X",
yaxis="Y",
unit="mm",
origin=(0.0, 0.0),
scale=(1.0, 1.0),
range_=(0, 0),
normalization=(0.0, 1.0),
dataProvider=None,
):
super().__init__()
self.__title = title
self.__axis = axis
self.__xaxis = xaxis
self.__yaxis = yaxis
self.__unit = unit
self.__origin = origin
self.__scale = scale
self.__range = range_
self.__normalization = normalization
self.__dataProvider = dataProvider
self.__index = min(range_)
# Static information
def getTitle(self) -> str:
"""Returns the main title prefix"""
return self.__title
def getAxisName(self) -> str:
"""Returns the name of the axis perpendicular to the slice"""
return self.__axis
def getXAxisName(self) -> str:
"""Returns the name of the X axis"""
return self.__xaxis
def getYAxisName(self) -> str:
"""Returns the name of the Y axis"""
return self.__yaxis
def getUnit(self) -> str:
"""Returns the unit in use"""
return self.__unit
def getSliceOrigin(self):
"""Returns the origin of the slice.
:returns: (ox, oy)
"""
return self.__origin
def getSliceScale(self):
"""Returns the scale factor on each axis.
:returns: (sx, sy)
"""
return self.__scale
def getIndexRange(self):
"""Returns the range of the slice indices.
:returns: (min, max)
"""
return self.__range
def getNormalization(self):
"""Returns the origin and scale along the axis perpendicular to the slices.
:returns: (origin, scale factor)
"""
return self.__normalization
def getXAxisTitle(self) -> str:
"""Returns the title to use for the plot X axis"""
return "%s (%s)" % (self.getXAxisName(), self.getUnit())
def getYAxisTitle(self) -> str:
"""Returns the title to use for the plot Y axis"""
return "%s (%s)" % (self.getYAxisName(), self.getUnit())
# Dynamic information
def setCurrentIndex(self, index: int) -> None:
"""Set the index of the slice to display.
:param int index: Index of the slice (clipped to slice range)
"""
min_, max_ = self.getIndexRange()
index = numpy.clip(int(index), min_, max_)
if index != self.__index:
self.__index = index
self.sigCurrentIndexChanged.emit(index)
def getCurrentIndex(self) -> int:
"""Returns the current slice index."""
return self.__index
def setSlicePosition(self, position: float) -> None:
"""Set the index of the slice from its normalized position"""
origin, scale = self.getNormalization()
self.setCurrentIndex(int((position - origin) / scale))
def getSlicePosition(self) -> int:
"""Returns the position of the slice with normalization"""
origin, scale = self.getNormalization()
return origin + self.getCurrentIndex() * scale
def getData(self):
"""Returns the current slice data"""
provider = self.__dataProvider
if provider is None:
data = numpy.empty((0, 0), dtype=numpy.float32)
else:
data = provider(self.getCurrentIndex())
if data is None:
data = numpy.empty((0, 0), dtype=numpy.float32)
return data