summaryrefslogtreecommitdiff
path: root/silx/gui/plot3d/ScalarFieldView.py
blob: 50cba05671a5c42f79f4ee25aecd82300cc07335 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2015-2018 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.
#
# ###########################################################################*/
"""This module provides a window to view a 3D scalar field.

It supports iso-surfaces, a cutting plane and the definition of
a region of interest.
"""

from __future__ import absolute_import

__authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "14/06/2018"

import re
import logging
import time
from collections import deque

import numpy

from silx.gui import qt, icons
from silx.gui.colors import rgba
from silx.gui.colors import Colormap

from silx.math.marchingcubes import MarchingCubes
from silx.math.combo import min_max

from .scene import axes, cutplane, interaction, primitives, transform
from . import scene
from .Plot3DWindow import Plot3DWindow
from .tools import InteractiveModeToolBar

_logger = logging.getLogger(__name__)


class Isosurface(qt.QObject):
    """Class representing an iso-surface

    :param parent: The View widget this iso-surface belongs to
    """

    sigLevelChanged = qt.Signal(float)
    """Signal emitted when the iso-surface level has changed.

    This signal provides the new level value (might be nan).
    """

    sigColorChanged = qt.Signal()
    """Signal emitted when the iso-surface color has changed"""

    sigVisibilityChanged = qt.Signal(bool)
    """Signal emitted when the iso-surface visibility has changed.

    This signal provides the new visibility status.
    """

    def __init__(self, parent):
        super(Isosurface, self).__init__(parent=parent)
        self._level = float('nan')
        self._autoLevelFunction = None
        self._color = rgba('#FFD700FF')
        self._data = None
        self._group = scene.Group()

    def _setData(self, data, copy=True):
        """Set the data set from which to build the iso-surface.

        :param numpy.ndarray data: The 3D dataset or None
        :param bool copy: True to make a copy, False to use as is if possible
        """
        if data is None:
            self._data = None
        else:
            self._data = numpy.array(data, copy=copy, order='C')

        self._update()

    def _get3DPrimitive(self):
        """Return the group containing the mesh of the iso-surface if any"""
        return self._group

    def isVisible(self):
        """Returns True if iso-surface is visible, else False"""
        return self._group.visible

    def setVisible(self, visible):
        """Set the visibility of the iso-surface in the view.

        :param bool visible: True to show the iso-surface, False to hide
        """
        visible = bool(visible)
        if visible != self._group.visible:
            self._group.visible = visible
            self.sigVisibilityChanged.emit(visible)

    def getLevel(self):
        """Return the level of this iso-surface (float)"""
        return self._level

    def setLevel(self, level):
        """Set the value at which to build the iso-surface.

        Setting this value reset auto-level function

        :param float level: The value at which to build the iso-surface
        """
        self._autoLevelFunction = None
        level = float(level)
        if level != self._level:
            self._level = level
            self._update()
            self.sigLevelChanged.emit(level)

    def isAutoLevel(self):
        """True if iso-level is rebuild for each data set."""
        return self.getAutoLevelFunction() is not None

    def getAutoLevelFunction(self):
        """Return the function computing the iso-level (callable or None)"""
        return self._autoLevelFunction

    def setAutoLevelFunction(self, autoLevel):
        """Set the function used to compute the iso-level.

        WARNING: The function might get called in a thread.

        :param callable autoLevel:
            A function taking a 3D numpy.ndarray of float32 and returning
            a float used as iso-level.
            Example: numpy.mean(data) + numpy.std(data)
        """
        assert callable(autoLevel)
        self._autoLevelFunction = autoLevel
        self._update()

    def getColor(self):
        """Return the color of this iso-surface (QColor)"""
        return qt.QColor.fromRgbF(*self._color)

    def setColor(self, color):
        """Set the color of the iso-surface

        :param color: RGBA color of the isosurface
        :type color: QColor, str or array-like of 4 float in [0., 1.]
        """
        color = rgba(color)
        if color != self._color:
            self._color = color
            if len(self._group.children) != 0:
                self._group.children[0].setAttribute('color', self._color)
            self.sigColorChanged.emit()

    def _update(self):
        """Update underlying mesh"""
        self._group.children = []

        if self._data is None:
            if self.isAutoLevel():
                self._level = float('nan')

        else:
            if self.isAutoLevel():
                st = time.time()
                try:
                    level = float(self.getAutoLevelFunction()(self._data))

                except Exception:
                    module = self.getAutoLevelFunction().__module__
                    name = self.getAutoLevelFunction().__name__
                    _logger.error(
                        "Error while executing iso level function %s.%s",
                        module,
                        name,
                        exc_info=True)
                    level = float('nan')

                else:
                    _logger.info(
                        'Computed iso-level in %f s.', time.time() - st)

                if level != self._level:
                    self._level = level
                    self.sigLevelChanged.emit(level)

            if not numpy.isfinite(self._level):
                return

            st = time.time()
            vertices, normals, indices = MarchingCubes(
                self._data,
                isolevel=self._level)
            _logger.info('Computed iso-surface in %f s.', time.time() - st)

            if len(vertices) == 0:
                return
            else:
                mesh = primitives.Mesh3D(vertices,
                                         colors=self._color,
                                         normals=normals,
                                         mode='triangles',
                                         indices=indices)
                self._group.children = [mesh]


class SelectedRegion(object):
    """Selection of a 3D region aligned with the axis.

    :param arrayRange: Range of the selection in the array
        ((zmin, zmax), (ymin, ymax), (xmin, xmax))
    :param dataBBox: Bounding box of the selection in data coordinates
        ((xmin, xmax), (ymin, ymax), (zmin, zmax))
    :param translation: Offset from array to data coordinates (ox, oy, oz)
    :param scale: Scale from array to data coordinates (sx, sy, sz)
    """

    def __init__(self, arrayRange, dataBBox,
                 translation=(0., 0., 0.),
                 scale=(1., 1., 1.)):
        self._arrayRange = numpy.array(arrayRange, copy=True, dtype=numpy.int)
        assert self._arrayRange.shape == (3, 2)
        assert numpy.all(self._arrayRange[:, 1] >= self._arrayRange[:, 0])

        self._dataRange = dataBBox

        self._translation = numpy.array(translation, dtype=numpy.float32)
        assert self._translation.shape == (3,)
        self._scale = numpy.array(scale, dtype=numpy.float32)
        assert self._scale.shape == (3,)

    def getArrayRange(self):
        """Returns array ranges of the selection: 3x2 array of int

        :return: A numpy array with ((zmin, zmax), (ymin, ymax), (xmin, xmax))
        :rtype: numpy.ndarray
        """
        return self._arrayRange.copy()

    def getArraySlices(self):
        """Slices corresponding to the selected range in the array

        :return: A numpy array with (zslice, yslice, zslice)
        :rtype: numpy.ndarray
        """
        return (slice(*self._arrayRange[0]),
                slice(*self._arrayRange[1]),
                slice(*self._arrayRange[2]))

    def getDataRange(self):
        """Range in the data coordinates of the selection: 3x2 array of float

        When the transform matrix is not the identity matrix
        (e.g., rotation, skew) the returned range is the one of the selected
        region bounding box in data coordinates.

        :return: A numpy array with ((xmin, xmax), (ymin, ymax), (zmin, zmax))
        :rtype: numpy.ndarray
        """
        return self._dataRange.copy()

    def getDataScale(self):
        """Scale from array to data coordinates: (sx, sy, sz)

        :return: A numpy array with (sx, sy, sz)
        :rtype: numpy.ndarray
        """
        return self._scale.copy()

    def getDataTranslation(self):
        """Offset from array to data coordinates: (ox, oy, oz)

        :return: A numpy array with (ox, oy, oz)
        :rtype: numpy.ndarray
        """
        return self._translation.copy()


class CutPlane(qt.QObject):
    """Class representing a cutting plane

    :param ~silx.gui.plot3d.ScalarFieldView.ScalarFieldView sfView:
        Widget in which the cut plane is applied.
    """

    sigVisibilityChanged = qt.Signal(bool)
    """Signal emitted when the cut visibility has changed.

    This signal provides the new visibility status.
    """

    sigDataChanged = qt.Signal()
    """Signal emitted when the data this plane is cutting has changed."""

    sigPlaneChanged = qt.Signal()
    """Signal emitted when the cut plane has moved"""

    sigColormapChanged = qt.Signal(Colormap)
    """Signal emitted when the colormap has changed

    This signal provides the new colormap.
    """

    sigTransparencyChanged = qt.Signal()
    """Signal emitted when the transparency of the plane has changed.

    This signal is emitted when calling :meth:`setDisplayValuesBelowMin`.
    """

    sigInterpolationChanged = qt.Signal(str)
    """Signal emitted when the cut plane interpolation has changed

    This signal provides the new interpolation mode.
    """

    def __init__(self, sfView):
        super(CutPlane, self).__init__(parent=sfView)

        self._dataRange = None
        self._visible = False

        self.__syncPlane = True

        # Plane stroke on the outer bounding box
        self._planeStroke = primitives.PlaneInGroup(normal=(0, 1, 0))
        self._planeStroke.visible = self._visible
        self._planeStroke.addListener(self._planeChanged)
        self._planeStroke.plane.addListener(self._planePositionChanged)

        # Plane with texture on the data bounding box
        self._dataPlane = cutplane.CutPlane(normal=(0, 1, 0))
        self._dataPlane.strokeVisible = False
        self._dataPlane.alpha = 1.
        self._dataPlane.visible = self._visible
        self._dataPlane.plane.addListener(self._planePositionChanged)

        self._colormap = Colormap(
            name='gray', normalization='linear', vmin=None, vmax=None)
        self.getColormap().sigChanged.connect(self._colormapChanged)
        self._updateSceneColormap()

        sfView.sigDataChanged.connect(self._sfViewDataChanged)
        sfView.sigTransformChanged.connect(self._sfViewTransformChanged)

    def _get3DPrimitives(self):
        """Return the cut plane scene node."""
        return self._planeStroke, self._dataPlane

    def _keepPlaneInBBox(self):
        """Makes sure the plane intersect its parent bounding box if any"""
        bounds = self._planeStroke.parent.bounds(dataBounds=True)
        if bounds is not None:
            self._planeStroke.plane.point = numpy.clip(
                self._planeStroke.plane.point,
                a_min=bounds[0], a_max=bounds[1])

    @staticmethod
    def _syncPlanes(master, slave):
        """Move slave PlaneInGroup so that it is coplanar with master.

        :param PlaneInGroup master: Reference PlaneInGroup
        :param PlaneInGroup slave: PlaneInGroup to align
        """
        masterToSlave = transform.StaticTransformList([
            slave.objectToSceneTransform.inverse(),
            master.objectToSceneTransform])

        point = masterToSlave.transformPoint(
            master.plane.point)
        normal = masterToSlave.transformNormal(
            master.plane.normal)
        slave.plane.setPlane(point, normal)

    def _sfViewDataChanged(self):
        """Handle data change in the ScalarFieldView this plane belongs to"""
        self._dataPlane.setData(self.sender().getData(), copy=False)

        # Store data range info as 3-tuple of values
        self._dataRange = self.sender().getDataRange()

        self.sigDataChanged.emit()

        # Update colormap range when autoscale
        if self.getColormap().isAutoscale():
            self._updateSceneColormap()

        self._keepPlaneInBBox()

    def _sfViewTransformChanged(self):
        """Handle transform changed in the ScalarFieldView"""
        self._keepPlaneInBBox()
        self._syncPlanes(master=self._planeStroke,
                         slave=self._dataPlane)
        self.sigPlaneChanged.emit()

    def _planeChanged(self, source, *args, **kwargs):
        """Handle events from the plane primitive"""
        # Using _visible for now, until scene as more info in events
        if source.visible != self._visible:
            self._visible = source.visible
            self.sigVisibilityChanged.emit(source.visible)

    def _planePositionChanged(self, source, *args, **kwargs):
        """Handle update of cut plane position and normal"""
        if self.__syncPlane:
            self.__syncPlane = False
            if source is self._planeStroke.plane:
                self._syncPlanes(master=self._planeStroke,
                                 slave=self._dataPlane)
            elif source is self._dataPlane.plane:
                self._syncPlanes(master=self._dataPlane,
                                 slave=self._planeStroke)
            else:
                _logger.error('Received an unknown object %s',
                              str(source))

            if self._planeStroke.visible or self._dataPlane.visible:
                self.sigPlaneChanged.emit()

            self.__syncPlane = True

    # Plane position

    def moveToCenter(self):
        """Move cut plane to center of data set"""
        self._planeStroke.moveToCenter()

    def isValid(self):
        """Returns whether the cut plane is defined or not (bool)"""
        return self._planeStroke.isValid

    def _plane(self, coordinates='array'):
        """Returns the scene plane to set.

        :param str coordinates: The coordinate system to use:
            Either 'scene' or 'array' (default)
        :rtype: Plane
        :raise ValueError: If coordinates is not correct
        """
        if coordinates == 'scene':
            return self._planeStroke.plane
        elif coordinates == 'array':
            return self._dataPlane.plane
        else:
             raise ValueError(
                'Unsupported coordinates: %s' % str(coordinates))

    def getNormal(self, coordinates='array'):
        """Returns the normal of the plane (as a unit vector)

        :param str coordinates: The coordinate system to use:
            Either 'scene' or 'array' (default)
        :return: Normal (nx, ny, nz), vector is 0 if no plane is defined
        :rtype: numpy.ndarray
        :raise ValueError: If coordinates is not correct
        """
        return self._plane(coordinates).normal

    def setNormal(self, normal, coordinates='array'):
        """Set the normal of the plane.

        :param normal: 3-tuple of float: nx, ny, nz
        :param str coordinates: The coordinate system to use:
            Either 'scene' or 'array' (default)
        :raise ValueError: If coordinates is not correct
        """
        self._plane(coordinates).normal = normal

    def getPoint(self, coordinates='array'):
        """Returns a point on the plane.

        :param str coordinates: The coordinate system to use:
            Either 'scene' or 'array' (default)
        :return: (x, y, z)
        :rtype: numpy.ndarray
        :raise ValueError: If coordinates is not correct
        """
        return self._plane(coordinates).point

    def setPoint(self, point, constraint=True, coordinates='array'):
        """Set a point contained in the plane.

        Warning: The plane might not intersect the bounding box of the data.

        :param point: (x, y, z) position
        :type point: 3-tuple of float
        :param bool constraint:
            True (default) to make sure the plane intersect data bounding box,
            False to set the plane without any constraint.
        :raise ValueError: If coordinates is not correc
        """
        self._plane(coordinates).point = point
        if constraint:
            self._keepPlaneInBBox()

    def getParameters(self, coordinates='array'):
        """Returns the plane equation parameters: a*x + b*y + c*z + d = 0

        :param str coordinates: The coordinate system to use:
            Either 'scene' or 'array' (default)
        :return: Plane equation parameters: (a, b, c, d)
        :rtype: numpy.ndarray
        :raise ValueError: If coordinates is not correct
        """
        return self._plane(coordinates).parameters

    def setParameters(self, parameters, constraint=True, coordinates='array'):
        """Set the plane equation parameters: a*x + b*y + c*z + d = 0

        Warning: The plane might not intersect the bounding box of the data.

        :param parameters: (a, b, c, d) plane equation parameters.
        :type parameters: 4-tuple of float
        :param bool constraint:
            True (default) to make sure the plane intersect data bounding box,
            False to set the plane without any constraint.
        :raise ValueError: If coordinates is not correc
        """
        self._plane(coordinates).parameters = parameters
        if constraint:
            self._keepPlaneInBBox()

    # Visibility

    def isVisible(self):
        """Returns True if the plane is visible, False otherwise"""
        return self._planeStroke.visible

    def setVisible(self, visible):
        """Set the visibility of the plane

        :param bool visible: True to make plane visible
        """
        visible = bool(visible)
        self._planeStroke.visible = visible
        self._dataPlane.visible = visible

    # Border stroke

    def getStrokeColor(self):
        """Returns the color of the plane border (QColor)"""
        return qt.QColor.fromRgbF(*self._planeStroke.color)

    def setStrokeColor(self, color):
        """Set the color of the plane border.

        :param color: RGB color: name, #RRGGBB or RGB values
        :type color:
            QColor, str or array-like of 3 or 4 float in [0., 1.] or uint8
        """
        color = rgba(color)
        self._planeStroke.color = color
        self._dataPlane.color = color

    # Data

    def getImageData(self):
        """Returns the data and information corresponding to the cut plane.

        The returned data is not interpolated,
        it is a slice of the 3D scalar field.

        Image data axes are so that plane normal is towards the point of view.

        :return: An object containing the 2D data slice and information
        """
        return _CutPlaneImage(self)

    # Interpolation

    def getInterpolation(self):
        """Returns the interpolation used to display to cut plane.

        :return: 'nearest' or 'linear'
        :rtype: str
        """
        return self._dataPlane.interpolation

    def setInterpolation(self, interpolation):
        """Set the interpolation used to display to cut plane

        The default interpolation is 'linear'

        :param str interpolation: 'nearest' or 'linear'
        """
        if interpolation != self.getInterpolation():
            self._dataPlane.interpolation = interpolation
            self.sigInterpolationChanged.emit(interpolation)

    # Colormap

    # def getAlpha(self):
    #     """Returns the transparency of the plane as a float in [0., 1.]"""
    #     return self._plane.alpha

    # def setAlpha(self, alpha):
    #     """Set the plane transparency.
    #
    #     :param float alpha: Transparency in [0., 1]
    #     """
    #     self._plane.alpha = alpha

    def getDisplayValuesBelowMin(self):
        """Return whether values <= colormap min are displayed or not.

        :rtype: bool
        """
        return self._dataPlane.colormap.displayValuesBelowMin

    def setDisplayValuesBelowMin(self, display):
        """Set whether to display values <= colormap min.

        :param bool display: True to show values below min,
                             False to discard them
        """
        display = bool(display)
        if display != self.getDisplayValuesBelowMin():
            self._dataPlane.colormap.displayValuesBelowMin = display
            self.sigTransparencyChanged.emit()

    def getColormap(self):
        """Returns the colormap set by :meth:`setColormap`.

        :return: The colormap
        :rtype: ~silx.gui.colors.Colormap
        """
        return self._colormap

    def setColormap(self,
                    name='gray',
                    norm=None,
                    vmin=None,
                    vmax=None):
        """Set the colormap to use.

        By either providing a :class:`Colormap` object or
        its name, normalization and range.

        :param name: Name of the colormap in
            'gray', 'reversed gray', 'temperature', 'red', 'green', 'blue'.
            Or Colormap object.
        :type name: str or ~silx.gui.colors.Colormap
        :param str norm: Colormap mapping: 'linear' or 'log'.
        :param float vmin: The minimum value of the range or None for autoscale
        :param float vmax: The maximum value of the range or None for autoscale
        """
        _logger.debug('setColormap %s %s (%s, %s)',
                      name, str(norm), str(vmin), str(vmax))

        self._colormap.sigChanged.disconnect(self._colormapChanged)

        if isinstance(name, Colormap):  # Use it as it is
            assert (norm, vmin, vmax) == (None, None, None)
            self._colormap = name
        else:
            if norm is None:
                norm = 'linear'
            self._colormap = Colormap(
                name=name, normalization=norm, vmin=vmin, vmax=vmax)

        self._colormap.sigChanged.connect(self._colormapChanged)
        self._colormapChanged()

    def getColormapEffectiveRange(self):
        """Returns the currently used range of the colormap.

        This range is computed from the data set if colormap is in autoscale.
        Range is clipped to positive values when using log scale.

        :return: 2-tuple of float
        """
        return self._dataPlane.colormap.range_

    def _updateSceneColormap(self):
        """Synchronizes scene's colormap with Colormap object"""
        colormap = self.getColormap()
        sceneCMap = self._dataPlane.colormap

        sceneCMap.colormap = colormap.getNColors()

        sceneCMap.norm = colormap.getNormalization()
        range_ = colormap.getColormapRange(data=self._dataRange)
        sceneCMap.range_ = range_

    def _colormapChanged(self):
        """Handle update of Colormap object"""
        self._updateSceneColormap()
        # Forward colormap changed event
        self.sigColormapChanged.emit(self.getColormap())


class _CutPlaneImage(object):
    """Object representing the data sliced by a cut plane

    :param CutPlane cutPlane: The CutPlane from which to generate image info
    """

    def __init__(self, cutPlane):
        # Init attributes with default values
        self._isValid = False
        self._data = numpy.zeros((0, 0), dtype=numpy.float32)
        self._index = 0
        self._xLabel = ''
        self._yLabel = ''
        self._normalLabel = ''
        self._scale = float('nan'), float('nan')
        self._translation = float('nan'), float('nan')
        self._position = float('nan')

        sfView = cutPlane.parent()
        if not sfView or not cutPlane.isValid():
            _logger.info("No plane available")
            return

        data = sfView.getData(copy=False)
        if data is None:
            _logger.info("No data available")
            return

        normal = cutPlane.getNormal(coordinates='array')
        point = cutPlane.getPoint(coordinates='array')

        if numpy.linalg.norm(numpy.cross(normal, (1., 0., 0.))) < 0.0017:
            if not 0 <= point[0] <= data.shape[2]:
                _logger.info("Plane outside dataset")
                return
            index = max(0, min(int(point[0]), data.shape[2] - 1))
            slice_ = data[:, :, index]
            xAxisIndex, yAxisIndex, normalAxisIndex = 1, 2, 0  # y, z, x

        elif numpy.linalg.norm(numpy.cross(normal, (0., 1., 0.))) < 0.0017:
            if not 0 <= point[1] <= data.shape[1]:
                _logger.info("Plane outside dataset")
                return
            index = max(0, min(int(point[1]), data.shape[1] - 1))
            slice_ = numpy.transpose(data[:, index, :])
            xAxisIndex, yAxisIndex, normalAxisIndex = 2, 0, 1  # z, x, y

        elif numpy.linalg.norm(numpy.cross(normal, (0., 0., 1.))) < 0.0017:
            if not 0 <= point[2] <= data.shape[0]:
                _logger.info("Plane outside dataset")
                return
            index = max(0, min(int(point[2]), data.shape[0] - 1))
            slice_ = data[index, :, :]
            xAxisIndex, yAxisIndex, normalAxisIndex = 0, 1, 2  # x, y, z
        else:
            _logger.warning('Unsupported normal: (%f, %f, %f)',
                            normal[0], normal[1], normal[2])
            return

        # Store cut plane image info

        self._isValid = True
        self._data = numpy.array(slice_, copy=True)
        self._index = index

        # Only store extra information when no transform matrix is set
        # Otherwise this information can be meaningless
        if numpy.all(numpy.equal(sfView.getTransformMatrix(),
                                 numpy.identity(3, dtype=numpy.float32))):
            labels = sfView.getAxesLabels()
            self._xLabel = labels[xAxisIndex]
            self._yLabel = labels[yAxisIndex]
            self._normalLabel = labels[normalAxisIndex]

            scale = sfView.getScale()
            self._scale = scale[xAxisIndex], scale[yAxisIndex]

            translation = sfView.getTranslation()
            self._translation = translation[xAxisIndex], translation[yAxisIndex]

            self._position = float(index * scale[normalAxisIndex] +
                                   translation[normalAxisIndex])

    def isValid(self):
        """Returns True if the cut plane image is defined (bool)"""
        return self._isValid

    def getData(self, copy=True):
        """Returns the image data sliced by the cut plane.

        :param bool copy: True to get a copy, False otherwise
        :return: The 2D image data corresponding to the cut plane
        :rtype: numpy.ndarray
        """
        return numpy.array(self._data, copy=copy)

    def getXLabel(self):
        """Returns the label associated to the X axis of the image (str)"""
        return self._xLabel

    def getYLabel(self):
        """Returns the label associated to the Y axis of the image (str)"""
        return self._yLabel

    def getNormalLabel(self):
        """Returns the label of the 3D axis of the plane normal (str)"""
        return self._normalLabel

    def getScale(self):
        """Returns the scales of the data as a 2-tuple of float (sx, sy)"""
        return self._scale

    def getTranslation(self):
        """Returns the offset of the data as a 2-tuple of float (ox, oy)"""
        return self._translation

    def getIndex(self):
        """Returns the index in the data array of the cut plane (int)"""
        return self._index

    def getPosition(self):
        """Returns the cut plane position along the normal axis (flaot)"""
        return self._position


class ScalarFieldView(Plot3DWindow):
    """Widget computing and displaying an iso-surface from a 3D scalar dataset.

    Limitation: Currently, iso-surfaces are generated with higher values
    than the iso-level 'inside' the surface.

    :param parent: See :class:`QMainWindow`
    """

    sigDataChanged = qt.Signal()
    """Signal emitted when the scalar data field has changed."""

    sigTransformChanged = qt.Signal()
    """Signal emitted when the transformation has changed.

    It is emitted by :meth:`setTranslation`, :meth:`setTransformMatrix`,
    :meth:`setScale`.
    """

    sigSelectedRegionChanged = qt.Signal(object)
    """Signal emitted when the selected region has changed.

    This signal provides the new selected region.
    """

    def __init__(self, parent=None):
        super(ScalarFieldView, self).__init__(parent)
        self._colormap = Colormap(
            name='gray', normalization='linear', vmin=None, vmax=None)
        self._selectedRange = None

        # Store iso-surfaces
        self._isosurfaces = []

        # Transformations
        self._dataScale = transform.Scale()
        self._dataTranslate = transform.Translate()
        self._dataTransform = transform.Matrix()   # default to identity

        self._foregroundColor = 1., 1., 1., 1.
        self._highlightColor = 0.7, 0.7, 0., 1.

        self._data = None
        self._dataRange = None

        self._group = primitives.BoundedGroup()
        self._group.transforms = [
            self._dataTranslate, self._dataTransform, self._dataScale]

        self._bbox = axes.LabelledAxes()
        self._bbox.children = [self._group]
        self._outerScale = transform.Scale(1., 1., 1.)
        self._bbox.transforms = [self._outerScale]
        self.getPlot3DWidget().viewport.scene.children.append(self._bbox)

        self._selectionBox = primitives.Box()
        self._selectionBox.strokeSmooth = False
        self._selectionBox.strokeWidth = 1.
        # self._selectionBox.fillColor = 1., 1., 1., 0.3
        # self._selectionBox.fillCulling = 'back'
        self._selectionBox.visible = False
        self._group.children.append(self._selectionBox)

        self._cutPlane = CutPlane(sfView=self)
        self._cutPlane.sigVisibilityChanged.connect(
            self._planeVisibilityChanged)
        planeStroke, dataPlane = self._cutPlane._get3DPrimitives()
        self._bbox.children.append(planeStroke)
        self._group.children.append(dataPlane)

        self._isogroup = primitives.GroupDepthOffset()
        self._isogroup.transforms = [
            # Convert from z, y, x from marching cubes to x, y, z
            transform.Matrix((
                (0., 0., 1., 0.),
                (0., 1., 0., 0.),
                (1., 0., 0., 0.),
                (0., 0., 0., 1.))),
            # Offset to match cutting plane coords
            transform.Translate(0.5, 0.5, 0.5)
        ]
        self._group.children.append(self._isogroup)

        self._initPanPlaneAction()

        self._updateColors()

        self.getPlot3DWidget().viewport.light.shininess = 32

    def saveConfig(self, ioDevice):
        """
        Saves this view state. Only isosurfaces at the moment. Does not save
        the isosurface's function.

        :param qt.QIODevice ioDevice: A `qt.QIODevice`.
        """

        stream = qt.QDataStream(ioDevice)

        stream.writeString('<ScalarFieldView>')

        isoSurfaces = self.getIsosurfaces()

        nIsoSurfaces = len(isoSurfaces)

        # TODO : delegate the serialization to the serialized items
        # isosurfaces
        if nIsoSurfaces:
            tagIn = '<IsoSurfaces nIso={0}>'.format(nIsoSurfaces)
            stream.writeString(tagIn)

            for surface in isoSurfaces:
                color = surface.getColor()
                level = surface.getLevel()
                visible = surface.isVisible()
                stream << color
                stream.writeDouble(level)
                stream.writeBool(visible)

            stream.writeString('</IsoSurfaces>')

        stream.writeString('<Style>')
        background = self.getBackgroundColor()
        foreground = self.getForegroundColor()
        highlight = self.getHighlightColor()
        stream << background << foreground << highlight
        stream.writeString('</Style>')

        stream.writeString('</ScalarFieldView>')

    def loadConfig(self, ioDevice):
        """
        Loads this view state.
        See ScalarFieldView.saveView to know what is supported at the moment.

        :param qt.QIODevice ioDevice: A `qt.QIODevice`.
        """

        tagStack = deque()

        tagInRegex = re.compile('<(?P<itemId>[^ /]*) *'
                                '(?P<args>.*)>')

        tagOutRegex = re.compile('</(?P<itemId>[^ ]*)>')

        tagRootInRegex = re.compile('<ScalarFieldView>')

        isoSurfaceArgsRegex = re.compile('nIso=(?P<nIso>[0-9]*)')

        stream = qt.QDataStream(ioDevice)

        tag = stream.readString()
        tagMatch = tagRootInRegex.match(tag)

        if tagMatch is None:
            # TODO : explicit error
            raise ValueError('Unknown data.')

        itemId = 'ScalarFieldView'

        tagStack.append(itemId)

        while True:

            tag = stream.readString()

            tagMatch = tagOutRegex.match(tag)
            if tagMatch:
                closeId = tagMatch.groupdict()['itemId']
                if closeId != itemId:
                    # TODO : explicit error
                    raise ValueError('Unexpected closing tag {0} '
                                     '(expected {1})'
                                     ''.format(closeId, itemId))

                if itemId == 'ScalarFieldView':
                    # reached end
                    break
                else:
                    itemId = tagStack.pop()
                    # fetching next tag
                    continue

            tagMatch = tagInRegex.match(tag)

            if tagMatch is None:
                # TODO : explicit error
                raise ValueError('Unknown data.')

            tagStack.append(itemId)

            matchDict = tagMatch.groupdict()

            itemId = matchDict['itemId']

            # TODO : delegate the deserialization to the serialized items
            if itemId == 'IsoSurfaces':
                argsMatch = isoSurfaceArgsRegex.match(matchDict['args'])
                if not argsMatch:
                    # TODO : explicit error
                    raise ValueError('Failed to parse args "{0}".'
                                     ''.format(matchDict['args']))
                argsDict = argsMatch.groupdict()
                nIso = int(argsDict['nIso'])
                if nIso:
                    for surface in self.getIsosurfaces():
                        self.removeIsosurface(surface)
                    for isoIdx in range(nIso):
                        color = qt.QColor()
                        stream >> color
                        level = stream.readDouble()
                        visible = stream.readBool()
                        surface = self.addIsosurface(level, color=color)
                        surface.setVisible(visible)
            elif itemId == 'Style':
                background = qt.QColor()
                foreground = qt.QColor()
                highlight = qt.QColor()
                stream >> background >> foreground >> highlight
                self.setBackgroundColor(background)
                self.setForegroundColor(foreground)
                self.setHighlightColor(highlight)
            else:
                raise ValueError('Unknown entry tag {0}.'
                                 ''.format(itemId))

    def _initPanPlaneAction(self):
        """Creates and init the pan plane action"""
        self._panPlaneAction = qt.QAction(self)
        self._panPlaneAction.setIcon(icons.getQIcon('3d-plane-pan'))
        self._panPlaneAction.setText('Pan plane')
        self._panPlaneAction.setCheckable(True)
        self._panPlaneAction.setToolTip(
            'Pan the cutting plane. Press <b>Ctrl</b> to rotate the scene.')
        self._panPlaneAction.setEnabled(False)

        self._panPlaneAction.triggered[bool].connect(self._planeActionTriggered)
        self.getPlot3DWidget().sigInteractiveModeChanged.connect(
            self._interactiveModeChanged)

        toolbar = self.findChild(InteractiveModeToolBar)
        if toolbar is not None:
            toolbar.addAction(self._panPlaneAction)

    def _planeActionTriggered(self, checked=False):
        self._panPlaneAction.setChecked(True)
        self.setInteractiveMode('plane')

    def _interactiveModeChanged(self):
        self._panPlaneAction.setChecked(self.getInteractiveMode() == 'plane')
        self._updateColors()

    def _planeVisibilityChanged(self, visible):
        """Handle visibility events from the plane"""
        if visible != self._panPlaneAction.isEnabled():
            self._panPlaneAction.setEnabled(visible)
            if visible:
                self.setInteractiveMode('plane')
            elif self._panPlaneAction.isChecked():
                self.setInteractiveMode('rotate')

    def setInteractiveMode(self, mode):
        """Choose the current interaction.

        :param str mode: Either rotate, pan or plane
        """
        if mode == self.getInteractiveMode():
            return

        sceneScale = self.getPlot3DWidget().viewport.scene.transforms[0]
        if mode == 'plane':
            mode = interaction.PanPlaneZoomOnWheelControl(
                self.getPlot3DWidget().viewport,
                self._cutPlane._get3DPrimitives()[0],
                mode='position',
                orbitAroundCenter=False,
                scaleTransform=sceneScale)

        self.getPlot3DWidget().setInteractiveMode(mode)
        self._updateColors()

    def getInteractiveMode(self):
        """Returns the current interaction mode, see :meth:`setInteractiveMode`
        """
        if isinstance(self.getPlot3DWidget().eventHandler,
                      interaction.PanPlaneZoomOnWheelControl):
            return 'plane'
        else:
            return self.getPlot3DWidget().getInteractiveMode()

    # Handle scalar field

    def setData(self, data, copy=True):
        """Set the 3D scalar data set to use for building the iso-surface.

        Dataset order is zyx (i.e., first dimension is z).

        :param data: scalar field from which to extract the iso-surface
        :type data: 3D numpy.ndarray of float32 with shape at least (2, 2, 2)
        :param bool copy:
            True (default) to make a copy,
            False to avoid copy (DO NOT MODIFY data afterwards)
        """
        if data is None:
            self._data = None
            self._dataRange = None
            self.setSelectedRegion(zrange=None, yrange=None, xrange_=None)
            self._group.shape = None
            self.centerScene()

        else:
            data = numpy.array(data, copy=copy, dtype=numpy.float32, order='C')
            assert data.ndim == 3
            assert min(data.shape) >= 2

            wasData = self._data is not None
            previousSelectedRegion = self.getSelectedRegion()

            self._data = data

            # Store data range info
            dataRange = min_max(self._data, min_positive=True, finite=True)
            if dataRange.minimum is None:  # Only non-finite data
                dataRange = None

            if dataRange is not None:
                min_positive = dataRange.min_positive
                if min_positive is None:
                    min_positive = float('nan')
                dataRange = dataRange.minimum, min_positive, dataRange.maximum
            self._dataRange = dataRange

            if previousSelectedRegion is not None:
                # Update selected region to ensure it is clipped to array range
                self.setSelectedRegion(*previousSelectedRegion.getArrayRange())

            self._group.shape = self._data.shape

            if not wasData:
                self.centerScene()  # Reset viewpoint the first time only

        # Update iso-surfaces
        for isosurface in self.getIsosurfaces():
            isosurface._setData(self._data, copy=False)

        self.sigDataChanged.emit()

    def getData(self, copy=True):
        """Get the 3D scalar data currently used to build the iso-surface.

        :param bool copy:
           True (default) to get a copy,
           False to get the internal data (DO NOT modify!)
        :return: The data set (or None if not set)
        """
        if self._data is None:
            return None
        else:
            return numpy.array(self._data, copy=copy)

    def getDataRange(self):
        """Return the range of the data as a 3-tuple of values.

        positive min is NaN if no data is positive.

        :return: (min, positive min, max) or None.
        """
        return self._dataRange

    # Transformations

    def setOuterScale(self, sx=1., sy=1., sz=1.):
        """Set the scale to apply to the whole scene including the axes.

        This is useful when axis lengths in data space are really different.

        :param float sx: Scale factor along the X axis
        :param float sy: Scale factor along the Y axis
        :param float sz: Scale factor along the Z axis
        """
        self._outerScale.setScale(sx, sy, sz)
        self.centerScene()

    def getOuterScale(self):
        """Returns the scales provided by :meth:`setOuterScale`.

        :rtype: numpy.ndarray
        """
        return self._outerScale.scale

    def setScale(self, sx=1., sy=1., sz=1.):
        """Set the scale of the 3D scalar field (i.e., size of a voxel).

        :param float sx: Scale factor along the X axis
        :param float sy: Scale factor along the Y axis
        :param float sz: Scale factor along the Z axis
        """
        scale = numpy.array((sx, sy, sz), dtype=numpy.float32)
        if not numpy.all(numpy.equal(scale, self.getScale())):
            self._dataScale.scale = scale
            self.sigTransformChanged.emit()
            self.centerScene()  # Reset viewpoint

    def getScale(self):
        """Returns the scales provided by :meth:`setScale` as a numpy.ndarray.
        """
        return self._dataScale.scale

    def setTranslation(self, x=0., y=0., z=0.):
        """Set the translation of the origin of the data array in data coordinates.

        :param float x: Offset of the data origin on the X axis
        :param float y: Offset of the data origin on the Y axis
        :param float z: Offset of the data origin on the Z axis
        """
        translation = numpy.array((x, y, z), dtype=numpy.float32)
        if not numpy.all(numpy.equal(translation, self.getTranslation())):
            self._dataTranslate.translation = translation
            self.sigTransformChanged.emit()
            self.centerScene()  # Reset viewpoint

    def getTranslation(self):
        """Returns the offset set by :meth:`setTranslation` as a numpy.ndarray.
        """
        return self._dataTranslate.translation

    def setTransformMatrix(self, matrix3x3):
        """Set the transform matrix applied to the data.

        :param numpy.ndarray matrix: 3x3 transform matrix
        """
        matrix3x3 = numpy.array(matrix3x3, copy=True, dtype=numpy.float32)
        if not numpy.all(numpy.equal(matrix3x3, self.getTransformMatrix())):
            matrix = numpy.identity(4, dtype=numpy.float32)
            matrix[:3, :3] = matrix3x3
            self._dataTransform.setMatrix(matrix)
            self.sigTransformChanged.emit()
            self.centerScene()  # Reset viewpoint

    def getTransformMatrix(self):
        """Returns the transform matrix applied to the data.

        See :meth:`setTransformMatrix`.

        :rtype: numpy.ndarray
        """
        return self._dataTransform.getMatrix()[:3, :3]

    # Axes labels

    def isBoundingBoxVisible(self):
        """Returns axes labels, grid and bounding box visibility.

        :rtype: bool
        """
        return self._bbox.boxVisible

    def setBoundingBoxVisible(self, visible):
        """Set axes labels, grid and bounding box visibility.

        :param bool visible: True to show axes, False to hide
        """
        visible = bool(visible)
        self._bbox.boxVisible = visible

    def setAxesLabels(self, xlabel=None, ylabel=None, zlabel=None):
        """Set the text labels of the axes.

        :param str xlabel: Label of the X axis, None to leave unchanged.
        :param str ylabel: Label of the Y axis, None to leave unchanged.
        :param str zlabel: Label of the Z axis, None to leave unchanged.
        """
        if xlabel is not None:
            self._bbox.xlabel = xlabel

        if ylabel is not None:
            self._bbox.ylabel = ylabel

        if zlabel is not None:
            self._bbox.zlabel = zlabel

    class _Labels(tuple):
        """Return type of :meth:`getAxesLabels`"""

        def getXLabel(self):
            """Label of the X axis (str)"""
            return self[0]

        def getYLabel(self):
            """Label of the Y axis (str)"""
            return self[1]

        def getZLabel(self):
            """Label of the Z axis (str)"""
            return self[2]

    def getAxesLabels(self):
        """Returns the text labels of the axes

        >>> widget = ScalarFieldView()
        >>> widget.setAxesLabels(xlabel='X')

        You can get the labels either as a 3-tuple:

        >>> xlabel, ylabel, zlabel = widget.getAxesLabels()

        Or as an object with methods getXLabel, getYLabel and getZLabel:

        >>> labels = widget.getAxesLabels()
        >>> labels.getXLabel()
        ... 'X'

        :return: object describing the labels
        """
        return self._Labels((self._bbox.xlabel,
                             self._bbox.ylabel,
                             self._bbox.zlabel))

    # Colors

    def _updateColors(self):
        """Update item depending on foreground/highlight color"""
        self._bbox.tickColor = self._foregroundColor
        self._selectionBox.strokeColor = self._foregroundColor
        if self.getInteractiveMode() == 'plane':
            self._cutPlane.setStrokeColor(self._highlightColor)
            self._bbox.color = self._foregroundColor
        else:
            self._cutPlane.setStrokeColor(self._foregroundColor)
            self._bbox.color = self._highlightColor

    def getForegroundColor(self):
        """Return color used for text and bounding box (QColor)"""
        return qt.QColor.fromRgbF(*self._foregroundColor)

    def setForegroundColor(self, color):
        """Set the foreground color.

        :param color: RGB color: name, #RRGGBB or RGB values
        :type color:
            QColor, str or array-like of 3 or 4 float in [0., 1.] or uint8
        """
        color = rgba(color)
        if color != self._foregroundColor:
            self._foregroundColor = color
            self._updateColors()

    def getHighlightColor(self):
        """Return color used for highlighted item bounding box (QColor)"""
        return qt.QColor.fromRgbF(*self._highlightColor)

    def setHighlightColor(self, color):
        """Set hightlighted item color.

        :param color: RGB color: name, #RRGGBB or RGB values
        :type color:
            QColor, str or array-like of 3 or 4 float in [0., 1.] or uint8
        """
        color = rgba(color)
        if color != self._highlightColor:
            self._highlightColor = color
            self._updateColors()

    # Cut Plane

    def getCutPlanes(self):
        """Return an iterable of all cut planes of the view.

        This includes hidden cut planes.

        For now, there is always one cut plane.
        """
        return (self._cutPlane,)

    # Selection

    def setSelectedRegion(self, zrange=None, yrange=None, xrange_=None):
        """Set the 3D selected region aligned with the axes.

        Provided range are array indices range.
        The provided ranges are clipped to the data.
        If a range is None, the range of the array on this dimension is used.

        :param zrange: (zmin, zmax) range of the selection
        :param yrange: (ymin, ymax) range of the selection
        :param xrange_: (xmin, xmax) range of the selection
        """
        # No range given: unset selection
        if zrange is None and yrange is None and xrange_ is None:
            selectedRange = None

        else:
            # Handle default ranges
            if self._data is not None:
                if zrange is None:
                    zrange = 0, self._data.shape[0]
                if yrange is None:
                    yrange = 0, self._data.shape[1]
                if xrange_ is None:
                    xrange_ = 0, self._data.shape[2]

            elif None in (xrange_, yrange, zrange):
                # One of the range is None and no data available
                raise RuntimeError(
                    'Data is not set, cannot get default range from it.')

            # Clip selected region to data shape and make sure min <= max
            selectedRange = numpy.array((
                (max(0, min(*zrange)),
                 min(self._data.shape[0], max(*zrange))),
                (max(0, min(*yrange)),
                 min(self._data.shape[1], max(*yrange))),
                (max(0, min(*xrange_)),
                 min(self._data.shape[2], max(*xrange_))),
                ), dtype=numpy.int)

        # numpy.equal supports None
        if not numpy.all(numpy.equal(selectedRange, self._selectedRange)):
            self._selectedRange = selectedRange

            # Update scene accordingly
            if self._selectedRange is None:
                self._selectionBox.visible = False
            else:
                self._selectionBox.visible = True
                scales = self._selectedRange[:, 1] - self._selectedRange[:, 0]
                self._selectionBox.size = scales[::-1]
                self._selectionBox.transforms = [
                    transform.Translate(*self._selectedRange[::-1, 0])]

            self.sigSelectedRegionChanged.emit(self.getSelectedRegion())

    def getSelectedRegion(self):
        """Returns the currently selected region or None."""
        if self._selectedRange is None:
            return None
        else:
            dataBBox = self._group.transforms.transformBounds(
                self._selectedRange[::-1].T).T
            return SelectedRegion(self._selectedRange, dataBBox,
                                  translation=self.getTranslation(),
                                  scale=self.getScale())

    # Handle iso-surfaces

    sigIsosurfaceAdded = qt.Signal(object)
    """Signal emitted when a new iso-surface is added to the view.

    The newly added iso-surface is provided by this signal
    """

    sigIsosurfaceRemoved = qt.Signal(object)
    """Signal emitted when an iso-surface is removed from the view

    The removed iso-surface is provided by this signal.
    """

    def addIsosurface(self, level, color):
        """Add an iso-surface to the view.

        :param level:
            The value at which to build the iso-surface or a callable
            (e.g., a function) taking a 3D numpy.ndarray as input and
            returning a float.
            Example: numpy.mean(data) + numpy.std(data)
        :type level: float or callable
        :param color: RGBA color of the isosurface
        :type color: str or array-like of 4 float in [0., 1.]
        :return: Isosurface object describing this isosurface
        """
        isosurface = Isosurface(parent=self)
        isosurface.setColor(color)
        if callable(level):
            isosurface.setAutoLevelFunction(level)
        else:
            isosurface.setLevel(level)
        isosurface._setData(self._data, copy=False)
        isosurface.sigLevelChanged.connect(self._updateIsosurfaces)

        self._isosurfaces.append(isosurface)

        self._updateIsosurfaces()

        self.sigIsosurfaceAdded.emit(isosurface)
        return isosurface

    def getIsosurfaces(self):
        """Return an iterable of all iso-surfaces of the view"""
        return tuple(self._isosurfaces)

    def removeIsosurface(self, isosurface):
        """Remove an iso-surface from the view.

        :param isosurface: The isosurface object to remove"""
        if isosurface not in self.getIsosurfaces():
            _logger.warning(
                "Try to remove isosurface that is not in the list: %s",
                str(isosurface))
        else:
            isosurface.sigLevelChanged.disconnect(self._updateIsosurfaces)
            self._isosurfaces.remove(isosurface)
            self._updateIsosurfaces()
            self.sigIsosurfaceRemoved.emit(isosurface)

    def clearIsosurfaces(self):
        """Remove all iso-surfaces from the view."""
        for isosurface in self.getIsosurfaces():
            self.removeIsosurface(isosurface)

    def _updateIsosurfaces(self, level=None):
        """Handle updates of iso-surfaces level and add/remove"""
        # Sorting using minus, this supposes data 'object' to be max values
        sortedIso = sorted(self.getIsosurfaces(),
                           key=lambda iso: - iso.getLevel())
        self._isogroup.children = [iso._get3DPrimitive() for iso in sortedIso]