example20.py 1.58 KB
Newer Older
1
2
3
4
#!/usr/bin/env python
from __future__ import print_function

import numpy as np
5
from example import (
6
7
    create_rec_simple, create_rec_packed, create_rec_nested, print_format_descriptors,
    print_rec_simple, print_rec_packed, print_rec_nested
8
)
9
10
11
12
13


def check_eq(arr, data, dtype):
    np.testing.assert_equal(arr, np.array(data, dtype=dtype))

14
15
print_format_descriptors()

Ivan Smirnov's avatar
Ivan Smirnov committed
16
17
18
19
simple_dtype = np.dtype({'names': ['x', 'y', 'z'],
                         'formats': ['?', 'u4', 'f4'],
                         'offsets': [0, 4, 8]})
packed_dtype = np.dtype([('x', '?'), ('y', 'u4'), ('z', 'f4')])
20

Ivan Smirnov's avatar
Ivan Smirnov committed
21
for func, dtype in [(create_rec_simple, simple_dtype), (create_rec_packed, packed_dtype)]:
Ivan Smirnov's avatar
Ivan Smirnov committed
22
23
24
25
26
    arr = func(0)
    assert arr.dtype == dtype
    check_eq(arr, [], simple_dtype)
    check_eq(arr, [], packed_dtype)

Ivan Smirnov's avatar
Ivan Smirnov committed
27
28
29
30
    arr = func(3)
    assert arr.dtype == dtype
    check_eq(arr, [(False, 0, 0.0), (True, 1, 1.5), (False, 2, 3.0)], simple_dtype)
    check_eq(arr, [(False, 0, 0.0), (True, 1, 1.5), (False, 2, 3.0)], packed_dtype)
31

32
33
34
35
36
37
    # uncomment lines below to cause a segfault upon exit in Py_Finalize :(

    # if dtype == simple_dtype:
    #     print_rec_simple(arr)
    # else:
    #     print_rec_packed(arr)
Ivan Smirnov's avatar
Ivan Smirnov committed
38
39
40
41
42
43
44
45
46
47
48
49

nested_dtype = np.dtype([('a', simple_dtype), ('b', packed_dtype)])

arr = create_rec_nested(0)
assert arr.dtype == nested_dtype
check_eq(arr, [], nested_dtype)

arr = create_rec_nested(3)
assert arr.dtype == nested_dtype
check_eq(arr, [((False, 0, 0.0), (True, 1, 1.5)),
               ((True, 1, 1.5), (False, 2, 3.0)),
               ((False, 2, 3.0), (True, 3, 4.5))], nested_dtype)
50
# print_rec_nested(arr)