test_core.py 14.7 KB
Newer Older
dboe's avatar
dboe committed
1
# pylint:disable=missing_function_docstring
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
2
3
import numpy as np
from tempfile import NamedTemporaryFile
4
import pickle
dboe's avatar
dboe committed
5
import pathlib
6
7
import unittest
import tfields
dboe's avatar
dboe committed
8
import uuid
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
9

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

12

dboe's avatar
dboe committed
13
# pylint:disable=no-member
dboe's avatar
dboe committed
14
class Base_Check(object):
dboe's avatar
dboe committed
15
    def demand_equal(self, other):
dboe's avatar
dboe committed
16
        self.assertIsInstance(other, type(self._inst))
dboe's avatar
dboe committed
17

dboe's avatar
dboe committed
18
19
20
21
    def demand_deep_copy(self, other):
        self.demand_equal(other)
        self.assertIsNot(self._inst, other)

dboe's avatar
dboe committed
22
    def test_pickle(self):
dboe's avatar
dboe committed
23
24
        with NamedTemporaryFile(suffix=".pickle") as out_file:
            pickle.dump(self._inst, out_file)
dboe's avatar
dboe committed
25
26
27
28
29
30
            out_file.flush()
            out_file.seek(0)
            reloaded = pickle.load(out_file)

        self.demand_equal(reloaded)

dboe's avatar
dboe committed
31
32
    def test_deep_copy(self):
        from copy import deepcopy
dboe's avatar
dboe committed
33

dboe's avatar
dboe committed
34
35
        other = deepcopy(self._inst)
        self.demand_deep_copy(other)
dboe's avatar
dboe committed
36

37
    def test_implicit_copy(self):
dboe's avatar
dboe committed
38
39
        other = type(self._inst)(self._inst)
        self.demand_deep_copy(other)
40
41

    def test_explicit_copy(self):
dboe's avatar
dboe committed
42
43
        other = self._inst.copy()
        self.demand_deep_copy(other)
dboe's avatar
dboe committed
44

dboe's avatar
dboe committed
45
    def test_save_npz(self):
dboe's avatar
dboe committed
46
        out_file = NamedTemporaryFile(suffix=".npz")
dboe's avatar
dboe committed
47
48
        self._inst.save(out_file.name)
        _ = out_file.seek(0)  # this is only necessary in the test
49
        load_inst = type(self._inst).load(out_file.name)
dboe's avatar
dboe committed
50
51
52
53
        # allow_pickle=True)  ?

        self.demand_equal(load_inst)

54
    def test_dict(self):
dboe's avatar
dboe committed
55
56
        d = self._inst._as_dict()
        other = type(self._inst)._from_dict(d)
57
58
        self.demand_equal(other)

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


dboe's avatar
dboe committed
63
64
65
66
class AbstractNdarray_Check(Base_Check):
    pass


dboe's avatar
dboe committed
67
# pylint:disable=no-member
dboe's avatar
dboe committed
68
class Tensors_Check(AbstractNdarray_Check):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
69
    """
70
    Testing derivatives of Tensors
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
71
    """
dboe's avatar
dboe committed
72

Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
73
74
    _inst = None

dboe's avatar
dboe committed
75
    def demand_equal(self, other, atol=False, transformed=False):
dboe's avatar
dboe committed
76
        super().demand_equal(other)
dboe's avatar
dboe committed
77
78
79
80
81
82
83
84
        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
85
    def test_slice_indexing(self):
dboe's avatar
dboe committed
86
        self.demand_index_equal(slice(0, None, None), "type")
dboe's avatar
dboe committed
87
88

    def test_pick_indexing(self):
dboe's avatar
dboe committed
89
        self.demand_index_equal(0, (np.ndarray, np.integer, float))
dboe's avatar
dboe committed
90
91

    def test_mask_indexing(self):
dboe's avatar
dboe committed
92
93
        mask = np.array([True if i % 2 == 0 else False for i in range(len(self._inst))])
        self.demand_index_equal(mask, "type")
dboe's avatar
dboe committed
94
95
96
97
98
99
100
101

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

    def demand_index_equal(self, index, check_type):
dboe's avatar
dboe committed
102
        if check_type == "type":
dboe's avatar
dboe committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
            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
118
    def test_self_equality(self):
119
        # Test equality
dboe's avatar
dboe committed
120
121
122
123
        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
124
        # self.assertIs(self._inst, np.asarray(self._inst))  # TODO investigate
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
125
126

    def test_cylinderTrafo(self):
127
        # Test coordinate transformations in circle
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
128
129
130
131
132
        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
133
        self.demand_equal(transformer, atol=True, transformed=True)
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
134
135

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

    def test_basic_merge(self):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
143
        # create 3 copies with different coord_sys
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
144
145
146
147
        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)
148

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

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

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

171

dboe's avatar
dboe committed
172
# pylint:disable=no-member
dboe's avatar
dboe committed
173
class TensorFields_Check(Tensors_Check):
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
174
    def test_fields(self):
dboe's avatar
dboe committed
175
        self.assertIsNotNone(self._inst.fields)
dboe's avatar
dboe committed
176
177
178
179
180
        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))

dboe's avatar
dboe committed
181
182
183
184
185
186
187
            self.check_fields_equal(self._inst.fields, self._fields)

    def check_fields_equal(self, fields_a, fields_b):
        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
188

dboe's avatar
dboe committed
189
190
191
192
193
194
    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):
dboe's avatar
dboe committed
195
                if check_type == "type":
dboe's avatar
dboe committed
196
                    check_type = type(self._inst.fields[i])
dboe's avatar
dboe committed
197
198
199
200
201
                self.assertTrue(
                    np.array_equal(
                        item.fields[i], np.array(self._inst.fields[i])[index]
                    )
                )
dboe's avatar
dboe committed
202
203
                self.assertIsInstance(item.fields[i], check_type)

dboe's avatar
dboe committed
204
205
206
207
208
209
    def demand_deep_copy(self, other):
        super().demand_deep_copy(other)
        self.assertIsNot(self._inst.fields, other.fields)
        for i in range(len(self._inst.fields)):
            self.assertIsNot(self._inst.fields[i], other.fields[i])

dboe's avatar
dboe committed
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
    def test_list_like_field(self):
        if self._inst.fields:
            fields = self._inst.fields
            self._inst.fields = []
            for i, field in enumerate(fields):
                self._inst.fields.append(field)

                # indexing
                self.assertTrue(self._inst.fields[i].equal(field))

            self.check_fields_equal(fields, self._inst.fields)

    def test_field_name_getitem(self):
        if self._inst.fields:
            for i, field in enumerate(self._inst.fields):
                if field.name is not None:
                    self.assertTrue(self._inst.fields[field.name].equal(field))

    def test_field_name_setitem(self):
        if self._inst.fields:
            fields = self._inst.fields
            self._inst.fields = []
            for i, field in enumerate(fields):
                if field.name is not None:
                    name = field.name
                else:
                    name = str(uuid.uuid4())
                # setitem via fields
                self._inst.fields[name] = field

                field_item = self._inst.fields[name]
                self.assertTrue(field_item.equal(field))
                self.assertTrue(self._inst.fields[i].equal(field_item))
                self.assertEqual(field_item.name, name)

            self.check_fields_equal(fields, self._inst.fields)

247

dboe's avatar
dboe committed
248
249
250
251
class TensorMaps_Check(TensorFields_Check):
    def test_maps(self):
        self.assertIsNotNone(self._inst.maps)

dboe's avatar
dboe committed
252
253
254
255
    def test_cleaned(self):
        clean = self._inst.cleaned()
        # no faces are removed
        for map_dim in self._inst.maps:
dboe's avatar
dboe committed
256
            self.assertEqual(len(self._inst.maps[map_dim]), len(clean.maps[map_dim]))
dboe's avatar
dboe committed
257

dboe's avatar
dboe committed
258
259
260
261
    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
262
263
264
265
266
267
    def demand_deep_copy(self, other):
        super().demand_deep_copy(other)
        self.assertIsNot(self._inst.maps, other.maps)
        for i in self._inst.maps:
            self.assertIsNot(self._inst.maps[i], other.maps[i])

dboe's avatar
dboe committed
268

Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
269
270
271
272
273
"""
EMPTY TESTS
"""


dboe's avatar
dboe committed
274
class Tensors_Empty_Test(Tensors_Check, unittest.TestCase):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
275
276
277
278
    def setUp(self):
        self._inst = tfields.Tensors([], dim=3)


dboe's avatar
dboe committed
279
class TensorFields_Empty_Test(TensorFields_Check, unittest.TestCase):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
280
281
282
    def setUp(self):
        self._fields = []
        self._inst = tfields.TensorFields([], dim=3)
283
284


dboe's avatar
dboe committed
285
class TensorMaps_Empty_Test(TensorMaps_Check, unittest.TestCase):
286
287
288
289
290
    def setUp(self):
        self._fields = []
        self._inst = tfields.TensorMaps([], dim=3)
        self._maps = []
        self._maps_fields = []
291

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

dboe's avatar
dboe committed
293
class TensorFields_Test(TensorFields_Check, unittest.TestCase):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
294
295
    def setUp(self):
        base = [(-5, 5, 11)] * 3
dboe's avatar
dboe committed
296
297
298
299
        self._fields = [
            tfields.Tensors.grid(*base, coord_sys="cylinder"),
            tfields.Tensors(range(11 ** 3)),
        ]
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
300
301
302
        tensors = tfields.Tensors.grid(*base)
        self._inst = tfields.TensorFields(tensors, *self._fields)

dboe's avatar
dboe committed
303
304
        self.assertTrue(self._fields[0].coord_sys, "cylinder")
        self.assertTrue(self._fields[1].coord_sys, "cartesian")
Daniel Boeckenhoff's avatar
Daniel Boeckenhoff committed
305

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

dboe's avatar
dboe committed
307
class TensorMaps_Test(TensorFields_Check, unittest.TestCase):
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
308
309
310
    def setUp(self):
        base = [(-1, 1, 3)] * 3
        tensors = tfields.Tensors.grid(*base)
dboe's avatar
dboe committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        self._fields = [
            tfields.Tensors.grid(*base, coord_sys="cylinder"),
            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.0, 21.0, 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)
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
326

dboe's avatar
dboe committed
327
328
    def test_legacy(self):
        this_dir = pathlib.Path(__file__).parent
dboe's avatar
dboe committed
329
330
331
332
        legacy_file = (
            this_dir
            / "resources/TensorMaps_0.2.1_ce3ea1fb69058dc39815be65f485abebb487a6bd.npz"
        )  # NOQA
dboe's avatar
dboe committed
333
334
335
        tm = tfields.TensorMaps.load(legacy_file)
        self.assertTrue(self._inst.equal(tm))

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

337
338
339
class TensorMaps_Indexing_Test(unittest.TestCase):
    def setUp(self):
        tensors = np.arange(10).reshape((-1, 1))
dboe's avatar
dboe committed
340
341
342
343
344
345
        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)
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365

    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):
dboe's avatar
dboe committed
366
367
368
        mask = self._inst[
            np.array([False, True, True, True, True, True, True, False, False, False])
        ]
369
370
371
372
373
374
        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
375
class TensorMaps_NoFields_Test(Tensors_Check, unittest.TestCase):
dboe's avatar
dboe committed
376
377
378
    def setUp(self):
        self._inst = tfields.TensorMaps(
            [[1, 2, 3], [3, 3, 3], [0, 0, 0], [5, 6, 7]],
dboe's avatar
dboe committed
379
            maps=[[[0, 1, 2], [1, 2, 3]], [[1]], [[0, 1, 2, 3]]],
dboe's avatar
dboe committed
380
381
382
        )


dboe's avatar
dboe committed
383
384
class Maps_Test(Base_Check, unittest.TestCase):
    def demand_equal(self, other):
dboe's avatar
dboe committed
385
        super().demand_equal(other)
dboe's avatar
dboe committed
386
387
388
        self._inst.equal(other)

    def setUp(self):
dboe's avatar
dboe committed
389
        self._inst = tfields.Maps(
dboe's avatar
dboe committed
390
391
            [[[0, 0, 0], [1, 2, 3], [1, 5, 9]], [[0, 4], [1, 3]], [[42]]]
        )
dboe's avatar
dboe committed
392
393


394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
class Maps_Init_Test(Maps_Test):
    def setUp(self):
        self._inst = tfields.Maps({3: [[0, 1, 2]], 0: [[]]})


class Maps_Rigid_Test(Maps_Test):
    def setUp(self):
        rig = tfields.Maps({0: [[1, 2, 42]], 3: [1]})
        self.assertIsInstance(rig[0], tfields.TensorFields)
        self.assertIsInstance(rig[3], tfields.TensorFields)
        self.assertEqual(tfields.dim(rig[0]), 3)
        self.assertEqual(tfields.dim(rig[3]), 1)
        self.assertEqual(tfields.rank(rig[0]), 1)
        self.assertEqual(tfields.rank(rig[3]), 0)
        self._inst = rig


dboe's avatar
dboe committed
411
412
class Container_Check(AbstractNdarray_Check):
    def demand_equal(self, other):
dboe's avatar
dboe committed
413
        super().demand_equal(other)
dboe's avatar
dboe committed
414
415
416
417
418
419
420
421
422
423
424
        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
425
426
427
428
429
430
431
432
433
434
435
436
437

    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),
dboe's avatar
dboe committed
438
439
            coord_sys="spherical",
        )
dboe's avatar
dboe committed
440
        sphere2 = sphere.copy() * 3
dboe's avatar
dboe committed
441
        self._inst = tfields.Container([sphere, sphere2], labels=["test"])
dboe's avatar
dboe committed
442
443


dboe's avatar
dboe committed
444
if __name__ == "__main__":
Daniel Böckenhoff (Laptop)'s avatar
Daniel Böckenhoff (Laptop) committed
445
    unittest.main()