5from pybind11_tests
import numpy_array
as m
7np = pytest.importorskip(
"numpy")
13 for size_check
in m.get_platform_dtype_size_checks():
15 assert size_check.size_cpp == size_check.size_numpy, size_check
17 for check
in m.get_concrete_dtype_checks():
19 assert check.numpy == check.pybind11, check
20 if check.numpy.num != check.pybind11.num:
22 "NOTE: typenum mismatch for {}: {} != {}".format(
23 check, check.numpy.num, check.pybind11.num
28@pytest.fixture(scope="function")
30 return np.array([[1, 2, 3], [4, 5, 6]],
"=u2")
36 assert all(m.shape(a) == [])
37 assert all(m.strides(a) == [])
38 with pytest.raises(IndexError)
as excinfo:
40 assert str(excinfo.value) ==
"invalid axis: 0 (ndim = 0)"
41 with pytest.raises(IndexError)
as excinfo:
43 assert str(excinfo.value) ==
"invalid axis: 0 (ndim = 0)"
46 assert m.itemsize(a) == 8
47 assert m.nbytes(a) == 8
50 a = np.array([[1, 2, 3], [4, 5, 6]],
"u2").view()
51 a.flags.writeable =
False
53 assert all(m.shape(a) == [2, 3])
54 assert m.shape(a, 0) == 2
55 assert m.shape(a, 1) == 3
56 assert all(m.strides(a) == [6, 2])
57 assert m.strides(a, 0) == 6
58 assert m.strides(a, 1) == 2
59 with pytest.raises(IndexError)
as excinfo:
61 assert str(excinfo.value) ==
"invalid axis: 2 (ndim = 2)"
62 with pytest.raises(IndexError)
as excinfo:
64 assert str(excinfo.value) ==
"invalid axis: 2 (ndim = 2)"
65 assert not m.writeable(a)
67 assert m.itemsize(a) == 2
68 assert m.nbytes(a) == 12
69 assert not m.owndata(a)
72@pytest.mark.parametrize(
73 "args, ret", [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)]
76 assert m.index_at(arr, *args) == ret
77 assert m.index_at_t(arr, *args) == ret
78 assert m.offset_at(arr, *args) == ret * arr.dtype.itemsize
79 assert m.offset_at_t(arr, *args) == ret * arr.dtype.itemsize
93 with pytest.raises(IndexError)
as excinfo:
95 assert str(excinfo.value) ==
"too many indices for an array: 3 (ndim = 2)"
98@pytest.mark.parametrize(
101 ([], [1, 2, 3, 4, 5, 6]),
103 ([0, 1], [2, 3, 4, 5, 6]),
108 from sys
import byteorder
110 assert all(m.data_t(arr, *args) == ret)
111 assert all(m.data(arr, *args)[(0
if byteorder ==
"little" else 1) :: 2] == ret)
112 assert all(m.data(arr, *args)[(1
if byteorder ==
"little" else 0) :: 2] == 0)
115@pytest.mark.parametrize("dim", [0, 1, 3])
117 for func
in m.at_t, m.mutate_at_t:
118 with pytest.raises(IndexError)
as excinfo:
119 func(arr, *([0] * dim))
120 assert str(excinfo.value) ==
"index dimension mismatch: {} (ndim = 2)".format(
126 assert m.at_t(arr, 0, 2) == 3
127 assert m.at_t(arr, 1, 0) == 4
129 assert all(m.mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6])
130 assert all(m.mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6])
134 arr.flags.writeable =
False
137 (m.mutate_data_t, ()),
138 (m.mutate_at_t, (0, 0)),
140 with pytest.raises(ValueError)
as excinfo:
142 assert str(excinfo.value) ==
"array is not writeable"
146 assert all(m.mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12])
147 assert all(m.mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24])
148 assert all(m.mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48])
149 assert all(m.mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96])
150 assert all(m.mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192])
152 assert all(m.mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193])
153 assert all(m.mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194])
154 assert all(m.mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195])
155 assert all(m.mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196])
156 assert all(m.mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197])
170 with pytest.raises(IndexError)
as excinfo:
172 assert str(excinfo.value) ==
"index 2 is out of bounds for axis 0 with size 2"
173 with pytest.raises(IndexError)
as excinfo:
175 assert str(excinfo.value) ==
"index 4 is out of bounds for axis 1 with size 3"
179 assert m.make_c_array().flags.c_contiguous
180 assert not m.make_c_array().flags.f_contiguous
181 assert m.make_f_array().flags.f_contiguous
182 assert not m.make_f_array().flags.c_contiguous
186 m.make_empty_shaped_array()
189 assert m.scalar_int().ndim == 0
190 assert m.scalar_int().shape == ()
191 assert m.scalar_int() == 42
195 def assert_references(a, b, base=None):
196 from distutils.version
import LooseVersion
201 assert a.__array_interface__[
"data"][0] == b.__array_interface__[
"data"][0]
202 assert a.shape == b.shape
203 assert a.strides == b.strides
204 assert a.flags.c_contiguous == b.flags.c_contiguous
205 assert a.flags.f_contiguous == b.flags.f_contiguous
206 assert a.flags.writeable == b.flags.writeable
207 assert a.flags.aligned == b.flags.aligned
208 if LooseVersion(np.__version__) >= LooseVersion(
"1.14.0"):
209 assert a.flags.writebackifcopy == b.flags.writebackifcopy
211 assert a.flags.updateifcopy == b.flags.updateifcopy
212 assert np.all(a == b)
213 assert not b.flags.owndata
214 assert b.base
is base
215 if a.flags.writeable
and a.ndim == 2:
217 assert b[0, 0] == 1234
219 a1 = np.array([1, 2], dtype=np.int16)
220 assert a1.flags.owndata
and a1.base
is None
222 assert_references(a1, a2)
224 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=
"F")
225 assert a1.flags.owndata
and a1.base
is None
227 assert_references(a1, a2)
229 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=
"C")
230 a1.flags.writeable =
False
232 assert_references(a1, a2)
234 a1 = np.random.random((4, 4, 4))
236 assert_references(a1, a2)
240 assert_references(a1t, a2, a1)
244 assert_references(a1d, a2, a1)
246 a1m = a1[::-1, ::-1, ::-1]
248 assert_references(a1m, a2, a1)
254 ac_view_1 = ac.numpy_view()
255 ac_view_2 = ac.numpy_view()
256 assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))
263 ArrayClass::numpy_view()
264 ArrayClass::numpy_view()
269 assert ac_view_2[0] == 4
270 assert ac_view_2[1] == 3
285 m.function_taking_uint64(123)
286 m.function_taking_uint64(np.uint64(123))
290 assert m.isinstance_untyped(np.array([1, 2, 3]),
"not an array")
291 assert m.isinstance_typed(np.array([1.0, 2.0, 3.0]))
295 defaults = m.default_constructors()
296 for a
in defaults.values():
298 assert defaults[
"array"].dtype == np.array([]).dtype
299 assert defaults[
"array_t<int32>"].dtype == np.int32
300 assert defaults[
"array_t<double>"].dtype == np.float64
302 results = m.converting_constructors([1, 2, 3])
303 for a
in results.values():
304 np.testing.assert_array_equal(a, [1, 2, 3])
305 assert results[
"array"].dtype == np.int_
306 assert results[
"array_t<int32>"].dtype == np.int32
307 assert results[
"array_t<double>"].dtype == np.float64
312 assert m.overloaded(np.array([1], dtype=
"float64")) ==
"double"
313 assert m.overloaded(np.array([1], dtype=
"float32")) ==
"float"
314 assert m.overloaded(np.array([1], dtype=
"ushort")) ==
"unsigned short"
315 assert m.overloaded(np.array([1], dtype=
"intc")) ==
"int"
316 assert m.overloaded(np.array([1], dtype=
"longlong")) ==
"long long"
317 assert m.overloaded(np.array([1], dtype=
"complex")) ==
"double complex"
318 assert m.overloaded(np.array([1], dtype=
"csingle")) ==
"float complex"
321 assert m.overloaded(np.array([1], dtype=
"uint8")) ==
"double"
323 with pytest.raises(TypeError)
as excinfo:
324 m.overloaded(
"not an array")
328 overloaded(): incompatible function arguments. The following argument types are supported:
329 1. (arg0: numpy.ndarray[numpy.float64]) -> str
330 2. (arg0: numpy.ndarray[numpy.float32]) -> str
331 3. (arg0: numpy.ndarray[numpy.int32]) -> str
332 4. (arg0: numpy.ndarray[numpy.uint16]) -> str
333 5. (arg0: numpy.ndarray[numpy.int64]) -> str
334 6. (arg0: numpy.ndarray[numpy.complex128]) -> str
335 7. (arg0: numpy.ndarray[numpy.complex64]) -> str
337 Invoked with:
'not an array'
341 assert m.overloaded2(np.array([1], dtype=
"float64")) ==
"double"
342 assert m.overloaded2(np.array([1], dtype=
"float32")) ==
"float"
343 assert m.overloaded2(np.array([1], dtype=
"complex64")) ==
"float complex"
344 assert m.overloaded2(np.array([1], dtype=
"complex128")) ==
"double complex"
345 assert m.overloaded2(np.array([1], dtype=
"float32")) ==
"float"
347 assert m.overloaded3(np.array([1], dtype=
"float64")) ==
"double"
348 assert m.overloaded3(np.array([1], dtype=
"intc")) ==
"int"
350 overloaded3(): incompatible function arguments. The following argument types are supported:
351 1. (arg0: numpy.ndarray[numpy.int32]) -> str
352 2. (arg0: numpy.ndarray[numpy.float64]) -> str
356 with pytest.raises(TypeError)
as excinfo:
357 m.overloaded3(np.array([1], dtype=
"uintc"))
358 assert msg(excinfo.value) == expected_exc +
repr(np.array([1], dtype=
"uint32"))
359 with pytest.raises(TypeError)
as excinfo:
360 m.overloaded3(np.array([1], dtype=
"float32"))
361 assert msg(excinfo.value) == expected_exc +
repr(np.array([1.0], dtype=
"float32"))
362 with pytest.raises(TypeError)
as excinfo:
363 m.overloaded3(np.array([1], dtype=
"complex"))
364 assert msg(excinfo.value) == expected_exc +
repr(np.array([1.0 + 0.0j]))
367 assert m.overloaded4(np.array([1], dtype=
"double")) ==
"double"
368 assert m.overloaded4(np.array([1], dtype=
"longlong")) ==
"long long"
372 assert m.overloaded4(np.array([1], dtype=
"float32")) ==
"double"
373 assert m.overloaded4(np.array([1], dtype=
"short")) ==
"long long"
375 assert m.overloaded5(np.array([1], dtype=
"double")) ==
"double"
376 assert m.overloaded5(np.array([1], dtype=
"uintc")) ==
"unsigned int"
377 assert m.overloaded5(np.array([1], dtype=
"float32")) ==
"unsigned int"
381 """Tests fix for #685 - ndarray shouldn't go to std::string overload"""
383 assert m.issue685(
"abc") ==
"string"
384 assert m.issue685(np.array([97, 98, 99], dtype=
"b")) ==
"array"
385 assert m.issue685(123) ==
"other"
389 z1 = np.array([[1, 2], [3, 4]], dtype=
"float64")
391 assert np.all(z1 == [[11, 12], [13, 14]])
393 with pytest.raises(ValueError)
as excinfo:
394 m.proxy_add2(np.array([1.0, 2, 3]), 5.0)
396 msg(excinfo.value) ==
"array has incorrect number of dimensions: 1; expected 2"
399 expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype=
"int")
400 assert np.all(m.proxy_init3(3.0) == expect_c)
401 expect_f = np.transpose(expect_c)
402 assert np.all(m.proxy_init3F(3.0) == expect_f)
404 assert m.proxy_squared_L2_norm(np.array(range(6))) == 55
405 assert m.proxy_squared_L2_norm(np.array(range(6), dtype=
"float64")) == 55
407 assert m.proxy_auxiliaries2(z1) == [11, 11,
True, 2, 8, 2, 2, 4, 32]
408 assert m.proxy_auxiliaries2(z1) == m.array_auxiliaries2(z1)
410 assert m.proxy_auxiliaries1_const_ref(z1[0, :])
411 assert m.proxy_auxiliaries2_const_ref(z1)
415 z1 = np.array([[1, 2], [3, 4]], dtype=
"float64")
416 m.proxy_add2_dyn(z1, 10)
417 assert np.all(z1 == [[11, 12], [13, 14]])
419 expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype=
"int")
420 assert np.all(m.proxy_init3_dyn(3.0) == expect_c)
422 assert m.proxy_auxiliaries2_dyn(z1) == [11, 11,
True, 2, 8, 2, 2, 4, 32]
423 assert m.proxy_auxiliaries2_dyn(z1) == m.array_auxiliaries2(z1)
427 with pytest.raises(ValueError)
as excinfo:
429 assert str(excinfo.value) ==
"cannot create a pybind11::array from a nullptr"
431 with pytest.raises(ValueError)
as excinfo:
432 m.array_t_fail_test()
433 assert str(excinfo.value) ==
"cannot create a pybind11::array_t from a nullptr"
435 with pytest.raises(ValueError)
as excinfo:
436 m.array_fail_test_negative_size()
437 assert str(excinfo.value) ==
"negative dimensions are not allowed"
441 assert m.array_initializer_list1().shape == (1,)
442 assert m.array_initializer_list2().shape == (1, 2)
443 assert m.array_initializer_list3().shape == (1, 2, 3)
444 assert m.array_initializer_list4().shape == (1, 2, 3, 4)
448 a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=
"float64")
451 assert np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
454 m.array_resize3(a, 4,
False)
458 m.array_resize3(a, 3,
True)
459 except ValueError
as e:
460 assert str(e).startswith(
"cannot resize an array")
464 m.array_resize3(b, 3,
False)
465 except ValueError
as e:
466 assert str(e).startswith(
"cannot resize this array: it does not own its data")
469 assert b.shape == (8, 8)
472@pytest.mark.xfail("env.PYPY")
474 a = m.create_and_resize(2)
476 assert np.all(a == 42.0)
480 a = np.ones(100 * 4).astype(
"uint8")
481 a_float_view = m.array_view(a,
"float32")
482 assert a_float_view.shape == (100 * 1,)
484 a_int16_view = m.array_view(a,
"int16")
485 assert a_int16_view.shape == (100 * 2,)
489 a = np.ones(100 * 4).astype(
"uint8")
490 with pytest.raises(TypeError):
491 m.array_view(a,
"deadly_dtype")
495 a = np.arange(2 * 7 * 3) + 1
496 x = m.reshape_initializer_list(a, 2, 7, 3)
497 assert x.shape == (2, 7, 3)
498 assert list(x[1][4]) == [34, 35, 36]
499 with pytest.raises(ValueError)
as excinfo:
500 m.reshape_initializer_list(a, 1, 7, 3)
501 assert str(excinfo.value) ==
"cannot reshape array of size 42 into shape (1,7,3)"
505 a = np.arange(3 * 7 * 2) + 1
506 x = m.reshape_tuple(a, (3, 7, 2))
507 assert x.shape == (3, 7, 2)
508 assert list(x[1][4]) == [23, 24]
509 y = m.reshape_tuple(x, (x.size,))
510 assert y.shape == (42,)
511 with pytest.raises(ValueError)
as excinfo:
512 m.reshape_tuple(a, (3, 7, 1))
513 assert str(excinfo.value) ==
"cannot reshape array of size 42 into shape (3,7,1)"
514 with pytest.raises(ValueError)
as excinfo:
515 m.reshape_tuple(a, ())
516 assert str(excinfo.value) ==
"cannot reshape array of size 42 into shape ()"
520 a = m.index_using_ellipsis(np.zeros((5, 6, 7)))
521 assert a.shape == (6,)
524@pytest.mark.parametrize(
527 m.test_fmt_desc_float,
528 m.test_fmt_desc_double,
529 m.test_fmt_desc_const_float,
530 m.test_fmt_desc_const_double,
534 assert "numpy.ndarray[numpy.float" in test_func.__doc__
537@pytest.mark.parametrize("forcecast", [False, True])
538@pytest.mark.parametrize("contiguity", [None, "C", "F"])
539@pytest.mark.parametrize("noconvert", [False, True])
540@pytest.mark.filterwarnings(
541 "ignore:Casting complex values to real discards the imaginary part:numpy.ComplexWarning"
544 function_name =
"accept_double"
545 if contiguity ==
"C":
546 function_name +=
"_c_style"
547 elif contiguity ==
"F":
548 function_name +=
"_f_style"
550 function_name +=
"_forcecast"
552 function_name +=
"_noconvert"
553 function =
getattr(m, function_name)
555 for dtype
in [np.dtype(
"float32"), np.dtype(
"float64"), np.dtype(
"complex128")]:
556 for order
in [
"C",
"F"]:
557 for shape
in [(2, 2), (1, 3, 1, 1), (1, 1, 1), (0,)]:
562 should_raise = dtype.name ==
"complex128" and not forcecast
567 trivially_contiguous = sum(1
for d
in shape
if d > 1) <= 1
568 should_raise = dtype.name !=
"float64" or (
569 contiguity
is not None
570 and contiguity != order
571 and not trivially_contiguous
574 array = np.zeros(shape, dtype=dtype, order=order)
579 TypeError, match=
"incompatible function arguments"
584@pytest.mark.xfail("env.PYPY")
586 from sys
import getrefcount
588 dtype = np.dtype(np.float_)
589 a = np.array([1], dtype=dtype)
590 before = getrefcount(dtype)
592 after = getrefcount(dtype)
593 assert after == before
object getattr(handle obj, handle name)
def test_index_offset(arr, args, ret)
def test_overload_resolution(msg)
def test_data(arr, args, ret)
def test_array_unchecked_fixed_dims(msg)
def test_index_using_ellipsis()
def test_reshape_initializer_list()
def test_make_c_f_array()
def test_mutate_readonly(arr)
def test_dim_check_fail(arr)
def test_make_empty_shaped_array()
def test_dtype_refcount_leak()
def test_cast_numpy_int64_to_uint64()
def test_array_unchecked_dyn_dims()
def test_format_descriptors_for_floating_point_types(test_func)
def test_argument_conversions(forcecast, contiguity, noconvert)
def test_array_view_invalid()
def test_mutate_data(arr)
def test_at_fail(arr, dim)
def test_numpy_view(capture)
def test_array_create_and_resize()
def test_array_attributes()
def test_greedy_string_overload()
def test_bounds_check(arr)
def test_initializer_list()