summaryrefslogtreecommitdiff
path: root/silx/gui/data/test/test_arraywidget.py
blob: 6bcbbd3641ff37111effc4de6d5dc37b5ea0588a (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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016 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.
#
# ###########################################################################*/
__authors__ = ["P. Knobel"]
__license__ = "MIT"
__date__ = "05/12/2016"

import os
import tempfile
import unittest

import numpy

from silx.gui import qt
from silx.gui.data import ArrayTableWidget
from silx.gui.utils.testutils import TestCaseQt

import h5py


class TestArrayWidget(TestCaseQt):
    """Basic test for ArrayTableWidget with a numpy array"""
    def setUp(self):
        super(TestArrayWidget, self).setUp()
        self.aw = ArrayTableWidget.ArrayTableWidget()

    def tearDown(self):
        del self.aw
        super(TestArrayWidget, self).tearDown()

    def testShow(self):
        """test for errors"""
        self.aw.show()
        self.qWaitForWindowExposed(self.aw)

    def testSetData0D(self):
        a = 1
        self.aw.setArrayData(a)
        b = self.aw.getData(copy=True)

        self.assertTrue(numpy.array_equal(a, b))

        # scalar/0D data has no frame index
        self.assertEqual(len(self.aw.model._index), 0)
        # and no perspective
        self.assertEqual(len(self.aw.model._perspective), 0)

    def testSetData1D(self):
        a = [1, 2]
        self.aw.setArrayData(a)
        b = self.aw.getData(copy=True)

        self.assertTrue(numpy.array_equal(a, b))

        # 1D data has no frame index
        self.assertEqual(len(self.aw.model._index), 0)
        # and no perspective
        self.assertEqual(len(self.aw.model._perspective), 0)

    def testSetData4D(self):
        a = numpy.reshape(numpy.linspace(0.213, 1.234, 1250),
                          (5, 5, 5, 10))
        self.aw.setArrayData(a)

        # default perspective (0, 1)
        self.assertEqual(list(self.aw.model._perspective),
                         [0, 1])
        self.aw.setPerspective((1, 3))
        self.assertEqual(list(self.aw.model._perspective),
                         [1, 3])

        b = self.aw.getData(copy=True)
        self.assertTrue(numpy.array_equal(a, b))

        # 4D data has a 2-tuple as frame index
        self.assertEqual(len(self.aw.model._index), 2)
        # default index is (0, 0)
        self.assertEqual(list(self.aw.model._index),
                         [0, 0])
        self.aw.setFrameIndex((3, 1))

        self.assertEqual(list(self.aw.model._index),
                         [3, 1])

    def testColors(self):
        a = numpy.arange(256, dtype=numpy.uint8)
        self.aw.setArrayData(a)

        bgcolor = numpy.empty(a.shape + (3,), dtype=numpy.uint8)
        # Black & white palette
        bgcolor[..., 0] = a
        bgcolor[..., 1] = a
        bgcolor[..., 2] = a

        fgcolor = numpy.bitwise_xor(bgcolor, 255)

        self.aw.setArrayColors(bgcolor, fgcolor)

        # test colors are as expected in model
        for i in range(256):
            # all RGB channels for BG equal to data value
            self.assertEqual(
                self.aw.model.data(self.aw.model.index(0, i),
                                   role=qt.Qt.BackgroundRole),
                qt.QColor(i, i, i),
                "Unexpected background color"
            )

            # all RGB channels for FG equal to XOR(data value, 255)
            self.assertEqual(
                self.aw.model.data(self.aw.model.index(0, i),
                                   role=qt.Qt.ForegroundRole),
                qt.QColor(i ^ 255, i ^ 255, i ^ 255),
                "Unexpected text color"
            )

        # test colors are reset to None when a new data array is loaded
        # with different shape
        self.aw.setArrayData(numpy.arange(300))

        for i in range(300):
            # all RGB channels for BG equal to data value
            self.assertIsNone(
                self.aw.model.data(self.aw.model.index(0, i),
                                   role=qt.Qt.BackgroundRole))

    def testDefaultFlagNotEditable(self):
        """editable should be False by default, in setArrayData"""
        self.aw.setArrayData([[0]])
        idx = self.aw.model.createIndex(0, 0)
        # model is editable
        self.assertFalse(
                self.aw.model.flags(idx) & qt.Qt.ItemIsEditable)

    def testFlagEditable(self):
        self.aw.setArrayData([[0]], editable=True)
        idx = self.aw.model.createIndex(0, 0)
        # model is editable
        self.assertTrue(
                self.aw.model.flags(idx) & qt.Qt.ItemIsEditable)

    def testFlagNotEditable(self):
        self.aw.setArrayData([[0]], editable=False)
        idx = self.aw.model.createIndex(0, 0)
        # model is editable
        self.assertFalse(
                self.aw.model.flags(idx) & qt.Qt.ItemIsEditable)

    def testReferenceReturned(self):
        """when setting the data with copy=False and
        retrieving it with getData(copy=False), we should recover
        the same original object.
        """
        # n-D (n >=2)
        a0 = numpy.reshape(numpy.linspace(0.213, 1.234, 1000),
                           (10, 10, 10))
        self.aw.setArrayData(a0, copy=False)
        a1 = self.aw.getData(copy=False)

        self.assertIs(a0, a1)

        # 1D
        b0 = numpy.linspace(0.213, 1.234, 1000)
        self.aw.setArrayData(b0, copy=False)
        b1 = self.aw.getData(copy=False)
        self.assertIs(b0, b1)


class TestH5pyArrayWidget(TestCaseQt):
    """Basic test for ArrayTableWidget with a dataset.

    Test flags, for dataset open in read-only or read-write modes"""
    def setUp(self):
        super(TestH5pyArrayWidget, self).setUp()
        self.aw = ArrayTableWidget.ArrayTableWidget()
        self.data = numpy.reshape(numpy.linspace(0.213, 1.234, 1000),
                                  (10, 10, 10))
        # create an h5py file with a dataset
        self.tempdir = tempfile.mkdtemp()
        self.h5_fname = os.path.join(self.tempdir, "array.h5")
        h5f = h5py.File(self.h5_fname)
        h5f["my_array"] = self.data
        h5f["my_scalar"] = 3.14
        h5f["my_1D_array"] = numpy.array(numpy.arange(1000))
        h5f.close()

    def tearDown(self):
        del self.aw
        os.unlink(self.h5_fname)
        os.rmdir(self.tempdir)
        super(TestH5pyArrayWidget, self).tearDown()

    def testShow(self):
        self.aw.show()
        self.qWaitForWindowExposed(self.aw)

    def testReadOnly(self):
        """Open H5 dataset in read-only mode, ensure the model is not editable."""
        h5f = h5py.File(self.h5_fname, "r")
        a = h5f["my_array"]
        # ArrayTableModel relies on following condition
        self.assertTrue(a.file.mode == "r")

        self.aw.setArrayData(a, copy=False, editable=True)

        self.assertIsInstance(a, h5py.Dataset)   # simple sanity check
        # internal representation must be a reference to original data (copy=False)
        self.assertIsInstance(self.aw.model._array, h5py.Dataset)
        self.assertTrue(self.aw.model._array.file.mode == "r")

        b = self.aw.getData()
        self.assertTrue(numpy.array_equal(self.data, b))

        # model must have detected read-only dataset and disabled editing
        self.assertFalse(self.aw.model._editable)
        idx = self.aw.model.createIndex(0, 0)
        self.assertFalse(
                 self.aw.model.flags(idx) & qt.Qt.ItemIsEditable)

        # force editing read-only datasets raises IOError
        self.assertRaises(IOError, self.aw.model.setData,
                          idx, 123.4, role=qt.Qt.EditRole)
        h5f.close()

    def testReadWrite(self):
        h5f = h5py.File(self.h5_fname, "r+")
        a = h5f["my_array"]
        self.assertTrue(a.file.mode == "r+")

        self.aw.setArrayData(a, copy=False, editable=True)
        b = self.aw.getData(copy=False)
        self.assertTrue(numpy.array_equal(self.data, b))

        idx = self.aw.model.createIndex(0, 0)
        # model is editable
        self.assertTrue(
                self.aw.model.flags(idx) & qt.Qt.ItemIsEditable)
        h5f.close()

    def testSetData0D(self):
        h5f = h5py.File(self.h5_fname, "r+")
        a = h5f["my_scalar"]
        self.aw.setArrayData(a)
        b = self.aw.getData(copy=True)

        self.assertTrue(numpy.array_equal(a, b))

        h5f.close()

    def testSetData1D(self):
        h5f = h5py.File(self.h5_fname, "r+")
        a = h5f["my_1D_array"]
        self.aw.setArrayData(a)
        b = self.aw.getData(copy=True)

        self.assertTrue(numpy.array_equal(a, b))

        h5f.close()

    def testReferenceReturned(self):
        """when setting the data with copy=False and
        retrieving it with getData(copy=False), we should recover
        the same original object.

        This only works for array with at least 2D. For 1D and 0D
        arrays, a view is created at some point, which  in the case
        of an hdf5 dataset creates a copy."""
        h5f = h5py.File(self.h5_fname, "r+")

        # n-D
        a0 = h5f["my_array"]
        self.aw.setArrayData(a0, copy=False)
        a1 = self.aw.getData(copy=False)
        self.assertIs(a0, a1)

        # 1D
        b0 = h5f["my_1D_array"]
        self.aw.setArrayData(b0, copy=False)
        b1 = self.aw.getData(copy=False)
        self.assertIs(b0, b1)

        h5f.close()


def suite():
    test_suite = unittest.TestSuite()
    test_suite.addTest(
        unittest.defaultTestLoader.loadTestsFromTestCase(TestArrayWidget))
    test_suite.addTest(
        unittest.defaultTestLoader.loadTestsFromTestCase(TestH5pyArrayWidget))
    return test_suite


if __name__ == '__main__':
    unittest.main(defaultTest='suite')