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:
22 print(
"NOTE: typenum mismatch for {}: {} != {}".format(
23 check, check.numpy.num, check.pybind11.num))
26 @pytest.fixture(scope=
'function')
28 return np.array([[1, 2, 3], [4, 5, 6]],
'=u2')
34 assert all(m.shape(a) == [])
35 assert all(m.strides(a) == [])
36 with pytest.raises(IndexError)
as excinfo:
38 assert str(excinfo.value) ==
'invalid axis: 0 (ndim = 0)' 39 with pytest.raises(IndexError)
as excinfo:
41 assert str(excinfo.value) ==
'invalid axis: 0 (ndim = 0)' 44 assert m.itemsize(a) == 8
45 assert m.nbytes(a) == 8
48 a = np.array([[1, 2, 3], [4, 5, 6]],
'u2').
view()
49 a.flags.writeable =
False 51 assert all(m.shape(a) == [2, 3])
52 assert m.shape(a, 0) == 2
53 assert m.shape(a, 1) == 3
54 assert all(m.strides(a) == [6, 2])
55 assert m.strides(a, 0) == 6
56 assert m.strides(a, 1) == 2
57 with pytest.raises(IndexError)
as excinfo:
59 assert str(excinfo.value) ==
'invalid axis: 2 (ndim = 2)' 60 with pytest.raises(IndexError)
as excinfo:
62 assert str(excinfo.value) ==
'invalid axis: 2 (ndim = 2)' 63 assert not m.writeable(a)
65 assert m.itemsize(a) == 2
66 assert m.nbytes(a) == 12
67 assert not m.owndata(a)
70 @pytest.mark.parametrize(
'args, ret', [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)])
72 assert m.index_at(arr, *args) == ret
73 assert m.index_at_t(arr, *args) == ret
74 assert m.offset_at(arr, *args) == ret * arr.dtype.itemsize
75 assert m.offset_at_t(arr, *args) == ret * arr.dtype.itemsize
79 for func
in (m.index_at, m.index_at_t, m.offset_at, m.offset_at_t, m.data, m.data_t,
80 m.mutate_data, m.mutate_data_t):
81 with pytest.raises(IndexError)
as excinfo:
83 assert str(excinfo.value) ==
'too many indices for an array: 3 (ndim = 2)' 86 @pytest.mark.parametrize(
'args, ret',
87 [([], [1, 2, 3, 4, 5, 6]),
89 ([0, 1], [2, 3, 4, 5, 6]),
92 from sys
import byteorder
93 assert all(m.data_t(arr, *args) == ret)
94 assert all(m.data(arr, *args)[(0
if byteorder ==
'little' else 1)::2] == ret)
95 assert all(m.data(arr, *args)[(1
if byteorder ==
'little' else 0)::2] == 0)
98 @pytest.mark.parametrize(
'dim', [0, 1, 3])
100 for func
in m.at_t, m.mutate_at_t:
101 with pytest.raises(IndexError)
as excinfo:
102 func(arr, *([0] * dim))
103 assert str(excinfo.value) ==
'index dimension mismatch: {} (ndim = 2)'.format(dim)
107 assert m.at_t(arr, 0, 2) == 3
108 assert m.at_t(arr, 1, 0) == 4
110 assert all(m.mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6])
111 assert all(m.mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6])
115 arr.flags.writeable =
False 116 for func, args
in (m.mutate_data, ()), (m.mutate_data_t, ()), (m.mutate_at_t, (0, 0)):
117 with pytest.raises(ValueError)
as excinfo:
119 assert str(excinfo.value) ==
'array is not writeable' 123 assert all(m.mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12])
124 assert all(m.mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24])
125 assert all(m.mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48])
126 assert all(m.mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96])
127 assert all(m.mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192])
129 assert all(m.mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193])
130 assert all(m.mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194])
131 assert all(m.mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195])
132 assert all(m.mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196])
133 assert all(m.mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197])
137 for func
in (m.index_at, m.index_at_t, m.data, m.data_t,
138 m.mutate_data, m.mutate_data_t, m.at_t, m.mutate_at_t):
139 with pytest.raises(IndexError)
as excinfo:
141 assert str(excinfo.value) ==
'index 2 is out of bounds for axis 0 with size 2' 142 with pytest.raises(IndexError)
as excinfo:
144 assert str(excinfo.value) ==
'index 4 is out of bounds for axis 1 with size 3' 148 assert m.make_c_array().flags.c_contiguous
149 assert not m.make_c_array().flags.f_contiguous
150 assert m.make_f_array().flags.f_contiguous
151 assert not m.make_f_array().flags.c_contiguous
155 m.make_empty_shaped_array()
158 assert m.scalar_int().ndim == 0
159 assert m.scalar_int().shape == ()
160 assert m.scalar_int() == 42
164 def assert_references(a, b, base=None):
165 from distutils.version
import LooseVersion
169 assert a.__array_interface__[
'data'][0] == b.__array_interface__[
'data'][0]
170 assert a.shape == b.shape
171 assert a.strides == b.strides
172 assert a.flags.c_contiguous == b.flags.c_contiguous
173 assert a.flags.f_contiguous == b.flags.f_contiguous
174 assert a.flags.writeable == b.flags.writeable
175 assert a.flags.aligned == b.flags.aligned
176 if LooseVersion(np.__version__) >= LooseVersion(
"1.14.0"):
177 assert a.flags.writebackifcopy == b.flags.writebackifcopy
179 assert a.flags.updateifcopy == b.flags.updateifcopy
180 assert np.all(a == b)
181 assert not b.flags.owndata
182 assert b.base
is base
183 if a.flags.writeable
and a.ndim == 2:
185 assert b[0, 0] == 1234
187 a1 = np.array([1, 2], dtype=np.int16)
188 assert a1.flags.owndata
and a1.base
is None 190 assert_references(a1, a2)
192 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=
'F')
193 assert a1.flags.owndata
and a1.base
is None 195 assert_references(a1, a2)
197 a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order=
'C')
198 a1.flags.writeable =
False 200 assert_references(a1, a2)
202 a1 = np.random.random((4, 4, 4))
204 assert_references(a1, a2)
208 assert_references(a1t, a2, a1)
212 assert_references(a1d, a2, a1)
214 a1m = a1[::-1, ::-1, ::-1]
216 assert_references(a1m, a2, a1)
222 ac_view_1 = ac.numpy_view()
223 ac_view_2 = ac.numpy_view()
224 assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))
227 assert capture ==
""" 229 ArrayClass::numpy_view() 230 ArrayClass::numpy_view() 234 assert ac_view_2[0] == 4
235 assert ac_view_2[1] == 3
241 assert capture ==
""" 247 m.function_taking_uint64(123)
248 m.function_taking_uint64(np.uint64(123))
252 assert m.isinstance_untyped(np.array([1, 2, 3]),
"not an array")
253 assert m.isinstance_typed(np.array([1.0, 2.0, 3.0]))
257 defaults = m.default_constructors()
258 for a
in defaults.values():
260 assert defaults[
"array"].dtype == np.array([]).dtype
261 assert defaults[
"array_t<int32>"].dtype == np.int32
262 assert defaults[
"array_t<double>"].dtype == np.float64
264 results = m.converting_constructors([1, 2, 3])
265 for a
in results.values():
266 np.testing.assert_array_equal(a, [1, 2, 3])
267 assert results[
"array"].dtype == np.int_
268 assert results[
"array_t<int32>"].dtype == np.int32
269 assert results[
"array_t<double>"].dtype == np.float64
274 assert m.overloaded(np.array([1], dtype=
'float64')) ==
'double' 275 assert m.overloaded(np.array([1], dtype=
'float32')) ==
'float' 276 assert m.overloaded(np.array([1], dtype=
'ushort')) ==
'unsigned short' 277 assert m.overloaded(np.array([1], dtype=
'intc')) ==
'int' 278 assert m.overloaded(np.array([1], dtype=
'longlong')) ==
'long long' 279 assert m.overloaded(np.array([1], dtype=
'complex')) ==
'double complex' 280 assert m.overloaded(np.array([1], dtype=
'csingle')) ==
'float complex' 283 assert m.overloaded(np.array([1], dtype=
'uint8')) ==
'double' 285 with pytest.raises(TypeError)
as excinfo:
286 m.overloaded(
"not an array")
287 assert msg(excinfo.value) ==
""" 288 overloaded(): incompatible function arguments. The following argument types are supported: 289 1. (arg0: numpy.ndarray[numpy.float64]) -> str 290 2. (arg0: numpy.ndarray[numpy.float32]) -> str 291 3. (arg0: numpy.ndarray[numpy.int32]) -> str 292 4. (arg0: numpy.ndarray[numpy.uint16]) -> str 293 5. (arg0: numpy.ndarray[numpy.int64]) -> str 294 6. (arg0: numpy.ndarray[numpy.complex128]) -> str 295 7. (arg0: numpy.ndarray[numpy.complex64]) -> str 297 Invoked with: 'not an array' 300 assert m.overloaded2(np.array([1], dtype=
'float64')) ==
'double' 301 assert m.overloaded2(np.array([1], dtype=
'float32')) ==
'float' 302 assert m.overloaded2(np.array([1], dtype=
'complex64')) ==
'float complex' 303 assert m.overloaded2(np.array([1], dtype=
'complex128')) ==
'double complex' 304 assert m.overloaded2(np.array([1], dtype=
'float32')) ==
'float' 306 assert m.overloaded3(np.array([1], dtype=
'float64')) ==
'double' 307 assert m.overloaded3(np.array([1], dtype=
'intc')) ==
'int' 309 overloaded3(): incompatible function arguments. The following argument types are supported: 310 1. (arg0: numpy.ndarray[numpy.int32]) -> str 311 2. (arg0: numpy.ndarray[numpy.float64]) -> str 315 with pytest.raises(TypeError)
as excinfo:
316 m.overloaded3(np.array([1], dtype=
'uintc'))
317 assert msg(excinfo.value) == expected_exc +
repr(np.array([1], dtype=
'uint32'))
318 with pytest.raises(TypeError)
as excinfo:
319 m.overloaded3(np.array([1], dtype=
'float32'))
320 assert msg(excinfo.value) == expected_exc +
repr(np.array([1.], dtype=
'float32'))
321 with pytest.raises(TypeError)
as excinfo:
322 m.overloaded3(np.array([1], dtype=
'complex'))
323 assert msg(excinfo.value) == expected_exc +
repr(np.array([1. + 0.j]))
326 assert m.overloaded4(np.array([1], dtype=
'double')) ==
'double' 327 assert m.overloaded4(np.array([1], dtype=
'longlong')) ==
'long long' 331 assert m.overloaded4(np.array([1], dtype=
'float32')) ==
'double' 332 assert m.overloaded4(np.array([1], dtype=
'short')) ==
'long long' 334 assert m.overloaded5(np.array([1], dtype=
'double')) ==
'double' 335 assert m.overloaded5(np.array([1], dtype=
'uintc')) ==
'unsigned int' 336 assert m.overloaded5(np.array([1], dtype=
'float32')) ==
'unsigned int' 340 """Tests fix for #685 - ndarray shouldn't go to std::string overload""" 342 assert m.issue685(
"abc") ==
"string" 343 assert m.issue685(np.array([97, 98, 99], dtype=
'b')) ==
"array" 344 assert m.issue685(123) ==
"other" 348 z1 = np.array([[1, 2], [3, 4]], dtype=
'float64')
350 assert np.all(z1 == [[11, 12], [13, 14]])
352 with pytest.raises(ValueError)
as excinfo:
353 m.proxy_add2(np.array([1., 2, 3]), 5.0)
354 assert msg(excinfo.value) ==
"array has incorrect number of dimensions: 1; expected 2" 356 expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype=
'int')
357 assert np.all(m.proxy_init3(3.0) == expect_c)
358 expect_f = np.transpose(expect_c)
359 assert np.all(m.proxy_init3F(3.0) == expect_f)
361 assert m.proxy_squared_L2_norm(np.array(range(6))) == 55
362 assert m.proxy_squared_L2_norm(np.array(range(6), dtype=
"float64")) == 55
364 assert m.proxy_auxiliaries2(z1) == [11, 11,
True, 2, 8, 2, 2, 4, 32]
365 assert m.proxy_auxiliaries2(z1) == m.array_auxiliaries2(z1)
369 z1 = np.array([[1, 2], [3, 4]], dtype=
'float64')
370 m.proxy_add2_dyn(z1, 10)
371 assert np.all(z1 == [[11, 12], [13, 14]])
373 expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype=
'int')
374 assert np.all(m.proxy_init3_dyn(3.0) == expect_c)
376 assert m.proxy_auxiliaries2_dyn(z1) == [11, 11,
True, 2, 8, 2, 2, 4, 32]
377 assert m.proxy_auxiliaries2_dyn(z1) == m.array_auxiliaries2(z1)
381 with pytest.raises(ValueError)
as excinfo:
383 assert str(excinfo.value) ==
'cannot create a pybind11::array from a nullptr' 385 with pytest.raises(ValueError)
as excinfo:
386 m.array_t_fail_test()
387 assert str(excinfo.value) ==
'cannot create a pybind11::array_t from a nullptr' 389 with pytest.raises(ValueError)
as excinfo:
390 m.array_fail_test_negative_size()
391 assert str(excinfo.value) ==
'negative dimensions are not allowed' 395 assert m.array_initializer_list1().shape == (1,)
396 assert m.array_initializer_list2().shape == (1, 2)
397 assert m.array_initializer_list3().shape == (1, 2, 3)
398 assert m.array_initializer_list4().shape == (1, 2, 3, 4)
402 a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=
'float64')
405 assert(np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
408 m.array_resize3(a, 4,
False)
412 m.array_resize3(a, 3,
True)
413 except ValueError
as e:
414 assert(
str(e).startswith(
"cannot resize an array"))
418 m.array_resize3(b, 3,
False)
419 except ValueError
as e:
420 assert(
str(e).startswith(
"cannot resize this array: it does not own its data"))
423 assert(b.shape == (8, 8))
426 @pytest.mark.xfail(
"env.PYPY")
428 a = m.create_and_resize(2)
430 assert(np.all(a == 42.))
434 a = m.index_using_ellipsis(np.zeros((5, 6, 7)))
435 assert a.shape == (6,)
438 @pytest.mark.parametrize(
"forcecast", [
False,
True])
439 @pytest.mark.parametrize(
"contiguity", [
None,
'C',
'F'])
440 @pytest.mark.parametrize(
"noconvert", [
False,
True])
441 @pytest.mark.filterwarnings(
442 "ignore:Casting complex values to real discards the imaginary part:numpy.ComplexWarning" 445 function_name =
"accept_double" 446 if contiguity ==
'C':
447 function_name +=
"_c_style" 448 elif contiguity ==
'F':
449 function_name +=
"_f_style" 451 function_name +=
"_forcecast" 453 function_name +=
"_noconvert" 454 function =
getattr(m, function_name)
456 for dtype
in [np.dtype(
'float32'), np.dtype(
'float64'), np.dtype(
'complex128')]:
457 for order
in [
'C',
'F']:
458 for shape
in [(2, 2), (1, 3, 1, 1), (1, 1, 1), (0,)]:
463 should_raise = dtype.name ==
'complex128' and not forcecast
468 trivially_contiguous =
sum(1
for d
in shape
if d > 1) <= 1
470 dtype.name !=
'float64' or 471 (contiguity
is not None and 472 contiguity != order
and 473 not trivially_contiguous)
476 array = np.zeros(shape, dtype=dtype, order=order)
480 with pytest.raises(TypeError, match=
"incompatible function arguments"):
484 @pytest.mark.xfail(
"env.PYPY")
486 from sys
import getrefcount
487 dtype = np.dtype(np.float_)
488 a = np.array([1], dtype=dtype)
489 before = getrefcount(dtype)
491 after = getrefcount(dtype)
492 assert after == before
void print(const Matrix &A, const string &s, ostream &stream)
def test_dtype_refcount_leak()
def test_array_resize(msg)
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()
def test_index_using_ellipsis()
def test_dim_check_fail(arr)
def test_numpy_view(capture)
def test_mutate_readonly(arr)
def test_greedy_string_overload()
def test_bounds_check(arr)
const mpreal sum(const mpreal tab[], const unsigned long int n, int &status, mp_rnd_t mode=mpreal::get_default_rnd())
def test_make_empty_shaped_array()
def test_array_unchecked_dyn_dims(msg)
object getattr(handle obj, handle name)
def test_cast_numpy_int64_to_uint64()
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_array_create_and_resize(msg)
def test_overload_resolution(msg)
def test_make_c_f_array()
def test_data(arr, args, ret)
def test_mutate_data(arr)