test_numpy_array.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. # -*- coding: utf-8 -*-
  2. import pytest
  3. import env # noqa: F401
  4. from pybind11_tests import numpy_array as m
  5. np = pytest.importorskip("numpy")
  6. def test_dtypes():
  7. # See issue #1328.
  8. # - Platform-dependent sizes.
  9. for size_check in m.get_platform_dtype_size_checks():
  10. print(size_check)
  11. assert size_check.size_cpp == size_check.size_numpy, size_check
  12. # - Concrete sizes.
  13. for check in m.get_concrete_dtype_checks():
  14. print(check)
  15. assert check.numpy == check.pybind11, check
  16. if check.numpy.num != check.pybind11.num:
  17. print(
  18. "NOTE: typenum mismatch for {}: {} != {}".format(
  19. check, check.numpy.num, check.pybind11.num
  20. )
  21. )
  22. @pytest.fixture(scope="function")
  23. def arr():
  24. return np.array([[1, 2, 3], [4, 5, 6]], "=u2")
  25. def test_array_attributes():
  26. a = np.array(0, "f8")
  27. assert m.ndim(a) == 0
  28. assert all(m.shape(a) == [])
  29. assert all(m.strides(a) == [])
  30. with pytest.raises(IndexError) as excinfo:
  31. m.shape(a, 0)
  32. assert str(excinfo.value) == "invalid axis: 0 (ndim = 0)"
  33. with pytest.raises(IndexError) as excinfo:
  34. m.strides(a, 0)
  35. assert str(excinfo.value) == "invalid axis: 0 (ndim = 0)"
  36. assert m.writeable(a)
  37. assert m.size(a) == 1
  38. assert m.itemsize(a) == 8
  39. assert m.nbytes(a) == 8
  40. assert m.owndata(a)
  41. a = np.array([[1, 2, 3], [4, 5, 6]], "u2").view()
  42. a.flags.writeable = False
  43. assert m.ndim(a) == 2
  44. assert all(m.shape(a) == [2, 3])
  45. assert m.shape(a, 0) == 2
  46. assert m.shape(a, 1) == 3
  47. assert all(m.strides(a) == [6, 2])
  48. assert m.strides(a, 0) == 6
  49. assert m.strides(a, 1) == 2
  50. with pytest.raises(IndexError) as excinfo:
  51. m.shape(a, 2)
  52. assert str(excinfo.value) == "invalid axis: 2 (ndim = 2)"
  53. with pytest.raises(IndexError) as excinfo:
  54. m.strides(a, 2)
  55. assert str(excinfo.value) == "invalid axis: 2 (ndim = 2)"
  56. assert not m.writeable(a)
  57. assert m.size(a) == 6
  58. assert m.itemsize(a) == 2
  59. assert m.nbytes(a) == 12
  60. assert not m.owndata(a)
  61. @pytest.mark.parametrize(
  62. "args, ret", [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)]
  63. )
  64. def test_index_offset(arr, args, ret):
  65. assert m.index_at(arr, *args) == ret
  66. assert m.index_at_t(arr, *args) == ret
  67. assert m.offset_at(arr, *args) == ret * arr.dtype.itemsize
  68. assert m.offset_at_t(arr, *args) == ret * arr.dtype.itemsize
  69. def test_dim_check_fail(arr):
  70. for func in (
  71. m.index_at,
  72. m.index_at_t,
  73. m.offset_at,
  74. m.offset_at_t,
  75. m.data,
  76. m.data_t,
  77. m.mutate_data,
  78. m.mutate_data_t,
  79. ):
  80. with pytest.raises(IndexError) as excinfo:
  81. func(arr, 1, 2, 3)
  82. assert str(excinfo.value) == "too many indices for an array: 3 (ndim = 2)"
  83. @pytest.mark.parametrize(
  84. "args, ret",
  85. [
  86. ([], [1, 2, 3, 4, 5, 6]),
  87. ([1], [4, 5, 6]),
  88. ([0, 1], [2, 3, 4, 5, 6]),
  89. ([1, 2], [6]),
  90. ],
  91. )
  92. def test_data(arr, args, ret):
  93. from sys import byteorder
  94. assert all(m.data_t(arr, *args) == ret)
  95. assert all(m.data(arr, *args)[(0 if byteorder == "little" else 1) :: 2] == ret)
  96. assert all(m.data(arr, *args)[(1 if byteorder == "little" else 0) :: 2] == 0)
  97. @pytest.mark.parametrize("dim", [0, 1, 3])
  98. def test_at_fail(arr, dim):
  99. for func in m.at_t, m.mutate_at_t:
  100. with pytest.raises(IndexError) as excinfo:
  101. func(arr, *([0] * dim))
  102. assert str(excinfo.value) == "index dimension mismatch: {} (ndim = 2)".format(
  103. dim
  104. )
  105. def test_at(arr):
  106. assert m.at_t(arr, 0, 2) == 3
  107. assert m.at_t(arr, 1, 0) == 4
  108. assert all(m.mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6])
  109. assert all(m.mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6])
  110. def test_mutate_readonly(arr):
  111. arr.flags.writeable = False
  112. for func, args in (
  113. (m.mutate_data, ()),
  114. (m.mutate_data_t, ()),
  115. (m.mutate_at_t, (0, 0)),
  116. ):
  117. with pytest.raises(ValueError) as excinfo:
  118. func(arr, *args)
  119. assert str(excinfo.value) == "array is not writeable"
  120. def test_mutate_data(arr):
  121. assert all(m.mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12])
  122. assert all(m.mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24])
  123. assert all(m.mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48])
  124. assert all(m.mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96])
  125. assert all(m.mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192])
  126. assert all(m.mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193])
  127. assert all(m.mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194])
  128. assert all(m.mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195])
  129. assert all(m.mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196])
  130. assert all(m.mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197])
  131. def test_bounds_check(arr):
  132. for func in (
  133. m.index_at,
  134. m.index_at_t,
  135. m.data,
  136. m.data_t,
  137. m.mutate_data,
  138. m.mutate_data_t,
  139. m.at_t,
  140. m.mutate_at_t,
  141. ):
  142. with pytest.raises(IndexError) as excinfo:
  143. func(arr, 2, 0)
  144. assert str(excinfo.value) == "index 2 is out of bounds for axis 0 with size 2"
  145. with pytest.raises(IndexError) as excinfo:
  146. func(arr, 0, 4)
  147. assert str(excinfo.value) == "index 4 is out of bounds for axis 1 with size 3"
  148. def test_make_c_f_array():
  149. assert m.make_c_array().flags.c_contiguous
  150. assert not m.make_c_array().flags.f_contiguous
  151. assert m.make_f_array().flags.f_contiguous
  152. assert not m.make_f_array().flags.c_contiguous
  153. def test_make_empty_shaped_array():
  154. m.make_empty_shaped_array()
  155. # empty shape means numpy scalar, PEP 3118
  156. assert m.scalar_int().ndim == 0
  157. assert m.scalar_int().shape == ()
  158. assert m.scalar_int() == 42
  159. def test_wrap():
  160. def assert_references(a, b, base=None):
  161. from distutils.version import LooseVersion
  162. if base is None:
  163. base = a
  164. assert a is not b
  165. assert a.__array_interface__["data"][0] == b.__array_interface__["data"][0]
  166. assert a.shape == b.shape
  167. assert a.strides == b.strides
  168. assert a.flags.c_contiguous == b.flags.c_contiguous
  169. assert a.flags.f_contiguous == b.flags.f_contiguous
  170. assert a.flags.writeable == b.flags.writeable
  171. assert a.flags.aligned == b.flags.aligned
  172. if LooseVersion(np.__version__) >= LooseVersion("1.14.0"):
  173. assert a.flags.writebackifcopy == b.flags.writebackifcopy
  174. else:
  175. assert a.flags.updateifcopy == b.flags.updateifcopy
  176. assert np.all(a == b)
  177. assert not b.flags.owndata
  178. assert b.base is base
  179. if a.flags.writeable and a.ndim == 2:
  180. a[0, 0] = 1234
  181. assert b[0, 0] == 1234
  182. a1 = np.array([1, 2], dtype=np.int16)
  183. assert a1.flags.owndata and a1.base is None
  184. a2 = m.wrap(a1)
  185. assert_references(a1, a2)
  186. a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order="F")
  187. assert a1.flags.owndata and a1.base is None
  188. a2 = m.wrap(a1)
  189. assert_references(a1, a2)
  190. a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order="C")
  191. a1.flags.writeable = False
  192. a2 = m.wrap(a1)
  193. assert_references(a1, a2)
  194. a1 = np.random.random((4, 4, 4))
  195. a2 = m.wrap(a1)
  196. assert_references(a1, a2)
  197. a1t = a1.transpose()
  198. a2 = m.wrap(a1t)
  199. assert_references(a1t, a2, a1)
  200. a1d = a1.diagonal()
  201. a2 = m.wrap(a1d)
  202. assert_references(a1d, a2, a1)
  203. a1m = a1[::-1, ::-1, ::-1]
  204. a2 = m.wrap(a1m)
  205. assert_references(a1m, a2, a1)
  206. def test_numpy_view(capture):
  207. with capture:
  208. ac = m.ArrayClass()
  209. ac_view_1 = ac.numpy_view()
  210. ac_view_2 = ac.numpy_view()
  211. assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))
  212. del ac
  213. pytest.gc_collect()
  214. assert (
  215. capture
  216. == """
  217. ArrayClass()
  218. ArrayClass::numpy_view()
  219. ArrayClass::numpy_view()
  220. """
  221. )
  222. ac_view_1[0] = 4
  223. ac_view_1[1] = 3
  224. assert ac_view_2[0] == 4
  225. assert ac_view_2[1] == 3
  226. with capture:
  227. del ac_view_1
  228. del ac_view_2
  229. pytest.gc_collect()
  230. pytest.gc_collect()
  231. assert (
  232. capture
  233. == """
  234. ~ArrayClass()
  235. """
  236. )
  237. def test_cast_numpy_int64_to_uint64():
  238. m.function_taking_uint64(123)
  239. m.function_taking_uint64(np.uint64(123))
  240. def test_isinstance():
  241. assert m.isinstance_untyped(np.array([1, 2, 3]), "not an array")
  242. assert m.isinstance_typed(np.array([1.0, 2.0, 3.0]))
  243. def test_constructors():
  244. defaults = m.default_constructors()
  245. for a in defaults.values():
  246. assert a.size == 0
  247. assert defaults["array"].dtype == np.array([]).dtype
  248. assert defaults["array_t<int32>"].dtype == np.int32
  249. assert defaults["array_t<double>"].dtype == np.float64
  250. results = m.converting_constructors([1, 2, 3])
  251. for a in results.values():
  252. np.testing.assert_array_equal(a, [1, 2, 3])
  253. assert results["array"].dtype == np.int_
  254. assert results["array_t<int32>"].dtype == np.int32
  255. assert results["array_t<double>"].dtype == np.float64
  256. def test_overload_resolution(msg):
  257. # Exact overload matches:
  258. assert m.overloaded(np.array([1], dtype="float64")) == "double"
  259. assert m.overloaded(np.array([1], dtype="float32")) == "float"
  260. assert m.overloaded(np.array([1], dtype="ushort")) == "unsigned short"
  261. assert m.overloaded(np.array([1], dtype="intc")) == "int"
  262. assert m.overloaded(np.array([1], dtype="longlong")) == "long long"
  263. assert m.overloaded(np.array([1], dtype="complex")) == "double complex"
  264. assert m.overloaded(np.array([1], dtype="csingle")) == "float complex"
  265. # No exact match, should call first convertible version:
  266. assert m.overloaded(np.array([1], dtype="uint8")) == "double"
  267. with pytest.raises(TypeError) as excinfo:
  268. m.overloaded("not an array")
  269. assert (
  270. msg(excinfo.value)
  271. == """
  272. overloaded(): incompatible function arguments. The following argument types are supported:
  273. 1. (arg0: numpy.ndarray[numpy.float64]) -> str
  274. 2. (arg0: numpy.ndarray[numpy.float32]) -> str
  275. 3. (arg0: numpy.ndarray[numpy.int32]) -> str
  276. 4. (arg0: numpy.ndarray[numpy.uint16]) -> str
  277. 5. (arg0: numpy.ndarray[numpy.int64]) -> str
  278. 6. (arg0: numpy.ndarray[numpy.complex128]) -> str
  279. 7. (arg0: numpy.ndarray[numpy.complex64]) -> str
  280. Invoked with: 'not an array'
  281. """
  282. )
  283. assert m.overloaded2(np.array([1], dtype="float64")) == "double"
  284. assert m.overloaded2(np.array([1], dtype="float32")) == "float"
  285. assert m.overloaded2(np.array([1], dtype="complex64")) == "float complex"
  286. assert m.overloaded2(np.array([1], dtype="complex128")) == "double complex"
  287. assert m.overloaded2(np.array([1], dtype="float32")) == "float"
  288. assert m.overloaded3(np.array([1], dtype="float64")) == "double"
  289. assert m.overloaded3(np.array([1], dtype="intc")) == "int"
  290. expected_exc = """
  291. overloaded3(): incompatible function arguments. The following argument types are supported:
  292. 1. (arg0: numpy.ndarray[numpy.int32]) -> str
  293. 2. (arg0: numpy.ndarray[numpy.float64]) -> str
  294. Invoked with: """
  295. with pytest.raises(TypeError) as excinfo:
  296. m.overloaded3(np.array([1], dtype="uintc"))
  297. assert msg(excinfo.value) == expected_exc + repr(np.array([1], dtype="uint32"))
  298. with pytest.raises(TypeError) as excinfo:
  299. m.overloaded3(np.array([1], dtype="float32"))
  300. assert msg(excinfo.value) == expected_exc + repr(np.array([1.0], dtype="float32"))
  301. with pytest.raises(TypeError) as excinfo:
  302. m.overloaded3(np.array([1], dtype="complex"))
  303. assert msg(excinfo.value) == expected_exc + repr(np.array([1.0 + 0.0j]))
  304. # Exact matches:
  305. assert m.overloaded4(np.array([1], dtype="double")) == "double"
  306. assert m.overloaded4(np.array([1], dtype="longlong")) == "long long"
  307. # Non-exact matches requiring conversion. Since float to integer isn't a
  308. # save conversion, it should go to the double overload, but short can go to
  309. # either (and so should end up on the first-registered, the long long).
  310. assert m.overloaded4(np.array([1], dtype="float32")) == "double"
  311. assert m.overloaded4(np.array([1], dtype="short")) == "long long"
  312. assert m.overloaded5(np.array([1], dtype="double")) == "double"
  313. assert m.overloaded5(np.array([1], dtype="uintc")) == "unsigned int"
  314. assert m.overloaded5(np.array([1], dtype="float32")) == "unsigned int"
  315. def test_greedy_string_overload():
  316. """Tests fix for #685 - ndarray shouldn't go to std::string overload"""
  317. assert m.issue685("abc") == "string"
  318. assert m.issue685(np.array([97, 98, 99], dtype="b")) == "array"
  319. assert m.issue685(123) == "other"
  320. def test_array_unchecked_fixed_dims(msg):
  321. z1 = np.array([[1, 2], [3, 4]], dtype="float64")
  322. m.proxy_add2(z1, 10)
  323. assert np.all(z1 == [[11, 12], [13, 14]])
  324. with pytest.raises(ValueError) as excinfo:
  325. m.proxy_add2(np.array([1.0, 2, 3]), 5.0)
  326. assert (
  327. msg(excinfo.value) == "array has incorrect number of dimensions: 1; expected 2"
  328. )
  329. expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype="int")
  330. assert np.all(m.proxy_init3(3.0) == expect_c)
  331. expect_f = np.transpose(expect_c)
  332. assert np.all(m.proxy_init3F(3.0) == expect_f)
  333. assert m.proxy_squared_L2_norm(np.array(range(6))) == 55
  334. assert m.proxy_squared_L2_norm(np.array(range(6), dtype="float64")) == 55
  335. assert m.proxy_auxiliaries2(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
  336. assert m.proxy_auxiliaries2(z1) == m.array_auxiliaries2(z1)
  337. assert m.proxy_auxiliaries1_const_ref(z1[0, :])
  338. assert m.proxy_auxiliaries2_const_ref(z1)
  339. def test_array_unchecked_dyn_dims(msg):
  340. z1 = np.array([[1, 2], [3, 4]], dtype="float64")
  341. m.proxy_add2_dyn(z1, 10)
  342. assert np.all(z1 == [[11, 12], [13, 14]])
  343. expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype="int")
  344. assert np.all(m.proxy_init3_dyn(3.0) == expect_c)
  345. assert m.proxy_auxiliaries2_dyn(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
  346. assert m.proxy_auxiliaries2_dyn(z1) == m.array_auxiliaries2(z1)
  347. def test_array_failure():
  348. with pytest.raises(ValueError) as excinfo:
  349. m.array_fail_test()
  350. assert str(excinfo.value) == "cannot create a pybind11::array from a nullptr"
  351. with pytest.raises(ValueError) as excinfo:
  352. m.array_t_fail_test()
  353. assert str(excinfo.value) == "cannot create a pybind11::array_t from a nullptr"
  354. with pytest.raises(ValueError) as excinfo:
  355. m.array_fail_test_negative_size()
  356. assert str(excinfo.value) == "negative dimensions are not allowed"
  357. def test_initializer_list():
  358. assert m.array_initializer_list1().shape == (1,)
  359. assert m.array_initializer_list2().shape == (1, 2)
  360. assert m.array_initializer_list3().shape == (1, 2, 3)
  361. assert m.array_initializer_list4().shape == (1, 2, 3, 4)
  362. def test_array_resize(msg):
  363. a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype="float64")
  364. m.array_reshape2(a)
  365. assert a.size == 9
  366. assert np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  367. # total size change should succced with refcheck off
  368. m.array_resize3(a, 4, False)
  369. assert a.size == 64
  370. # ... and fail with refcheck on
  371. try:
  372. m.array_resize3(a, 3, True)
  373. except ValueError as e:
  374. assert str(e).startswith("cannot resize an array")
  375. # transposed array doesn't own data
  376. b = a.transpose()
  377. try:
  378. m.array_resize3(b, 3, False)
  379. except ValueError as e:
  380. assert str(e).startswith("cannot resize this array: it does not own its data")
  381. # ... but reshape should be fine
  382. m.array_reshape2(b)
  383. assert b.shape == (8, 8)
  384. @pytest.mark.xfail("env.PYPY")
  385. def test_array_create_and_resize(msg):
  386. a = m.create_and_resize(2)
  387. assert a.size == 4
  388. assert np.all(a == 42.0)
  389. def test_index_using_ellipsis():
  390. a = m.index_using_ellipsis(np.zeros((5, 6, 7)))
  391. assert a.shape == (6,)
  392. @pytest.mark.parametrize("forcecast", [False, True])
  393. @pytest.mark.parametrize("contiguity", [None, "C", "F"])
  394. @pytest.mark.parametrize("noconvert", [False, True])
  395. @pytest.mark.filterwarnings(
  396. "ignore:Casting complex values to real discards the imaginary part:numpy.ComplexWarning"
  397. )
  398. def test_argument_conversions(forcecast, contiguity, noconvert):
  399. function_name = "accept_double"
  400. if contiguity == "C":
  401. function_name += "_c_style"
  402. elif contiguity == "F":
  403. function_name += "_f_style"
  404. if forcecast:
  405. function_name += "_forcecast"
  406. if noconvert:
  407. function_name += "_noconvert"
  408. function = getattr(m, function_name)
  409. for dtype in [np.dtype("float32"), np.dtype("float64"), np.dtype("complex128")]:
  410. for order in ["C", "F"]:
  411. for shape in [(2, 2), (1, 3, 1, 1), (1, 1, 1), (0,)]:
  412. if not noconvert:
  413. # If noconvert is not passed, only complex128 needs to be truncated and
  414. # "cannot be safely obtained". So without `forcecast`, the argument shouldn't
  415. # be accepted.
  416. should_raise = dtype.name == "complex128" and not forcecast
  417. else:
  418. # If noconvert is passed, only float64 and the matching order is accepted.
  419. # If at most one dimension has a size greater than 1, the array is also
  420. # trivially contiguous.
  421. trivially_contiguous = sum(1 for d in shape if d > 1) <= 1
  422. should_raise = dtype.name != "float64" or (
  423. contiguity is not None
  424. and contiguity != order
  425. and not trivially_contiguous
  426. )
  427. array = np.zeros(shape, dtype=dtype, order=order)
  428. if not should_raise:
  429. function(array)
  430. else:
  431. with pytest.raises(
  432. TypeError, match="incompatible function arguments"
  433. ):
  434. function(array)
  435. @pytest.mark.xfail("env.PYPY")
  436. def test_dtype_refcount_leak():
  437. from sys import getrefcount
  438. dtype = np.dtype(np.float_)
  439. a = np.array([1], dtype=dtype)
  440. before = getrefcount(dtype)
  441. m.ndim(a)
  442. after = getrefcount(dtype)
  443. assert after == before