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}" 25 @pytest.fixture(scope=
"function")
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
and a1.base
is None 216 assert_references(a1, a2)
218 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=
"F")
219 assert a1.flags.owndata
and 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.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(
"cannot resize this array: it does not own its data")
463 assert b.shape == (8, 8)
466 @pytest.mark.xfail(
"env.PYPY")
468 a = m.create_and_resize(2)
470 assert np.all(a == 42.0)
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,)
478 a_int16_view = m.array_view(a,
"int16")
479 assert a_int16_view.shape == (100 * 2,)
483 a = np.ones(100 * 4).astype(
"uint8")
484 with pytest.raises(TypeError):
485 m.array_view(a,
"deadly_dtype")
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)" 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 ()" 514 a = m.index_using_ellipsis(np.zeros((5, 6, 7)))
515 assert a.shape == (6,)
518 @pytest.mark.parametrize(
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,
528 assert "numpy.ndarray[numpy.float" in test_func.__doc__
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" 538 function_name =
"accept_double" 539 if contiguity ==
"C":
540 function_name +=
"_c_style" 541 elif contiguity ==
"F":
542 function_name +=
"_f_style" 544 function_name +=
"_forcecast" 546 function_name +=
"_noconvert" 547 function =
getattr(m, function_name)
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,)]:
556 should_raise = dtype.name ==
"complex128" and not forcecast
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
568 array = np.zeros(shape, dtype=dtype, order=order)
573 TypeError, match=
"incompatible function arguments" 578 @pytest.mark.xfail(
"env.PYPY")
580 from sys
import getrefcount
582 dtype = np.dtype(np.float_)
583 a = np.array([1], dtype=dtype)
584 before = getrefcount(dtype)
586 after = getrefcount(dtype)
587 assert after == before
def test_dtype_refcount_leak()
static const Eigen::internal::all_t all
def test_array_attributes()
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set set pointsize set encoding default set nopolar set noparametric set view
def test_initializer_list()
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
def test_index_using_ellipsis()
def test_dim_check_fail(arr)
def test_array_view_invalid()
def test_numpy_view(capture)
def test_mutate_readonly(arr)
def test_format_descriptors_for_floating_point_types(test_func)
def test_greedy_string_overload()
def test_bounds_check(arr)
def test_make_empty_shaped_array()
def test_array_unchecked_dyn_dims()
def test_array_create_and_resize()
object getattr(handle obj, handle name)
def test_cast_numpy_int64_to_uint64()
Double_ range(const Point2_ &p, const Point2_ &q)
def test_at_fail(arr, dim)
def test_argument_conversions(forcecast, contiguity, noconvert)
def test_array_unchecked_fixed_dims(msg)
def test_index_offset(arr, args, ret)
def test_overload_resolution(msg)
def test_make_c_f_array()
def test_data(arr, args, ret)
def test_reshape_initializer_list()
def test_mutate_data(arr)