test_core.py 12.4 KB
Newer Older
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
1
2
import numpy as np
from tempfile import NamedTemporaryFile
3
import pickle
4
5
import unittest
import tfields
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
6

7
ATOL = 1e-8
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
8

9

dboe's avatar
dboe committed
10
class Base_Check(object):
dboe's avatar
dboe committed
11
    def demand_equal(self, other):
dboe's avatar
dboe committed
12
        self.assertIsInstance(other, type(self._inst))
dboe's avatar
dboe committed
13
14
15
16
17
18
19
20
21
22
23

    def test_pickle(self):
        with NamedTemporaryFile(suffix='.pickle') as out_file:
            pickle.dump(self._inst,
                        out_file)
            out_file.flush()
            out_file.seek(0)
            reloaded = pickle.load(out_file)

        self.demand_equal(reloaded)

dboe's avatar
dboe committed
24
25
26
27
28
29
    def test_deep_copy(self):
        from copy import deepcopy
        copy = deepcopy(self._inst)
        self.demand_equal(copy)
        self.assertIsNot(self._inst, copy)

30
31
32
    def test_implicit_copy(self):
        copy = type(self._inst)(self._inst)
        self.demand_equal(copy)
dboe's avatar
dboe committed
33
        self.assertIsNot(self._inst, copy)
34
35
36
37
38

    def test_explicit_copy(self):
        copy = self._inst.copy()
        self.demand_equal(copy)
        self.assertIsNot(self._inst, copy)
dboe's avatar
dboe committed
39

dboe's avatar
dboe committed
40
41
42
43
    def test_save_npz(self):
        out_file = NamedTemporaryFile(suffix='.npz')
        self._inst.save(out_file.name)
        _ = out_file.seek(0)  # this is only necessary in the test
44
        load_inst = type(self._inst).load(out_file.name)
dboe's avatar
dboe committed
45
46
47
48
        # allow_pickle=True)  ?

        self.demand_equal(load_inst)

49
    def test_dict(self):
dboe's avatar
dboe committed
50
51
        d = self._inst._as_new_dict()
        other = type(self._inst)._from_new_dict(d)
52
        self.demand_equal(other)
dboe's avatar
dboe committed
53
54
55
        # d = self._inst._as_dict()
        # other = type(self._inst)._from_dict(**d)
        # self.demand_equal(other)
56

dboe's avatar
dboe committed
57
58
59
60
    def tearDown(self):
        del self._inst


dboe's avatar
dboe committed
61
62
63
64
class AbstractNdarray_Check(Base_Check):
    pass


dboe's avatar
dboe committed
65
class Tensors_Check(AbstractNdarray_Check):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
66
    """
67
    Testing derivatives of Tensors
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
68
69
70
    """
    _inst = None

dboe's avatar
dboe committed
71
    def demand_equal(self, other, atol=False, transformed=False):
dboe's avatar
dboe committed
72
        super().demand_equal(other)
dboe's avatar
dboe committed
73
74
75
76
77
78
79
80
        if atol:
            self.assertTrue(self._inst.equal(other, atol=ATOL))
        else:
            self.assertTrue(self._inst.equal(other))
        if not transformed:
            self.assertEqual(self._inst.coord_sys, other.coord_sys)
        self.assertEqual(self._inst.name, other.name)

dboe's avatar
dboe committed
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
    def test_slice_indexing(self):
        self.demand_index_equal(slice(0, None, None), 'type')

    def test_pick_indexing(self):
        self.demand_index_equal(0, (np.ndarray, np.integer, np.float))

    def test_mask_indexing(self):
        mask = np.array([True if i % 2 == 0 else False
                         for i in range(len(self._inst))])
        self.demand_index_equal(mask, 'type')

    def test_iteration(self):
        # iteration
        iterator = iter(self._inst)
        if len(self._inst) > 0:
            next(iterator)

    def demand_index_equal(self, index, check_type):
        if check_type == 'type':
            check_type = type(self._inst)
        tensors = np.array(self._inst)
        if len(self._inst) > 0:

            item = self._inst[index]
            self.assertTrue(np.array_equal(item, tensors[index]))
            self.assertIsInstance(item, check_type)

    def check_indexing(self):
        if not self._inst.fields and len(self._inst) == 0:
            return
        fields = [np.array(field) for field in self._inst.fields]
        for f, field in enumerate(fields):
            self._inst.fields[f]

Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
115
    def test_self_equality(self):
116
        # Test equality
dboe's avatar
dboe committed
117
118
119
120
        self.demand_equal(self._inst)
        transformer = self._inst.copy()
        transformer.transform(tfields.bases.CYLINDER)
        self.demand_equal(transformer, atol=True, transformed=True)
dboe's avatar
dboe committed
121
        # self.assertIs(self._inst, np.asarray(self._inst))  # TODO investigate
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
122
123

    def test_cylinderTrafo(self):
124
        # Test coordinate transformations in circle
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
125
126
127
128
129
        transformer = self._inst.copy()
        transformer.transform(tfields.bases.CYLINDER)
        if len(self._inst) > 0:
            self.assertFalse(np.array_equal(self._inst, transformer))
        transformer.transform(tfields.bases.CARTESIAN)
dboe's avatar
dboe committed
130
        self.demand_equal(transformer, atol=True, transformed=True)
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
131
132

    def test_spericalTrafo(self):
133
        # Test coordinate transformations in circle
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
134
135
136
        transformer = self._inst.copy()
        transformer.transform(tfields.bases.SPHERICAL)
        transformer.transform(tfields.bases.CARTESIAN)
dboe's avatar
dboe committed
137
        self.demand_equal(transformer, atol=True, transformed=True)
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
138
139

    def test_basic_merge(self):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
140
        # create 3 copies with different coord_sys
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
141
142
143
144
        merge_list = [self._inst.copy() for i in range(3)]
        merge_list[0].transform(tfields.bases.CARTESIAN)
        merge_list[1].transform(tfields.bases.CYLINDER)
        merge_list[2].transform(tfields.bases.SPHERICAL)
145

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
146
        # merge them and check that the first coord_sys is taken
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
147
        obj = type(self._inst).merged(*merge_list)
148
        self.assertTrue(obj.coord_sys == tfields.bases.CARTESIAN)
149

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
150
        # check that all copies are the same also with new coord_sys
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
151
152
153
154
        for i in range(len(merge_list)):
            value = np.allclose(merge_list[0],
                                obj[i * len(self._inst): (i + 1) *
                                    len(self._inst)],
155
                                atol=ATOL)
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
156
157
            self.assertTrue(value)

158
159
        obj_cs = type(self._inst).merged(*merge_list,
                                         coord_sys=tfields.bases.CYLINDER)
160
161
162
163
164
165
        for i in range(len(merge_list)):
            value = np.allclose(merge_list[1],
                                obj_cs[i * len(self._inst): (i + 1) *
                                       len(self._inst)],
                                atol=ATOL)
            self.assertTrue(value)
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
166

167

dboe's avatar
dboe committed
168
class TensorFields_Check(Tensors_Check):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
169
    def test_fields(self):
dboe's avatar
dboe committed
170
        self.assertIsNotNone(self._inst.fields)
dboe's avatar
dboe committed
171
172
173
174
175
176
177
178
179
        if self._inst.fields:
            # field is of type list
            self.assertTrue(isinstance(self._inst.fields, list))
            self.assertTrue(len(self._inst.fields) == len(self._fields))

            for field, target_field in zip(self._inst.fields, self._fields):
                self.assertTrue(np.array_equal(field, target_field))
                # fields are copied not reffered by a pointer
                self.assertFalse(field is target_field)
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
180

dboe's avatar
dboe committed
181
182
183
184
185
186
187
188
189
190
191
192
    def demand_index_equal(self, index, check_type):
        super().demand_index_equal(index, check_type)

        if len(self._inst) > 0:
            item = self._inst[index]
            for i, field in enumerate(self._inst.fields):
                if check_type == 'type':
                    check_type = type(self._inst.fields[i])
                self.assertTrue(np.array_equal(
                    item.fields[i], np.array(self._inst.fields[i])[index]))
                self.assertIsInstance(item.fields[i], check_type)

193

dboe's avatar
dboe committed
194
195
196
197
class TensorMaps_Check(TensorFields_Check):
    def test_maps(self):
        self.assertIsNotNone(self._inst.maps)

dboe's avatar
dboe committed
198
199
200
201
202
203
204
    def test_cleaned(self):
        clean = self._inst.cleaned()
        # no faces are removed
        for map_dim in self._inst.maps:
            self.assertEqual(len(self._inst.maps[map_dim]),
                             len(clean.maps[map_dim]))

dboe's avatar
dboe committed
205
206
207
208
    def demand_index_equal(self, index, check_type):
        super().demand_index_equal(index, check_type)
        # TODO: this is hard to check generically

dboe's avatar
dboe committed
209

Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
210
211
212
213
214
"""
EMPTY TESTS
"""


dboe's avatar
dboe committed
215
class Tensors_Empty_Test(Tensors_Check, unittest.TestCase):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
216
217
218
219
    def setUp(self):
        self._inst = tfields.Tensors([], dim=3)


dboe's avatar
dboe committed
220
class TensorFields_Empty_Test(TensorFields_Check, unittest.TestCase):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
221
222
223
    def setUp(self):
        self._fields = []
        self._inst = tfields.TensorFields([], dim=3)
224
225


dboe's avatar
dboe committed
226
class TensorMaps_Empty_Test(TensorMaps_Check, unittest.TestCase):
227
228
229
230
231
    def setUp(self):
        self._fields = []
        self._inst = tfields.TensorMaps([], dim=3)
        self._maps = []
        self._maps_fields = []
232

Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
233

dboe's avatar
dboe committed
234
class TensorFields_Test(TensorFields_Empty_Test):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
235
236
    def setUp(self):
        base = [(-5, 5, 11)] * 3
237
        self._fields = [tfields.Tensors.grid(*base, coord_sys='cylinder'),
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
238
239
240
241
                        tfields.Tensors(range(11**3))]
        tensors = tfields.Tensors.grid(*base)
        self._inst = tfields.TensorFields(tensors, *self._fields)

Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
242
243
244
        self.assertTrue(self._fields[0].coord_sys, 'cylinder')
        self.assertTrue(self._fields[1].coord_sys, 'cartesian')

Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
245

dboe's avatar
dboe committed
246
class TensorMaps_Test(TensorMaps_Empty_Test):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
247
248
249
    def setUp(self):
        base = [(-1, 1, 3)] * 3
        tensors = tfields.Tensors.grid(*base)
250
        self._fields = [tfields.Tensors.grid(*base, coord_sys='cylinder'),
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
                        tfields.Tensors(range(len(tensors)))]
        self._maps_tensors = [[[0, 0, 0],
                               [1, 2, 3],
                               [1, 5, 9]],
                              [[0, 4],
                               [1, 3]],
                              [[42]]]
        self._maps_fields = [[[42., 21., 11]],
                             [[3, 25]],
                             [[111]]]
        self._maps = [tfields.TensorFields(map_tensors,
                                           *map_fields) for map_tensors,
                      map_fields in zip(self._maps_tensors, self._maps_fields)]
        self._inst = tfields.TensorMaps(tensors, *self._fields,
                                        maps=self._maps)


dboe's avatar
[A    
dboe committed
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
class TensorMaps_Indexing_Test(unittest.TestCase):
    def setUp(self):
        tensors = np.arange(10).reshape((-1, 1))
        self._maps_tensors = [[[0, 0, 0],
                               [1, 2, 3],
                               [3, 5, 9]],
                              [[6, 4],
                               [7, 8]],
                              [[7]]]
        self._inst = tfields.TensorMaps(tensors,
                                        maps=self._maps_tensors)

    def test_pick_indexing(self):
        pick = self._inst[7]
        self.assertTrue(pick.equal([7]))
        self.assertTrue(np.array_equal(pick.maps[1], [[0]]))
        self.assertTrue(len(pick.maps), 1)

        pick = self._inst[0]
        self.assertTrue(pick.equal([[0]]))
        self.assertTrue(np.array_equal(pick.maps[3], [[0, 0, 0]]))
        self.assertTrue(len(pick.maps), 1)

    def test_slice_indexing(self):
        slce = self._inst[1:7]
        self.assertTrue(slce.equal([[1], [2], [3], [4], [5], [6]]))
        self.assertTrue(np.array_equal(slce.maps[3], [[0, 1, 2]]))
        self.assertTrue(np.array_equal(slce.maps[2], [[5, 3]]))
        self.assertTrue(len(slce.maps), 2)

    def test_mask_indexing(self):
        mask = self._inst[np.array([False, True, True, True, True,
                                    True, True, False, False, False])]
        self.assertTrue(mask.equal([[1], [2], [3], [4], [5], [6]]))
        self.assertTrue(np.array_equal(mask.maps[3], [[0, 1, 2]]))
        self.assertTrue(np.array_equal(mask.maps[2], [[5, 3]]))
        self.assertTrue(len(mask.maps), 2)


dboe's avatar
dboe committed
307
308
309
310
311
312
313
314
class TensorMaps_NoFields_Test(TensorMaps_Test):
    def setUp(self):
        self._inst = tfields.TensorMaps(
            [[1, 2, 3], [3, 3, 3], [0, 0, 0], [5, 6, 7]],
            maps=[[[0, 1, 2], [1, 2, 3]], [[1]], [[0, 1, 2, 3]]]
        )


dboe's avatar
dboe committed
315
316
class Maps_Test(Base_Check, unittest.TestCase):
    def demand_equal(self, other):
dboe's avatar
dboe committed
317
        super().demand_equal(other)
dboe's avatar
dboe committed
318
319
320
        self._inst.equal(other)

    def setUp(self):
dboe's avatar
dboe committed
321
322
323
324
325
326
327
        self._inst = tfields.Maps(
            [[[0, 0, 0],
              [1, 2, 3],
              [1, 5, 9]],
             [[0, 4],
              [1, 3]],
             [[42]]])
dboe's avatar
dboe committed
328
329


dboe's avatar
dboe committed
330
331
class Container_Check(AbstractNdarray_Check):
    def demand_equal(self, other):
dboe's avatar
dboe committed
332
        super().demand_equal(other)
dboe's avatar
dboe committed
333
334
335
336
337
338
339
340
341
342
343
        for i, item in enumerate(self._inst.items):
            if issubclass(type(item), tfields.core.AbstractNdarray):
                self.assertTrue(other.items[i].equal(item))
            else:
                self.assertEqual(other.items[i], item)
            try:
                self._inst.labels[i]
            except (IndexError, TypeError):
                pass
            else:
                self.assertEqual(other.labels[i], self._inst.labels[i])
dboe's avatar
dboe committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358

    def test_item(self):
        if len(self._inst.items) > 0:
            self.assertEqual(len(self._inst), len(self._inst))
            self.assertEqual(type(self._inst), type(self._inst))


class Container_Test(Container_Check, unittest.TestCase):
    def setUp(self):
        sphere = tfields.Mesh3D.grid(
            (1, 1, 1),
            (-np.pi, np.pi, 3),
            (-np.pi / 2, np.pi / 2, 3),
            coord_sys='spherical')
        sphere2 = sphere.copy() * 3
dboe's avatar
dboe committed
359
        self._inst = tfields.Container([sphere, sphere2], labels=['test'])
dboe's avatar
dboe committed
360
361


Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
362
363
if __name__ == '__main__':
    unittest.main()