μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
test_numpy_array.py
Go to the documentation of this file.
1import pytest
2
3import env # noqa: F401
4from pybind11_tests import numpy_array as m
5
6np = pytest.importorskip("numpy")
7
8
9def test_dtypes():
10 # See issue #1328.
11 # - Platform-dependent sizes.
12 for size_check in m.get_platform_dtype_size_checks():
13 print(size_check)
14 assert size_check.size_cpp == size_check.size_numpy, size_check
15 # - Concrete sizes.
16 for check in m.get_concrete_dtype_checks():
17 print(check)
18 assert check.numpy == check.pybind11, check
19 if check.numpy.num != check.pybind11.num:
20 print(
21 f"NOTE: typenum mismatch for {check}: {check.numpy.num} != {check.pybind11.num}"
22 )
23
24
25@pytest.fixture(scope="function")
26def arr():
27 return np.array([[1, 2, 3], [4, 5, 6]], "=u2")
28
29
30def test_array_attributes():
31 a = np.array(0, "f8")
32 assert m.ndim(a) == 0
33 assert all(m.shape(a) == [])
34 assert all(m.strides(a) == [])
35 with pytest.raises(IndexError) as excinfo:
36 m.shape(a, 0)
37 assert str(excinfo.value) == "invalid axis: 0 (ndim = 0)"
38 with pytest.raises(IndexError) as excinfo:
39 m.strides(a, 0)
40 assert str(excinfo.value) == "invalid axis: 0 (ndim = 0)"
41 assert m.writeable(a)
42 assert m.size(a) == 1
43 assert m.itemsize(a) == 8
44 assert m.nbytes(a) == 8
45 assert m.owndata(a)
46
47 a = np.array([[1, 2, 3], [4, 5, 6]], "u2").view()
48 a.flags.writeable = False
49 assert m.ndim(a) == 2
50 assert all(m.shape(a) == [2, 3])
51 assert m.shape(a, 0) == 2
52 assert m.shape(a, 1) == 3
53 assert all(m.strides(a) == [6, 2])
54 assert m.strides(a, 0) == 6
55 assert m.strides(a, 1) == 2
56 with pytest.raises(IndexError) as excinfo:
57 m.shape(a, 2)
58 assert str(excinfo.value) == "invalid axis: 2 (ndim = 2)"
59 with pytest.raises(IndexError) as excinfo:
60 m.strides(a, 2)
61 assert str(excinfo.value) == "invalid axis: 2 (ndim = 2)"
62 assert not m.writeable(a)
63 assert m.size(a) == 6
64 assert m.itemsize(a) == 2
65 assert m.nbytes(a) == 12
66 assert not m.owndata(a)
67
68
69@pytest.mark.parametrize(
70 "args, ret", [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)]
71)
72def test_index_offset(arr, args, ret):
73 assert m.index_at(arr, *args) == ret
74 assert m.index_at_t(arr, *args) == ret
75 assert m.offset_at(arr, *args) == ret * arr.dtype.itemsize
76 assert m.offset_at_t(arr, *args) == ret * arr.dtype.itemsize
77
78
79def test_dim_check_fail(arr):
80 for func in (
81 m.index_at,
82 m.index_at_t,
83 m.offset_at,
84 m.offset_at_t,
85 m.data,
86 m.data_t,
87 m.mutate_data,
88 m.mutate_data_t,
89 ):
90 with pytest.raises(IndexError) as excinfo:
91 func(arr, 1, 2, 3)
92 assert str(excinfo.value) == "too many indices for an array: 3 (ndim = 2)"
93
94
95@pytest.mark.parametrize(
96 "args, ret",
97 [
98 ([], [1, 2, 3, 4, 5, 6]),
99 ([1], [4, 5, 6]),
100 ([0, 1], [2, 3, 4, 5, 6]),
101 ([1, 2], [6]),
102 ],
103)
104def test_data(arr, args, ret):
105 from sys import byteorder
106
107 assert all(m.data_t(arr, *args) == ret)
108 assert all(m.data(arr, *args)[(0 if byteorder == "little" else 1) :: 2] == ret)
109 assert all(m.data(arr, *args)[(1 if byteorder == "little" else 0) :: 2] == 0)
110
111
112@pytest.mark.parametrize("dim", [0, 1, 3])
113def test_at_fail(arr, dim):
114 for func in m.at_t, m.mutate_at_t:
115 with pytest.raises(IndexError) as excinfo:
116 func(arr, *([0] * dim))
117 assert str(excinfo.value) == f"index dimension mismatch: {dim} (ndim = 2)"
118
119
120def test_at(arr):
121 assert m.at_t(arr, 0, 2) == 3
122 assert m.at_t(arr, 1, 0) == 4
123
124 assert all(m.mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6])
125 assert all(m.mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6])
126
127
128def test_mutate_readonly(arr):
129 arr.flags.writeable = False
130 for func, args in (
131 (m.mutate_data, ()),
132 (m.mutate_data_t, ()),
133 (m.mutate_at_t, (0, 0)),
134 ):
135 with pytest.raises(ValueError) as excinfo:
136 func(arr, *args)
137 assert str(excinfo.value) == "array is not writeable"
138
139
140def test_mutate_data(arr):
141 assert all(m.mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12])
142 assert all(m.mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24])
143 assert all(m.mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48])
144 assert all(m.mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96])
145 assert all(m.mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192])
146
147 assert all(m.mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193])
148 assert all(m.mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194])
149 assert all(m.mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195])
150 assert all(m.mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196])
151 assert all(m.mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197])
152
153
154def test_bounds_check(arr):
155 for func in (
156 m.index_at,
157 m.index_at_t,
158 m.data,
159 m.data_t,
160 m.mutate_data,
161 m.mutate_data_t,
162 m.at_t,
163 m.mutate_at_t,
164 ):
165 with pytest.raises(IndexError) as excinfo:
166 func(arr, 2, 0)
167 assert str(excinfo.value) == "index 2 is out of bounds for axis 0 with size 2"
168 with pytest.raises(IndexError) as excinfo:
169 func(arr, 0, 4)
170 assert str(excinfo.value) == "index 4 is out of bounds for axis 1 with size 3"
171
172
173def test_make_c_f_array():
174 assert m.make_c_array().flags.c_contiguous
175 assert not m.make_c_array().flags.f_contiguous
176 assert m.make_f_array().flags.f_contiguous
177 assert not m.make_f_array().flags.c_contiguous
178
179
180def test_make_empty_shaped_array():
181 m.make_empty_shaped_array()
182
183 # empty shape means numpy scalar, PEP 3118
184 assert m.scalar_int().ndim == 0
185 assert m.scalar_int().shape == ()
186 assert m.scalar_int() == 42
187
188
189def test_wrap():
190 def assert_references(a, b, base=None):
191 if base is None:
192 base = a
193 assert a is not b
194 assert a.__array_interface__["data"][0] == b.__array_interface__["data"][0]
195 assert a.shape == b.shape
196 assert a.strides == b.strides
197 assert a.flags.c_contiguous == b.flags.c_contiguous
198 assert a.flags.f_contiguous == b.flags.f_contiguous
199 assert a.flags.writeable == b.flags.writeable
200 assert a.flags.aligned == b.flags.aligned
201 # 1.13 supported Python 3.6
202 if tuple(int(x) for x in np.__version__.split(".")[:2]) >= (1, 14):
203 assert a.flags.writebackifcopy == b.flags.writebackifcopy
204 else:
205 assert a.flags.updateifcopy == b.flags.updateifcopy
206 assert np.all(a == b)
207 assert not b.flags.owndata
208 assert b.base is base
209 if a.flags.writeable and a.ndim == 2:
210 a[0, 0] = 1234
211 assert b[0, 0] == 1234
212
213 a1 = np.array([1, 2], dtype=np.int16)
214 assert a1.flags.owndata and a1.base is None
215 a2 = m.wrap(a1)
216 assert_references(a1, a2)
217
218 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order="F")
219 assert a1.flags.owndata and a1.base is None
220 a2 = m.wrap(a1)
221 assert_references(a1, a2)
222
223 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order="C")
224 a1.flags.writeable = False
225 a2 = m.wrap(a1)
226 assert_references(a1, a2)
227
228 a1 = np.random.random((4, 4, 4))
229 a2 = m.wrap(a1)
230 assert_references(a1, a2)
231
232 a1t = a1.transpose()
233 a2 = m.wrap(a1t)
234 assert_references(a1t, a2, a1)
235
236 a1d = a1.diagonal()
237 a2 = m.wrap(a1d)
238 assert_references(a1d, a2, a1)
239
240 a1m = a1[::-1, ::-1, ::-1]
241 a2 = m.wrap(a1m)
242 assert_references(a1m, a2, a1)
243
244
245def test_numpy_view(capture):
246 with capture:
247 ac = m.ArrayClass()
248 ac_view_1 = ac.numpy_view()
249 ac_view_2 = ac.numpy_view()
250 assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))
251 del ac
252 pytest.gc_collect()
253 assert (
254 capture
255 == """
256 ArrayClass()
257 ArrayClass::numpy_view()
258 ArrayClass::numpy_view()
259 """
260 )
261 ac_view_1[0] = 4
262 ac_view_1[1] = 3
263 assert ac_view_2[0] == 4
264 assert ac_view_2[1] == 3
265 with capture:
266 del ac_view_1
267 del ac_view_2
268 pytest.gc_collect()
269 pytest.gc_collect()
270 assert (
271 capture
272 == """
273 ~ArrayClass()
274 """
275 )
276
277
278def test_cast_numpy_int64_to_uint64():
279 m.function_taking_uint64(123)
280 m.function_taking_uint64(np.uint64(123))
281
282
283def test_isinstance():
284 assert m.isinstance_untyped(np.array([1, 2, 3]), "not an array")
285 assert m.isinstance_typed(np.array([1.0, 2.0, 3.0]))
286
287
288def test_constructors():
289 defaults = m.default_constructors()
290 for a in defaults.values():
291 assert a.size == 0
292 assert defaults["array"].dtype == np.array([]).dtype
293 assert defaults["array_t<int32>"].dtype == np.int32
294 assert defaults["array_t<double>"].dtype == np.float64
295
296 results = m.converting_constructors([1, 2, 3])
297 for a in results.values():
298 np.testing.assert_array_equal(a, [1, 2, 3])
299 assert results["array"].dtype == np.int_
300 assert results["array_t<int32>"].dtype == np.int32
301 assert results["array_t<double>"].dtype == np.float64
302
303
304def test_overload_resolution(msg):
305 # Exact overload matches:
306 assert m.overloaded(np.array([1], dtype="float64")) == "double"
307 assert m.overloaded(np.array([1], dtype="float32")) == "float"
308 assert m.overloaded(np.array([1], dtype="ushort")) == "unsigned short"
309 assert m.overloaded(np.array([1], dtype="intc")) == "int"
310 assert m.overloaded(np.array([1], dtype="longlong")) == "long long"
311 assert m.overloaded(np.array([1], dtype="complex")) == "double complex"
312 assert m.overloaded(np.array([1], dtype="csingle")) == "float complex"
313
314 # No exact match, should call first convertible version:
315 assert m.overloaded(np.array([1], dtype="uint8")) == "double"
316
317 with pytest.raises(TypeError) as excinfo:
318 m.overloaded("not an array")
319 assert (
320 msg(excinfo.value)
321 == """
322 overloaded(): incompatible function arguments. The following argument types are supported:
323 1. (arg0: numpy.ndarray[numpy.float64]) -> str
324 2. (arg0: numpy.ndarray[numpy.float32]) -> str
325 3. (arg0: numpy.ndarray[numpy.int32]) -> str
326 4. (arg0: numpy.ndarray[numpy.uint16]) -> str
327 5. (arg0: numpy.ndarray[numpy.int64]) -> str
328 6. (arg0: numpy.ndarray[numpy.complex128]) -> str
329 7. (arg0: numpy.ndarray[numpy.complex64]) -> str
330
331 Invoked with: 'not an array'
332 """
333 )
334
335 assert m.overloaded2(np.array([1], dtype="float64")) == "double"
336 assert m.overloaded2(np.array([1], dtype="float32")) == "float"
337 assert m.overloaded2(np.array([1], dtype="complex64")) == "float complex"
338 assert m.overloaded2(np.array([1], dtype="complex128")) == "double complex"
339 assert m.overloaded2(np.array([1], dtype="float32")) == "float"
340
341 assert m.overloaded3(np.array([1], dtype="float64")) == "double"
342 assert m.overloaded3(np.array([1], dtype="intc")) == "int"
343 expected_exc = """
344 overloaded3(): incompatible function arguments. The following argument types are supported:
345 1. (arg0: numpy.ndarray[numpy.int32]) -> str
346 2. (arg0: numpy.ndarray[numpy.float64]) -> str
347
348 Invoked with: """
349
350 with pytest.raises(TypeError) as excinfo:
351 m.overloaded3(np.array([1], dtype="uintc"))
352 assert msg(excinfo.value) == expected_exc + repr(np.array([1], dtype="uint32"))
353 with pytest.raises(TypeError) as excinfo:
354 m.overloaded3(np.array([1], dtype="float32"))
355 assert msg(excinfo.value) == expected_exc + repr(np.array([1.0], dtype="float32"))
356 with pytest.raises(TypeError) as excinfo:
357 m.overloaded3(np.array([1], dtype="complex"))
358 assert msg(excinfo.value) == expected_exc + repr(np.array([1.0 + 0.0j]))
359
360 # Exact matches:
361 assert m.overloaded4(np.array([1], dtype="double")) == "double"
362 assert m.overloaded4(np.array([1], dtype="longlong")) == "long long"
363 # Non-exact matches requiring conversion. Since float to integer isn't a
364 # save conversion, it should go to the double overload, but short can go to
365 # either (and so should end up on the first-registered, the long long).
366 assert m.overloaded4(np.array([1], dtype="float32")) == "double"
367 assert m.overloaded4(np.array([1], dtype="short")) == "long long"
368
369 assert m.overloaded5(np.array([1], dtype="double")) == "double"
370 assert m.overloaded5(np.array([1], dtype="uintc")) == "unsigned int"
371 assert m.overloaded5(np.array([1], dtype="float32")) == "unsigned int"
372
373
374def test_greedy_string_overload():
375 """Tests fix for #685 - ndarray shouldn't go to std::string overload"""
376
377 assert m.issue685("abc") == "string"
378 assert m.issue685(np.array([97, 98, 99], dtype="b")) == "array"
379 assert m.issue685(123) == "other"
380
381
382def test_array_unchecked_fixed_dims(msg):
383 z1 = np.array([[1, 2], [3, 4]], dtype="float64")
384 m.proxy_add2(z1, 10)
385 assert np.all(z1 == [[11, 12], [13, 14]])
386
387 with pytest.raises(ValueError) as excinfo:
388 m.proxy_add2(np.array([1.0, 2, 3]), 5.0)
389 assert (
390 msg(excinfo.value) == "array has incorrect number of dimensions: 1; expected 2"
391 )
392
393 expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype="int")
394 assert np.all(m.proxy_init3(3.0) == expect_c)
395 expect_f = np.transpose(expect_c)
396 assert np.all(m.proxy_init3F(3.0) == expect_f)
397
398 assert m.proxy_squared_L2_norm(np.array(range(6))) == 55
399 assert m.proxy_squared_L2_norm(np.array(range(6), dtype="float64")) == 55
400
401 assert m.proxy_auxiliaries2(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
402 assert m.proxy_auxiliaries2(z1) == m.array_auxiliaries2(z1)
403
404 assert m.proxy_auxiliaries1_const_ref(z1[0, :])
405 assert m.proxy_auxiliaries2_const_ref(z1)
406
407
408def test_array_unchecked_dyn_dims():
409 z1 = np.array([[1, 2], [3, 4]], dtype="float64")
410 m.proxy_add2_dyn(z1, 10)
411 assert np.all(z1 == [[11, 12], [13, 14]])
412
413 expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype="int")
414 assert np.all(m.proxy_init3_dyn(3.0) == expect_c)
415
416 assert m.proxy_auxiliaries2_dyn(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
417 assert m.proxy_auxiliaries2_dyn(z1) == m.array_auxiliaries2(z1)
418
419
420def test_array_failure():
421 with pytest.raises(ValueError) as excinfo:
422 m.array_fail_test()
423 assert str(excinfo.value) == "cannot create a pybind11::array from a nullptr"
424
425 with pytest.raises(ValueError) as excinfo:
426 m.array_t_fail_test()
427 assert str(excinfo.value) == "cannot create a pybind11::array_t from a nullptr"
428
429 with pytest.raises(ValueError) as excinfo:
430 m.array_fail_test_negative_size()
431 assert str(excinfo.value) == "negative dimensions are not allowed"
432
433
434def test_initializer_list():
435 assert m.array_initializer_list1().shape == (1,)
436 assert m.array_initializer_list2().shape == (1, 2)
437 assert m.array_initializer_list3().shape == (1, 2, 3)
438 assert m.array_initializer_list4().shape == (1, 2, 3, 4)
439
440
441def test_array_resize():
442 a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype="float64")
443 m.array_reshape2(a)
444 assert a.size == 9
445 assert np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
446
447 # total size change should succced with refcheck off
448 m.array_resize3(a, 4, False)
449 assert a.size == 64
450 # ... and fail with refcheck on
451 try:
452 m.array_resize3(a, 3, True)
453 except ValueError as e:
454 assert str(e).startswith("cannot resize an array")
455 # transposed array doesn't own data
456 b = a.transpose()
457 try:
458 m.array_resize3(b, 3, False)
459 except ValueError as e:
460 assert str(e).startswith("cannot resize this array: it does not own its data")
461 # ... but reshape should be fine
462 m.array_reshape2(b)
463 assert b.shape == (8, 8)
464
465
466@pytest.mark.xfail("env.PYPY")
467def test_array_create_and_resize():
468 a = m.create_and_resize(2)
469 assert a.size == 4
470 assert np.all(a == 42.0)
471
472
473def test_array_view():
474 a = np.ones(100 * 4).astype("uint8")
475 a_float_view = m.array_view(a, "float32")
476 assert a_float_view.shape == (100 * 1,) # 1 / 4 bytes = 8 / 32
477
478 a_int16_view = m.array_view(a, "int16") # 1 / 2 bytes = 16 / 32
479 assert a_int16_view.shape == (100 * 2,)
480
481
482def test_array_view_invalid():
483 a = np.ones(100 * 4).astype("uint8")
484 with pytest.raises(TypeError):
485 m.array_view(a, "deadly_dtype")
486
487
488def test_reshape_initializer_list():
489 a = np.arange(2 * 7 * 3) + 1
490 x = m.reshape_initializer_list(a, 2, 7, 3)
491 assert x.shape == (2, 7, 3)
492 assert list(x[1][4]) == [34, 35, 36]
493 with pytest.raises(ValueError) as excinfo:
494 m.reshape_initializer_list(a, 1, 7, 3)
495 assert str(excinfo.value) == "cannot reshape array of size 42 into shape (1,7,3)"
496
497
498def test_reshape_tuple():
499 a = np.arange(3 * 7 * 2) + 1
500 x = m.reshape_tuple(a, (3, 7, 2))
501 assert x.shape == (3, 7, 2)
502 assert list(x[1][4]) == [23, 24]
503 y = m.reshape_tuple(x, (x.size,))
504 assert y.shape == (42,)
505 with pytest.raises(ValueError) as excinfo:
506 m.reshape_tuple(a, (3, 7, 1))
507 assert str(excinfo.value) == "cannot reshape array of size 42 into shape (3,7,1)"
508 with pytest.raises(ValueError) as excinfo:
509 m.reshape_tuple(a, ())
510 assert str(excinfo.value) == "cannot reshape array of size 42 into shape ()"
511
512
513def test_index_using_ellipsis():
514 a = m.index_using_ellipsis(np.zeros((5, 6, 7)))
515 assert a.shape == (6,)
516
517
518@pytest.mark.parametrize(
519 "test_func",
520 [
521 m.test_fmt_desc_float,
522 m.test_fmt_desc_double,
523 m.test_fmt_desc_const_float,
524 m.test_fmt_desc_const_double,
525 ],
526)
527def test_format_descriptors_for_floating_point_types(test_func):
528 assert "numpy.ndarray[numpy.float" in test_func.__doc__
529
530
531@pytest.mark.parametrize("forcecast", [False, True])
532@pytest.mark.parametrize("contiguity", [None, "C", "F"])
533@pytest.mark.parametrize("noconvert", [False, True])
534@pytest.mark.filterwarnings(
535 "ignore:Casting complex values to real discards the imaginary part:numpy.ComplexWarning"
536)
537def test_argument_conversions(forcecast, contiguity, noconvert):
538 function_name = "accept_double"
539 if contiguity == "C":
540 function_name += "_c_style"
541 elif contiguity == "F":
542 function_name += "_f_style"
543 if forcecast:
544 function_name += "_forcecast"
545 if noconvert:
546 function_name += "_noconvert"
547 function = getattr(m, function_name)
548
549 for dtype in [np.dtype("float32"), np.dtype("float64"), np.dtype("complex128")]:
550 for order in ["C", "F"]:
551 for shape in [(2, 2), (1, 3, 1, 1), (1, 1, 1), (0,)]:
552 if not noconvert:
553 # If noconvert is not passed, only complex128 needs to be truncated and
554 # "cannot be safely obtained". So without `forcecast`, the argument shouldn't
555 # be accepted.
556 should_raise = dtype.name == "complex128" and not forcecast
557 else:
558 # If noconvert is passed, only float64 and the matching order is accepted.
559 # If at most one dimension has a size greater than 1, the array is also
560 # trivially contiguous.
561 trivially_contiguous = sum(1 for d in shape if d > 1) <= 1
562 should_raise = dtype.name != "float64" or (
563 contiguity is not None
564 and contiguity != order
565 and not trivially_contiguous
566 )
567
568 array = np.zeros(shape, dtype=dtype, order=order)
569 if not should_raise:
570 function(array)
571 else:
572 with pytest.raises(
573 TypeError, match="incompatible function arguments"
574 ):
575 function(array)
576
577
578@pytest.mark.xfail("env.PYPY")
579def test_dtype_refcount_leak():
580 from sys import getrefcount
581
582 dtype = np.dtype(np.float_)
583 a = np.array([1], dtype=dtype)
584 before = getrefcount(dtype)
585 m.ndim(a)
586 after = getrefcount(dtype)
587 assert after == before
588
589
591 arr = np.zeros((), np.float64)
592 arr[()] = 37.2
593 assert m.round_trip_float(arr) == 37.2
Definition: pytypes.h:1746
Definition: pytypes.h:1200
object getattr(handle obj, handle name)
Definition: pytypes.h:537
str repr(handle h)
Definition: pytypes.h:2027
py::array arr