1 from __future__
import annotations
6 from pybind11_tests
import numpy_array
as m
8 np = pytest.importorskip(
"numpy")
14 for size_check
in m.get_platform_dtype_size_checks():
16 assert size_check.size_cpp == size_check.size_numpy, size_check
18 for check
in m.get_concrete_dtype_checks():
20 assert check.numpy == check.pybind11, check
21 if check.numpy.num != check.pybind11.num:
23 f
"NOTE: typenum mismatch for {check}: {check.numpy.num} != {check.pybind11.num}"
29 return np.array([[1, 2, 3], [4, 5, 6]],
"=u2")
35 assert all(m.shape(a) == [])
36 assert all(m.strides(a) == [])
37 with pytest.raises(IndexError)
as excinfo:
39 assert str(excinfo.value) ==
"invalid axis: 0 (ndim = 0)"
40 with pytest.raises(IndexError)
as excinfo:
42 assert str(excinfo.value) ==
"invalid axis: 0 (ndim = 0)"
45 assert m.itemsize(a) == 8
46 assert m.nbytes(a) == 8
49 a = np.array([[1, 2, 3], [4, 5, 6]],
"u2").
view()
50 a.flags.writeable =
False
52 assert all(m.shape(a) == [2, 3])
53 assert m.shape(a, 0) == 2
54 assert m.shape(a, 1) == 3
55 assert all(m.strides(a) == [6, 2])
56 assert m.strides(a, 0) == 6
57 assert m.strides(a, 1) == 2
58 with pytest.raises(IndexError)
as excinfo:
60 assert str(excinfo.value) ==
"invalid axis: 2 (ndim = 2)"
61 with pytest.raises(IndexError)
as excinfo:
63 assert str(excinfo.value) ==
"invalid axis: 2 (ndim = 2)"
64 assert not m.writeable(a)
66 assert m.itemsize(a) == 2
67 assert m.nbytes(a) == 12
68 assert not m.owndata(a)
71 @pytest.mark.parametrize(
72 (
"args",
"ret"), [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)]
75 assert m.index_at(arr, *args) == ret
76 assert m.index_at_t(arr, *args) == ret
77 assert m.offset_at(arr, *args) == ret * arr.dtype.itemsize
78 assert m.offset_at_t(arr, *args) == ret * arr.dtype.itemsize
92 with pytest.raises(IndexError)
as excinfo:
94 assert str(excinfo.value) ==
"too many indices for an array: 3 (ndim = 2)"
97 @pytest.mark.parametrize(
100 ([], [1, 2, 3, 4, 5, 6]),
102 ([0, 1], [2, 3, 4, 5, 6]),
107 from sys
import byteorder
109 assert all(m.data_t(arr, *args) == ret)
110 assert all(m.data(arr, *args)[(0
if byteorder ==
"little" else 1) :: 2] == ret)
111 assert all(m.data(arr, *args)[(1
if byteorder ==
"little" else 0) :: 2] == 0)
114 @pytest.mark.parametrize(
"dim", [0, 1, 3])
116 for func
in m.at_t, m.mutate_at_t:
117 with pytest.raises(IndexError)
as excinfo:
118 func(arr, *([0] * dim))
119 assert str(excinfo.value) == f
"index dimension mismatch: {dim} (ndim = 2)"
123 assert m.at_t(arr, 0, 2) == 3
124 assert m.at_t(arr, 1, 0) == 4
126 assert all(m.mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6])
127 assert all(m.mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6])
131 arr.flags.writeable =
False
134 (m.mutate_data_t, ()),
135 (m.mutate_at_t, (0, 0)),
137 with pytest.raises(ValueError)
as excinfo:
139 assert str(excinfo.value) ==
"array is not writeable"
143 assert all(m.mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12])
144 assert all(m.mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24])
145 assert all(m.mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48])
146 assert all(m.mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96])
147 assert all(m.mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192])
149 assert all(m.mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193])
150 assert all(m.mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194])
151 assert all(m.mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195])
152 assert all(m.mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196])
153 assert all(m.mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197])
167 with pytest.raises(IndexError)
as excinfo:
169 assert str(excinfo.value) ==
"index 2 is out of bounds for axis 0 with size 2"
170 with pytest.raises(IndexError)
as excinfo:
172 assert str(excinfo.value) ==
"index 4 is out of bounds for axis 1 with size 3"
176 assert m.make_c_array().flags.c_contiguous
177 assert not m.make_c_array().flags.f_contiguous
178 assert m.make_f_array().flags.f_contiguous
179 assert not m.make_f_array().flags.c_contiguous
183 m.make_empty_shaped_array()
186 assert m.scalar_int().ndim == 0
187 assert m.scalar_int().shape == ()
188 assert m.scalar_int() == 42
192 def assert_references(a, b, base=None):
196 assert a.__array_interface__[
"data"][0] == b.__array_interface__[
"data"][0]
197 assert a.shape == b.shape
198 assert a.strides == b.strides
199 assert a.flags.c_contiguous == b.flags.c_contiguous
200 assert a.flags.f_contiguous == b.flags.f_contiguous
201 assert a.flags.writeable == b.flags.writeable
202 assert a.flags.aligned == b.flags.aligned
203 assert a.flags.writebackifcopy == b.flags.writebackifcopy
204 assert np.all(a == b)
205 assert not b.flags.owndata
206 assert b.base
is base
207 if a.flags.writeable
and a.ndim == 2:
209 assert b[0, 0] == 1234
211 a1 = np.array([1, 2], dtype=np.int16)
212 assert a1.flags.owndata
213 assert a1.base
is None
215 assert_references(a1, a2)
217 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=
"F")
218 assert a1.flags.owndata
219 assert a1.base
is None
221 assert_references(a1, a2)
223 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=
"C")
224 a1.flags.writeable =
False
226 assert_references(a1, a2)
228 a1 = np.random.random((4, 4, 4))
230 assert_references(a1, a2)
234 assert_references(a1t, a2, a1)
238 assert_references(a1d, a2, a1)
240 a1m = a1[::-1, ::-1, ::-1]
242 assert_references(a1m, a2, a1)
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))
257 ArrayClass::numpy_view()
258 ArrayClass::numpy_view()
263 assert ac_view_2[0] == 4
264 assert ac_view_2[1] == 3
279 m.function_taking_uint64(123)
280 m.function_taking_uint64(np.uint64(123))
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]))
289 defaults = m.default_constructors()
290 for a
in defaults.values():
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
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.dtype(int)
300 assert results[
"array_t<int32>"].dtype == np.int32
301 assert results[
"array_t<double>"].dtype == np.float64
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"
315 assert m.overloaded(np.array([1], dtype=
"uint8")) ==
"double"
317 with pytest.raises(TypeError)
as excinfo:
318 m.overloaded(
"not an array")
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
331 Invoked with: 'not an array'
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"
341 assert m.overloaded3(np.array([1], dtype=
"float64")) ==
"double"
342 assert m.overloaded3(np.array([1], dtype=
"intc")) ==
"int"
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
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]))
361 assert m.overloaded4(np.array([1], dtype=
"double")) ==
"double"
362 assert m.overloaded4(np.array([1], dtype=
"longlong")) ==
"long long"
366 assert m.overloaded4(np.array([1], dtype=
"float32")) ==
"double"
367 assert m.overloaded4(np.array([1], dtype=
"short")) ==
"long long"
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"
375 """Tests fix for #685 - ndarray shouldn't go to std::string overload"""
377 assert m.issue685(
"abc") ==
"string"
378 assert m.issue685(np.array([97, 98, 99], dtype=
"b")) ==
"array"
379 assert m.issue685(123) ==
"other"
383 z1 = np.array([[1, 2], [3, 4]], dtype=
"float64")
385 assert np.all(z1 == [[11, 12], [13, 14]])
387 with pytest.raises(ValueError)
as excinfo:
388 m.proxy_add2(np.array([1.0, 2, 3]), 5.0)
390 msg(excinfo.value) ==
"array has incorrect number of dimensions: 1; expected 2"
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)
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
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)
404 assert m.proxy_auxiliaries1_const_ref(z1[0, :])
405 assert m.proxy_auxiliaries2_const_ref(z1)
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]])
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)
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)
421 with pytest.raises(ValueError)
as excinfo:
423 assert str(excinfo.value) ==
"cannot create a pybind11::array from a nullptr"
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"
429 with pytest.raises(ValueError)
as excinfo:
430 m.array_fail_test_negative_size()
431 assert str(excinfo.value) ==
"negative dimensions are not allowed"
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)
442 a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=
"float64")
445 assert np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
448 m.array_resize3(a, 4,
False)
452 m.array_resize3(a, 3,
True)
453 except ValueError
as e:
454 assert str(e).startswith(
"cannot resize an array")
458 m.array_resize3(b, 3,
False)
459 except ValueError
as e:
460 assert str(e).startswith(
461 "cannot resize this array: it does not own its data"
465 assert b.shape == (8, 8)
468 @pytest.mark.xfail(
"env.PYPY")
470 a = m.create_and_resize(2)
472 assert np.all(a == 42.0)
476 a = np.ones(100 * 4).astype(
"uint8")
477 a_float_view = m.array_view(a,
"float32")
478 assert a_float_view.shape == (100 * 1,)
480 a_int16_view = m.array_view(a,
"int16")
481 assert a_int16_view.shape == (100 * 2,)
485 a = np.ones(100 * 4).astype(
"uint8")
486 with pytest.raises(TypeError):
487 m.array_view(a,
"deadly_dtype")
491 a = np.arange(2 * 7 * 3) + 1
492 x = m.reshape_initializer_list(a, 2, 7, 3)
493 assert x.shape == (2, 7, 3)
494 assert list(x[1][4]) == [34, 35, 36]
495 with pytest.raises(ValueError)
as excinfo:
496 m.reshape_initializer_list(a, 1, 7, 3)
497 assert str(excinfo.value) ==
"cannot reshape array of size 42 into shape (1,7,3)"
501 a = np.arange(3 * 7 * 2) + 1
502 x = m.reshape_tuple(a, (3, 7, 2))
503 assert x.shape == (3, 7, 2)
504 assert list(x[1][4]) == [23, 24]
505 y = m.reshape_tuple(x, (x.size,))
506 assert y.shape == (42,)
507 with pytest.raises(ValueError)
as excinfo:
508 m.reshape_tuple(a, (3, 7, 1))
509 assert str(excinfo.value) ==
"cannot reshape array of size 42 into shape (3,7,1)"
510 with pytest.raises(ValueError)
as excinfo:
511 m.reshape_tuple(a, ())
512 assert str(excinfo.value) ==
"cannot reshape array of size 42 into shape ()"
516 a = m.index_using_ellipsis(np.zeros((5, 6, 7)))
517 assert a.shape == (6,)
520 @pytest.mark.parametrize(
523 m.test_fmt_desc_float,
524 m.test_fmt_desc_double,
525 m.test_fmt_desc_const_float,
526 m.test_fmt_desc_const_double,
530 assert "numpy.ndarray[numpy.float" in test_func.__doc__
533 @pytest.mark.parametrize(
"forcecast", [
False,
True])
534 @pytest.mark.parametrize(
"contiguity", [
None,
"C",
"F"])
535 @pytest.mark.parametrize(
"noconvert", [
False,
True])
536 @pytest.mark.filterwarnings(
537 "ignore:Casting complex values to real discards the imaginary part:"
539 "numpy.exceptions.ComplexWarning"
541 else "numpy.ComplexWarning"
545 function_name =
"accept_double"
546 if contiguity ==
"C":
547 function_name +=
"_c_style"
548 elif contiguity ==
"F":
549 function_name +=
"_f_style"
551 function_name +=
"_forcecast"
553 function_name +=
"_noconvert"
554 function =
getattr(m, function_name)
556 for dtype
in [np.dtype(
"float32"), np.dtype(
"float64"), np.dtype(
"complex128")]:
557 for order
in [
"C",
"F"]:
558 for shape
in [(2, 2), (1, 3, 1, 1), (1, 1, 1), (0,)]:
563 should_raise = dtype.name ==
"complex128" and not forcecast
568 trivially_contiguous = sum(1
for d
in shape
if d > 1) <= 1
569 should_raise = dtype.name !=
"float64" or (
570 contiguity
is not None
571 and contiguity != order
572 and not trivially_contiguous
575 array = np.zeros(shape, dtype=dtype, order=order)
580 TypeError, match=
"incompatible function arguments"
585 @pytest.mark.xfail(
"env.PYPY")
587 from sys
import getrefcount
590 dtype = np.dtype(np.float64)
591 a = np.array([1], dtype=dtype)
592 before = getrefcount(dtype)
594 after = getrefcount(dtype)
595 assert after == before
599 arr = np.zeros((), np.float64)
601 assert m.round_trip_float(arr) == 37.2
628 return [vh.value
for vh
in vhs]
634 m.pass_array_pyobject_ptr_return_sum_str_values(
644 m.pass_array_pyobject_ptr_return_sum_str_values(
654 m.pass_array_pyobject_ptr_return_as_list(
657 ) == [-1,
"two", 3.0]
660 @pytest.mark.parametrize(
661 (
"return_array_pyobject_ptr",
"unwrap"),
663 (m.return_array_pyobject_ptr_cpp_loop, list),
664 (m.return_array_pyobject_ptr_from_list, UnwrapPyValueHolder),
671 assert arr_from_list.dtype == np.dtype(
"O")
672 assert unwrap(arr_from_list) == [6,
"seven", -8.0]