4 from pybind11_tests
import numpy_array
as m
6 np = pytest.importorskip(
"numpy")
12 for size_check
in m.get_platform_dtype_size_checks():
14 assert size_check.size_cpp == size_check.size_numpy, size_check
16 for check
in m.get_concrete_dtype_checks():
18 assert check.numpy == check.pybind11, check
19 if check.numpy.num != check.pybind11.num:
21 f
"NOTE: typenum mismatch for {check}: {check.numpy.num} != {check.pybind11.num}"
27 return np.array([[1, 2, 3], [4, 5, 6]],
"=u2")
33 assert all(m.shape(a) == [])
34 assert all(m.strides(a) == [])
35 with pytest.raises(IndexError)
as excinfo:
37 assert str(excinfo.value) ==
"invalid axis: 0 (ndim = 0)"
38 with pytest.raises(IndexError)
as excinfo:
40 assert str(excinfo.value) ==
"invalid axis: 0 (ndim = 0)"
43 assert m.itemsize(a) == 8
44 assert m.nbytes(a) == 8
47 a = np.array([[1, 2, 3], [4, 5, 6]],
"u2").
view()
48 a.flags.writeable =
False
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:
58 assert str(excinfo.value) ==
"invalid axis: 2 (ndim = 2)"
59 with pytest.raises(IndexError)
as excinfo:
61 assert str(excinfo.value) ==
"invalid axis: 2 (ndim = 2)"
62 assert not m.writeable(a)
64 assert m.itemsize(a) == 2
65 assert m.nbytes(a) == 12
66 assert not m.owndata(a)
69 @pytest.mark.parametrize(
70 (
"args",
"ret"), [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)]
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
90 with pytest.raises(IndexError)
as excinfo:
92 assert str(excinfo.value) ==
"too many indices for an array: 3 (ndim = 2)"
95 @pytest.mark.parametrize(
98 ([], [1, 2, 3, 4, 5, 6]),
100 ([0, 1], [2, 3, 4, 5, 6]),
105 from sys
import byteorder
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)
112 @pytest.mark.parametrize(
"dim", [0, 1, 3])
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)"
121 assert m.at_t(arr, 0, 2) == 3
122 assert m.at_t(arr, 1, 0) == 4
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])
129 arr.flags.writeable =
False
132 (m.mutate_data_t, ()),
133 (m.mutate_at_t, (0, 0)),
135 with pytest.raises(ValueError)
as excinfo:
137 assert str(excinfo.value) ==
"array is not writeable"
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])
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])
165 with pytest.raises(IndexError)
as excinfo:
167 assert str(excinfo.value) ==
"index 2 is out of bounds for axis 0 with size 2"
168 with pytest.raises(IndexError)
as excinfo:
170 assert str(excinfo.value) ==
"index 4 is out of bounds for axis 1 with size 3"
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
181 m.make_empty_shaped_array()
184 assert m.scalar_int().ndim == 0
185 assert m.scalar_int().shape == ()
186 assert m.scalar_int() == 42
190 def assert_references(a, b, base=None):
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
202 if tuple(
int(x)
for x
in np.__version__.split(
".")[:2]) >= (1, 14):
203 assert a.flags.writebackifcopy == b.flags.writebackifcopy
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:
211 assert b[0, 0] == 1234
213 a1 = np.array([1, 2], dtype=np.int16)
214 assert a1.flags.owndata
215 assert a1.base
is None
217 assert_references(a1, a2)
219 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=
"F")
220 assert a1.flags.owndata
221 assert a1.base
is None
223 assert_references(a1, a2)
225 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=
"C")
226 a1.flags.writeable =
False
228 assert_references(a1, a2)
230 a1 = np.random.random((4, 4, 4))
232 assert_references(a1, a2)
236 assert_references(a1t, a2, a1)
240 assert_references(a1d, a2, a1)
242 a1m = a1[::-1, ::-1, ::-1]
244 assert_references(a1m, a2, a1)
250 ac_view_1 = ac.numpy_view()
251 ac_view_2 = ac.numpy_view()
252 assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))
259 ArrayClass::numpy_view()
260 ArrayClass::numpy_view()
265 assert ac_view_2[0] == 4
266 assert ac_view_2[1] == 3
281 m.function_taking_uint64(123)
282 m.function_taking_uint64(np.uint64(123))
286 assert m.isinstance_untyped(np.array([1, 2, 3]),
"not an array")
287 assert m.isinstance_typed(np.array([1.0, 2.0, 3.0]))
291 defaults = m.default_constructors()
292 for a
in defaults.values():
294 assert defaults[
"array"].dtype == np.array([]).dtype
295 assert defaults[
"array_t<int32>"].dtype == np.int32
296 assert defaults[
"array_t<double>"].dtype == np.float64
298 results = m.converting_constructors([1, 2, 3])
299 for a
in results.values():
300 np.testing.assert_array_equal(a, [1, 2, 3])
301 assert results[
"array"].dtype == np.int_
302 assert results[
"array_t<int32>"].dtype == np.int32
303 assert results[
"array_t<double>"].dtype == np.float64
308 assert m.overloaded(np.array([1], dtype=
"float64")) ==
"double"
309 assert m.overloaded(np.array([1], dtype=
"float32")) ==
"float"
310 assert m.overloaded(np.array([1], dtype=
"ushort")) ==
"unsigned short"
311 assert m.overloaded(np.array([1], dtype=
"intc")) ==
"int"
312 assert m.overloaded(np.array([1], dtype=
"longlong")) ==
"long long"
313 assert m.overloaded(np.array([1], dtype=
"complex")) ==
"double complex"
314 assert m.overloaded(np.array([1], dtype=
"csingle")) ==
"float complex"
317 assert m.overloaded(np.array([1], dtype=
"uint8")) ==
"double"
319 with pytest.raises(TypeError)
as excinfo:
320 m.overloaded(
"not an array")
324 overloaded(): incompatible function arguments. The following argument types are supported:
325 1. (arg0: numpy.ndarray[numpy.float64]) -> str
326 2. (arg0: numpy.ndarray[numpy.float32]) -> str
327 3. (arg0: numpy.ndarray[numpy.int32]) -> str
328 4. (arg0: numpy.ndarray[numpy.uint16]) -> str
329 5. (arg0: numpy.ndarray[numpy.int64]) -> str
330 6. (arg0: numpy.ndarray[numpy.complex128]) -> str
331 7. (arg0: numpy.ndarray[numpy.complex64]) -> str
333 Invoked with: 'not an array'
337 assert m.overloaded2(np.array([1], dtype=
"float64")) ==
"double"
338 assert m.overloaded2(np.array([1], dtype=
"float32")) ==
"float"
339 assert m.overloaded2(np.array([1], dtype=
"complex64")) ==
"float complex"
340 assert m.overloaded2(np.array([1], dtype=
"complex128")) ==
"double complex"
341 assert m.overloaded2(np.array([1], dtype=
"float32")) ==
"float"
343 assert m.overloaded3(np.array([1], dtype=
"float64")) ==
"double"
344 assert m.overloaded3(np.array([1], dtype=
"intc")) ==
"int"
346 overloaded3(): incompatible function arguments. The following argument types are supported:
347 1. (arg0: numpy.ndarray[numpy.int32]) -> str
348 2. (arg0: numpy.ndarray[numpy.float64]) -> str
352 with pytest.raises(TypeError)
as excinfo:
353 m.overloaded3(np.array([1], dtype=
"uintc"))
354 assert msg(excinfo.value) == expected_exc +
repr(np.array([1], dtype=
"uint32"))
355 with pytest.raises(TypeError)
as excinfo:
356 m.overloaded3(np.array([1], dtype=
"float32"))
357 assert msg(excinfo.value) == expected_exc +
repr(np.array([1.0], dtype=
"float32"))
358 with pytest.raises(TypeError)
as excinfo:
359 m.overloaded3(np.array([1], dtype=
"complex"))
360 assert msg(excinfo.value) == expected_exc +
repr(np.array([1.0 + 0.0j]))
363 assert m.overloaded4(np.array([1], dtype=
"double")) ==
"double"
364 assert m.overloaded4(np.array([1], dtype=
"longlong")) ==
"long long"
368 assert m.overloaded4(np.array([1], dtype=
"float32")) ==
"double"
369 assert m.overloaded4(np.array([1], dtype=
"short")) ==
"long long"
371 assert m.overloaded5(np.array([1], dtype=
"double")) ==
"double"
372 assert m.overloaded5(np.array([1], dtype=
"uintc")) ==
"unsigned int"
373 assert m.overloaded5(np.array([1], dtype=
"float32")) ==
"unsigned int"
377 """Tests fix for #685 - ndarray shouldn't go to std::string overload"""
379 assert m.issue685(
"abc") ==
"string"
380 assert m.issue685(np.array([97, 98, 99], dtype=
"b")) ==
"array"
381 assert m.issue685(123) ==
"other"
385 z1 = np.array([[1, 2], [3, 4]], dtype=
"float64")
387 assert np.all(z1 == [[11, 12], [13, 14]])
389 with pytest.raises(ValueError)
as excinfo:
390 m.proxy_add2(np.array([1.0, 2, 3]), 5.0)
392 msg(excinfo.value) ==
"array has incorrect number of dimensions: 1; expected 2"
395 expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(
range(3, 30)), dtype=
"int")
396 assert np.all(m.proxy_init3(3.0) == expect_c)
397 expect_f = np.transpose(expect_c)
398 assert np.all(m.proxy_init3F(3.0) == expect_f)
400 assert m.proxy_squared_L2_norm(np.array(
range(6))) == 55
401 assert m.proxy_squared_L2_norm(np.array(
range(6), dtype=
"float64")) == 55
403 assert m.proxy_auxiliaries2(z1) == [11, 11,
True, 2, 8, 2, 2, 4, 32]
404 assert m.proxy_auxiliaries2(z1) == m.array_auxiliaries2(z1)
406 assert m.proxy_auxiliaries1_const_ref(z1[0, :])
407 assert m.proxy_auxiliaries2_const_ref(z1)
411 z1 = np.array([[1, 2], [3, 4]], dtype=
"float64")
412 m.proxy_add2_dyn(z1, 10)
413 assert np.all(z1 == [[11, 12], [13, 14]])
415 expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(
range(3, 30)), dtype=
"int")
416 assert np.all(m.proxy_init3_dyn(3.0) == expect_c)
418 assert m.proxy_auxiliaries2_dyn(z1) == [11, 11,
True, 2, 8, 2, 2, 4, 32]
419 assert m.proxy_auxiliaries2_dyn(z1) == m.array_auxiliaries2(z1)
423 with pytest.raises(ValueError)
as excinfo:
425 assert str(excinfo.value) ==
"cannot create a pybind11::array from a nullptr"
427 with pytest.raises(ValueError)
as excinfo:
428 m.array_t_fail_test()
429 assert str(excinfo.value) ==
"cannot create a pybind11::array_t from a nullptr"
431 with pytest.raises(ValueError)
as excinfo:
432 m.array_fail_test_negative_size()
433 assert str(excinfo.value) ==
"negative dimensions are not allowed"
437 assert m.array_initializer_list1().shape == (1,)
438 assert m.array_initializer_list2().shape == (1, 2)
439 assert m.array_initializer_list3().shape == (1, 2, 3)
440 assert m.array_initializer_list4().shape == (1, 2, 3, 4)
444 a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=
"float64")
447 assert np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
450 m.array_resize3(a, 4,
False)
454 m.array_resize3(a, 3,
True)
455 except ValueError
as e:
456 assert str(e).startswith(
"cannot resize an array")
460 m.array_resize3(b, 3,
False)
461 except ValueError
as e:
462 assert str(e).startswith(
463 "cannot resize this array: it does not own its data"
467 assert b.shape == (8, 8)
470 @pytest.mark.xfail(
"env.PYPY")
472 a = m.create_and_resize(2)
474 assert np.all(a == 42.0)
478 a = np.ones(100 * 4).astype(
"uint8")
479 a_float_view = m.array_view(a,
"float32")
480 assert a_float_view.shape == (100 * 1,)
482 a_int16_view = m.array_view(a,
"int16")
483 assert a_int16_view.shape == (100 * 2,)
487 a = np.ones(100 * 4).astype(
"uint8")
488 with pytest.raises(TypeError):
489 m.array_view(a,
"deadly_dtype")
493 a = np.arange(2 * 7 * 3) + 1
494 x = m.reshape_initializer_list(a, 2, 7, 3)
495 assert x.shape == (2, 7, 3)
496 assert list(x[1][4]) == [34, 35, 36]
497 with pytest.raises(ValueError)
as excinfo:
498 m.reshape_initializer_list(a, 1, 7, 3)
499 assert str(excinfo.value) ==
"cannot reshape array of size 42 into shape (1,7,3)"
503 a = np.arange(3 * 7 * 2) + 1
504 x = m.reshape_tuple(a, (3, 7, 2))
505 assert x.shape == (3, 7, 2)
506 assert list(x[1][4]) == [23, 24]
507 y = m.reshape_tuple(x, (x.size,))
508 assert y.shape == (42,)
509 with pytest.raises(ValueError)
as excinfo:
510 m.reshape_tuple(a, (3, 7, 1))
511 assert str(excinfo.value) ==
"cannot reshape array of size 42 into shape (3,7,1)"
512 with pytest.raises(ValueError)
as excinfo:
513 m.reshape_tuple(a, ())
514 assert str(excinfo.value) ==
"cannot reshape array of size 42 into shape ()"
518 a = m.index_using_ellipsis(np.zeros((5, 6, 7)))
519 assert a.shape == (6,)
522 @pytest.mark.parametrize(
525 m.test_fmt_desc_float,
526 m.test_fmt_desc_double,
527 m.test_fmt_desc_const_float,
528 m.test_fmt_desc_const_double,
532 assert "numpy.ndarray[numpy.float" in test_func.__doc__
535 @pytest.mark.parametrize(
"forcecast", [
False,
True])
536 @pytest.mark.parametrize(
"contiguity", [
None,
"C",
"F"])
537 @pytest.mark.parametrize(
"noconvert", [
False,
True])
538 @pytest.mark.filterwarnings(
539 "ignore:Casting complex values to real discards the imaginary part:numpy.ComplexWarning"
542 function_name =
"accept_double"
543 if contiguity ==
"C":
544 function_name +=
"_c_style"
545 elif contiguity ==
"F":
546 function_name +=
"_f_style"
548 function_name +=
"_forcecast"
550 function_name +=
"_noconvert"
551 function =
getattr(m, function_name)
553 for dtype
in [np.dtype(
"float32"), np.dtype(
"float64"), np.dtype(
"complex128")]:
554 for order
in [
"C",
"F"]:
555 for shape
in [(2, 2), (1, 3, 1, 1), (1, 1, 1), (0,)]:
560 should_raise = dtype.name ==
"complex128" and not forcecast
565 trivially_contiguous = sum(1
for d
in shape
if d > 1) <= 1
566 should_raise = dtype.name !=
"float64" or (
567 contiguity
is not None
568 and contiguity != order
569 and not trivially_contiguous
572 array = np.zeros(shape, dtype=dtype, order=order)
577 TypeError, match=
"incompatible function arguments"
582 @pytest.mark.xfail(
"env.PYPY")
584 from sys
import getrefcount
586 dtype = np.dtype(np.float_)
587 a = np.array([1], dtype=dtype)
588 before = getrefcount(dtype)
590 after = getrefcount(dtype)
591 assert after == before
595 arr = np.zeros((), np.float64)
597 assert m.round_trip_float(arr) == 37.2
624 return [vh.value
for vh
in vhs]
630 m.pass_array_pyobject_ptr_return_sum_str_values(
640 m.pass_array_pyobject_ptr_return_sum_str_values(
650 m.pass_array_pyobject_ptr_return_as_list(
653 ) == [-1,
"two", 3.0]
656 @pytest.mark.parametrize(
657 (
"return_array_pyobject_ptr",
"unwrap"),
659 (m.return_array_pyobject_ptr_cpp_loop, list),
660 (m.return_array_pyobject_ptr_from_list, UnwrapPyValueHolder),
667 assert arr_from_list.dtype == np.dtype(
"O")
668 assert unwrap(arr_from_list) == [6,
"seven", -8.0]