test_numpy_array.py revision 12037:d28054ac6ec9
112855Sgabeblack@google.comimport pytest
212855Sgabeblack@google.com
312855Sgabeblack@google.compytestmark = pytest.requires_numpy
412855Sgabeblack@google.com
512855Sgabeblack@google.comwith pytest.suppress(ImportError):
612855Sgabeblack@google.com    import numpy as np
712855Sgabeblack@google.com
812855Sgabeblack@google.com
912855Sgabeblack@google.com@pytest.fixture(scope='function')
1012855Sgabeblack@google.comdef arr():
1112855Sgabeblack@google.com    return np.array([[1, 2, 3], [4, 5, 6]], '=u2')
1212855Sgabeblack@google.com
1312855Sgabeblack@google.com
1412855Sgabeblack@google.comdef test_array_attributes():
1512855Sgabeblack@google.com    from pybind11_tests.array import (
1612855Sgabeblack@google.com        ndim, shape, strides, writeable, size, itemsize, nbytes, owndata
1712855Sgabeblack@google.com    )
1812855Sgabeblack@google.com
1912855Sgabeblack@google.com    a = np.array(0, 'f8')
2012855Sgabeblack@google.com    assert ndim(a) == 0
2112855Sgabeblack@google.com    assert all(shape(a) == [])
2212855Sgabeblack@google.com    assert all(strides(a) == [])
2312855Sgabeblack@google.com    with pytest.raises(IndexError) as excinfo:
2412855Sgabeblack@google.com        shape(a, 0)
2512855Sgabeblack@google.com    assert str(excinfo.value) == 'invalid axis: 0 (ndim = 0)'
2612855Sgabeblack@google.com    with pytest.raises(IndexError) as excinfo:
2712855Sgabeblack@google.com        strides(a, 0)
2812855Sgabeblack@google.com    assert str(excinfo.value) == 'invalid axis: 0 (ndim = 0)'
2912855Sgabeblack@google.com    assert writeable(a)
3012855Sgabeblack@google.com    assert size(a) == 1
3112855Sgabeblack@google.com    assert itemsize(a) == 8
3212855Sgabeblack@google.com    assert nbytes(a) == 8
3312855Sgabeblack@google.com    assert owndata(a)
3412855Sgabeblack@google.com
3512855Sgabeblack@google.com    a = np.array([[1, 2, 3], [4, 5, 6]], 'u2').view()
3612855Sgabeblack@google.com    a.flags.writeable = False
3712855Sgabeblack@google.com    assert ndim(a) == 2
3812855Sgabeblack@google.com    assert all(shape(a) == [2, 3])
3912855Sgabeblack@google.com    assert shape(a, 0) == 2
4012855Sgabeblack@google.com    assert shape(a, 1) == 3
4112855Sgabeblack@google.com    assert all(strides(a) == [6, 2])
4212855Sgabeblack@google.com    assert strides(a, 0) == 6
4312855Sgabeblack@google.com    assert strides(a, 1) == 2
4412855Sgabeblack@google.com    with pytest.raises(IndexError) as excinfo:
4512855Sgabeblack@google.com        shape(a, 2)
4612855Sgabeblack@google.com    assert str(excinfo.value) == 'invalid axis: 2 (ndim = 2)'
4712855Sgabeblack@google.com    with pytest.raises(IndexError) as excinfo:
4812855Sgabeblack@google.com        strides(a, 2)
4912855Sgabeblack@google.com    assert str(excinfo.value) == 'invalid axis: 2 (ndim = 2)'
5012855Sgabeblack@google.com    assert not writeable(a)
5112855Sgabeblack@google.com    assert size(a) == 6
5212855Sgabeblack@google.com    assert itemsize(a) == 2
53    assert nbytes(a) == 12
54    assert not owndata(a)
55
56
57@pytest.mark.parametrize('args, ret', [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)])
58def test_index_offset(arr, args, ret):
59    from pybind11_tests.array import index_at, index_at_t, offset_at, offset_at_t
60    assert index_at(arr, *args) == ret
61    assert index_at_t(arr, *args) == ret
62    assert offset_at(arr, *args) == ret * arr.dtype.itemsize
63    assert offset_at_t(arr, *args) == ret * arr.dtype.itemsize
64
65
66def test_dim_check_fail(arr):
67    from pybind11_tests.array import (index_at, index_at_t, offset_at, offset_at_t, data, data_t,
68                                      mutate_data, mutate_data_t)
69    for func in (index_at, index_at_t, offset_at, offset_at_t, data, data_t,
70                 mutate_data, mutate_data_t):
71        with pytest.raises(IndexError) as excinfo:
72            func(arr, 1, 2, 3)
73        assert str(excinfo.value) == 'too many indices for an array: 3 (ndim = 2)'
74
75
76@pytest.mark.parametrize('args, ret',
77                         [([], [1, 2, 3, 4, 5, 6]),
78                          ([1], [4, 5, 6]),
79                          ([0, 1], [2, 3, 4, 5, 6]),
80                          ([1, 2], [6])])
81def test_data(arr, args, ret):
82    from pybind11_tests.array import data, data_t
83    from sys import byteorder
84    assert all(data_t(arr, *args) == ret)
85    assert all(data(arr, *args)[(0 if byteorder == 'little' else 1)::2] == ret)
86    assert all(data(arr, *args)[(1 if byteorder == 'little' else 0)::2] == 0)
87
88
89def test_mutate_readonly(arr):
90    from pybind11_tests.array import mutate_data, mutate_data_t, mutate_at_t
91    arr.flags.writeable = False
92    for func, args in (mutate_data, ()), (mutate_data_t, ()), (mutate_at_t, (0, 0)):
93        with pytest.raises(ValueError) as excinfo:
94            func(arr, *args)
95        assert str(excinfo.value) == 'array is not writeable'
96
97
98@pytest.mark.parametrize('dim', [0, 1, 3])
99def test_at_fail(arr, dim):
100    from pybind11_tests.array import at_t, mutate_at_t
101    for func in at_t, mutate_at_t:
102        with pytest.raises(IndexError) as excinfo:
103            func(arr, *([0] * dim))
104        assert str(excinfo.value) == 'index dimension mismatch: {} (ndim = 2)'.format(dim)
105
106
107def test_at(arr):
108    from pybind11_tests.array import at_t, mutate_at_t
109
110    assert at_t(arr, 0, 2) == 3
111    assert at_t(arr, 1, 0) == 4
112
113    assert all(mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6])
114    assert all(mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6])
115
116
117def test_mutate_data(arr):
118    from pybind11_tests.array import mutate_data, mutate_data_t
119
120    assert all(mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12])
121    assert all(mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24])
122    assert all(mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48])
123    assert all(mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96])
124    assert all(mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192])
125
126    assert all(mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193])
127    assert all(mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194])
128    assert all(mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195])
129    assert all(mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196])
130    assert all(mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197])
131
132
133def test_bounds_check(arr):
134    from pybind11_tests.array import (index_at, index_at_t, data, data_t,
135                                      mutate_data, mutate_data_t, at_t, mutate_at_t)
136    funcs = (index_at, index_at_t, data, data_t,
137             mutate_data, mutate_data_t, at_t, mutate_at_t)
138    for func in funcs:
139        with pytest.raises(IndexError) as excinfo:
140            func(arr, 2, 0)
141        assert str(excinfo.value) == 'index 2 is out of bounds for axis 0 with size 2'
142        with pytest.raises(IndexError) as excinfo:
143            func(arr, 0, 4)
144        assert str(excinfo.value) == 'index 4 is out of bounds for axis 1 with size 3'
145
146
147def test_make_c_f_array():
148    from pybind11_tests.array import (
149        make_c_array, make_f_array
150    )
151    assert make_c_array().flags.c_contiguous
152    assert not make_c_array().flags.f_contiguous
153    assert make_f_array().flags.f_contiguous
154    assert not make_f_array().flags.c_contiguous
155
156
157def test_wrap():
158    from pybind11_tests.array import wrap
159
160    def assert_references(a, b, base=None):
161        if base is None:
162            base = a
163        assert a is not b
164        assert a.__array_interface__['data'][0] == b.__array_interface__['data'][0]
165        assert a.shape == b.shape
166        assert a.strides == b.strides
167        assert a.flags.c_contiguous == b.flags.c_contiguous
168        assert a.flags.f_contiguous == b.flags.f_contiguous
169        assert a.flags.writeable == b.flags.writeable
170        assert a.flags.aligned == b.flags.aligned
171        assert a.flags.updateifcopy == b.flags.updateifcopy
172        assert np.all(a == b)
173        assert not b.flags.owndata
174        assert b.base is base
175        if a.flags.writeable and a.ndim == 2:
176            a[0, 0] = 1234
177            assert b[0, 0] == 1234
178
179    a1 = np.array([1, 2], dtype=np.int16)
180    assert a1.flags.owndata and a1.base is None
181    a2 = wrap(a1)
182    assert_references(a1, a2)
183
184    a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order='F')
185    assert a1.flags.owndata and a1.base is None
186    a2 = wrap(a1)
187    assert_references(a1, a2)
188
189    a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order='C')
190    a1.flags.writeable = False
191    a2 = wrap(a1)
192    assert_references(a1, a2)
193
194    a1 = np.random.random((4, 4, 4))
195    a2 = wrap(a1)
196    assert_references(a1, a2)
197
198    a1t = a1.transpose()
199    a2 = wrap(a1t)
200    assert_references(a1t, a2, a1)
201
202    a1d = a1.diagonal()
203    a2 = wrap(a1d)
204    assert_references(a1d, a2, a1)
205
206
207def test_numpy_view(capture):
208    from pybind11_tests.array import ArrayClass
209    with capture:
210        ac = ArrayClass()
211        ac_view_1 = ac.numpy_view()
212        ac_view_2 = ac.numpy_view()
213        assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))
214        del ac
215        pytest.gc_collect()
216    assert capture == """
217        ArrayClass()
218        ArrayClass::numpy_view()
219        ArrayClass::numpy_view()
220    """
221    ac_view_1[0] = 4
222    ac_view_1[1] = 3
223    assert ac_view_2[0] == 4
224    assert ac_view_2[1] == 3
225    with capture:
226        del ac_view_1
227        del ac_view_2
228        pytest.gc_collect()
229        pytest.gc_collect()
230    assert capture == """
231        ~ArrayClass()
232    """
233
234
235@pytest.unsupported_on_pypy
236def test_cast_numpy_int64_to_uint64():
237    from pybind11_tests.array import function_taking_uint64
238    function_taking_uint64(123)
239    function_taking_uint64(np.uint64(123))
240
241
242def test_isinstance():
243    from pybind11_tests.array import isinstance_untyped, isinstance_typed
244
245    assert isinstance_untyped(np.array([1, 2, 3]), "not an array")
246    assert isinstance_typed(np.array([1.0, 2.0, 3.0]))
247
248
249def test_constructors():
250    from pybind11_tests.array import default_constructors, converting_constructors
251
252    defaults = default_constructors()
253    for a in defaults.values():
254        assert a.size == 0
255    assert defaults["array"].dtype == np.array([]).dtype
256    assert defaults["array_t<int32>"].dtype == np.int32
257    assert defaults["array_t<double>"].dtype == np.float64
258
259    results = converting_constructors([1, 2, 3])
260    for a in results.values():
261        np.testing.assert_array_equal(a, [1, 2, 3])
262    assert results["array"].dtype == np.int_
263    assert results["array_t<int32>"].dtype == np.int32
264    assert results["array_t<double>"].dtype == np.float64
265
266
267def test_overload_resolution(msg):
268    from pybind11_tests.array import overloaded, overloaded2, overloaded3, overloaded4, overloaded5
269
270    # Exact overload matches:
271    assert overloaded(np.array([1], dtype='float64')) == 'double'
272    assert overloaded(np.array([1], dtype='float32')) == 'float'
273    assert overloaded(np.array([1], dtype='ushort')) == 'unsigned short'
274    assert overloaded(np.array([1], dtype='intc')) == 'int'
275    assert overloaded(np.array([1], dtype='longlong')) == 'long long'
276    assert overloaded(np.array([1], dtype='complex')) == 'double complex'
277    assert overloaded(np.array([1], dtype='csingle')) == 'float complex'
278
279    # No exact match, should call first convertible version:
280    assert overloaded(np.array([1], dtype='uint8')) == 'double'
281
282    with pytest.raises(TypeError) as excinfo:
283        overloaded("not an array")
284    assert msg(excinfo.value) == """
285        overloaded(): incompatible function arguments. The following argument types are supported:
286            1. (arg0: numpy.ndarray[float64]) -> str
287            2. (arg0: numpy.ndarray[float32]) -> str
288            3. (arg0: numpy.ndarray[int32]) -> str
289            4. (arg0: numpy.ndarray[uint16]) -> str
290            5. (arg0: numpy.ndarray[int64]) -> str
291            6. (arg0: numpy.ndarray[complex128]) -> str
292            7. (arg0: numpy.ndarray[complex64]) -> str
293
294        Invoked with: 'not an array'
295    """
296
297    assert overloaded2(np.array([1], dtype='float64')) == 'double'
298    assert overloaded2(np.array([1], dtype='float32')) == 'float'
299    assert overloaded2(np.array([1], dtype='complex64')) == 'float complex'
300    assert overloaded2(np.array([1], dtype='complex128')) == 'double complex'
301    assert overloaded2(np.array([1], dtype='float32')) == 'float'
302
303    assert overloaded3(np.array([1], dtype='float64')) == 'double'
304    assert overloaded3(np.array([1], dtype='intc')) == 'int'
305    expected_exc = """
306        overloaded3(): incompatible function arguments. The following argument types are supported:
307            1. (arg0: numpy.ndarray[int32]) -> str
308            2. (arg0: numpy.ndarray[float64]) -> str
309
310        Invoked with:"""
311
312    with pytest.raises(TypeError) as excinfo:
313        overloaded3(np.array([1], dtype='uintc'))
314    assert msg(excinfo.value) == expected_exc + " array([1], dtype=uint32)"
315    with pytest.raises(TypeError) as excinfo:
316        overloaded3(np.array([1], dtype='float32'))
317    assert msg(excinfo.value) == expected_exc + " array([ 1.], dtype=float32)"
318    with pytest.raises(TypeError) as excinfo:
319        overloaded3(np.array([1], dtype='complex'))
320    assert msg(excinfo.value) == expected_exc + " array([ 1.+0.j])"
321
322    # Exact matches:
323    assert overloaded4(np.array([1], dtype='double')) == 'double'
324    assert overloaded4(np.array([1], dtype='longlong')) == 'long long'
325    # Non-exact matches requiring conversion.  Since float to integer isn't a
326    # save conversion, it should go to the double overload, but short can go to
327    # either (and so should end up on the first-registered, the long long).
328    assert overloaded4(np.array([1], dtype='float32')) == 'double'
329    assert overloaded4(np.array([1], dtype='short')) == 'long long'
330
331    assert overloaded5(np.array([1], dtype='double')) == 'double'
332    assert overloaded5(np.array([1], dtype='uintc')) == 'unsigned int'
333    assert overloaded5(np.array([1], dtype='float32')) == 'unsigned int'
334
335
336def test_greedy_string_overload():  # issue 685
337    from pybind11_tests.array import issue685
338
339    assert issue685("abc") == "string"
340    assert issue685(np.array([97, 98, 99], dtype='b')) == "array"
341    assert issue685(123) == "other"
342
343
344def test_array_unchecked_fixed_dims(msg):
345    from pybind11_tests.array import (proxy_add2, proxy_init3F, proxy_init3, proxy_squared_L2_norm,
346                                      proxy_auxiliaries2, array_auxiliaries2)
347
348    z1 = np.array([[1, 2], [3, 4]], dtype='float64')
349    proxy_add2(z1, 10)
350    assert np.all(z1 == [[11, 12], [13, 14]])
351
352    with pytest.raises(ValueError) as excinfo:
353        proxy_add2(np.array([1., 2, 3]), 5.0)
354    assert msg(excinfo.value) == "array has incorrect number of dimensions: 1; expected 2"
355
356    expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype='int')
357    assert np.all(proxy_init3(3.0) == expect_c)
358    expect_f = np.transpose(expect_c)
359    assert np.all(proxy_init3F(3.0) == expect_f)
360
361    assert proxy_squared_L2_norm(np.array(range(6))) == 55
362    assert proxy_squared_L2_norm(np.array(range(6), dtype="float64")) == 55
363
364    assert proxy_auxiliaries2(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
365    assert proxy_auxiliaries2(z1) == array_auxiliaries2(z1)
366
367
368def test_array_unchecked_dyn_dims(msg):
369    from pybind11_tests.array import (proxy_add2_dyn, proxy_init3_dyn, proxy_auxiliaries2_dyn,
370                                      array_auxiliaries2)
371    z1 = np.array([[1, 2], [3, 4]], dtype='float64')
372    proxy_add2_dyn(z1, 10)
373    assert np.all(z1 == [[11, 12], [13, 14]])
374
375    expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype='int')
376    assert np.all(proxy_init3_dyn(3.0) == expect_c)
377
378    assert proxy_auxiliaries2_dyn(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
379    assert proxy_auxiliaries2_dyn(z1) == array_auxiliaries2(z1)
380