You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

435 lines
16 KiB

2 months ago
  1. import pytest
  2. pytestmark = pytest.requires_numpy
  3. with pytest.suppress(ImportError):
  4. import numpy as np
  5. @pytest.fixture(scope='function')
  6. def arr():
  7. return np.array([[1, 2, 3], [4, 5, 6]], '=u2')
  8. def test_array_attributes():
  9. from pybind11_tests.array import (
  10. ndim, shape, strides, writeable, size, itemsize, nbytes, owndata
  11. )
  12. a = np.array(0, 'f8')
  13. assert ndim(a) == 0
  14. assert all(shape(a) == [])
  15. assert all(strides(a) == [])
  16. with pytest.raises(IndexError) as excinfo:
  17. shape(a, 0)
  18. assert str(excinfo.value) == 'invalid axis: 0 (ndim = 0)'
  19. with pytest.raises(IndexError) as excinfo:
  20. strides(a, 0)
  21. assert str(excinfo.value) == 'invalid axis: 0 (ndim = 0)'
  22. assert writeable(a)
  23. assert size(a) == 1
  24. assert itemsize(a) == 8
  25. assert nbytes(a) == 8
  26. assert owndata(a)
  27. a = np.array([[1, 2, 3], [4, 5, 6]], 'u2').view()
  28. a.flags.writeable = False
  29. assert ndim(a) == 2
  30. assert all(shape(a) == [2, 3])
  31. assert shape(a, 0) == 2
  32. assert shape(a, 1) == 3
  33. assert all(strides(a) == [6, 2])
  34. assert strides(a, 0) == 6
  35. assert strides(a, 1) == 2
  36. with pytest.raises(IndexError) as excinfo:
  37. shape(a, 2)
  38. assert str(excinfo.value) == 'invalid axis: 2 (ndim = 2)'
  39. with pytest.raises(IndexError) as excinfo:
  40. strides(a, 2)
  41. assert str(excinfo.value) == 'invalid axis: 2 (ndim = 2)'
  42. assert not writeable(a)
  43. assert size(a) == 6
  44. assert itemsize(a) == 2
  45. assert nbytes(a) == 12
  46. assert not owndata(a)
  47. @pytest.mark.parametrize('args, ret', [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)])
  48. def test_index_offset(arr, args, ret):
  49. from pybind11_tests.array import index_at, index_at_t, offset_at, offset_at_t
  50. assert index_at(arr, *args) == ret
  51. assert index_at_t(arr, *args) == ret
  52. assert offset_at(arr, *args) == ret * arr.dtype.itemsize
  53. assert offset_at_t(arr, *args) == ret * arr.dtype.itemsize
  54. def test_dim_check_fail(arr):
  55. from pybind11_tests.array import (index_at, index_at_t, offset_at, offset_at_t, data, data_t,
  56. mutate_data, mutate_data_t)
  57. for func in (index_at, index_at_t, offset_at, offset_at_t, data, data_t,
  58. mutate_data, mutate_data_t):
  59. with pytest.raises(IndexError) as excinfo:
  60. func(arr, 1, 2, 3)
  61. assert str(excinfo.value) == 'too many indices for an array: 3 (ndim = 2)'
  62. @pytest.mark.parametrize('args, ret',
  63. [([], [1, 2, 3, 4, 5, 6]),
  64. ([1], [4, 5, 6]),
  65. ([0, 1], [2, 3, 4, 5, 6]),
  66. ([1, 2], [6])])
  67. def test_data(arr, args, ret):
  68. from pybind11_tests.array import data, data_t
  69. from sys import byteorder
  70. assert all(data_t(arr, *args) == ret)
  71. assert all(data(arr, *args)[(0 if byteorder == 'little' else 1)::2] == ret)
  72. assert all(data(arr, *args)[(1 if byteorder == 'little' else 0)::2] == 0)
  73. def test_mutate_readonly(arr):
  74. from pybind11_tests.array import mutate_data, mutate_data_t, mutate_at_t
  75. arr.flags.writeable = False
  76. for func, args in (mutate_data, ()), (mutate_data_t, ()), (mutate_at_t, (0, 0)):
  77. with pytest.raises(ValueError) as excinfo:
  78. func(arr, *args)
  79. assert str(excinfo.value) == 'array is not writeable'
  80. @pytest.mark.parametrize('dim', [0, 1, 3])
  81. def test_at_fail(arr, dim):
  82. from pybind11_tests.array import at_t, mutate_at_t
  83. for func in at_t, mutate_at_t:
  84. with pytest.raises(IndexError) as excinfo:
  85. func(arr, *([0] * dim))
  86. assert str(excinfo.value) == 'index dimension mismatch: {} (ndim = 2)'.format(dim)
  87. def test_at(arr):
  88. from pybind11_tests.array import at_t, mutate_at_t
  89. assert at_t(arr, 0, 2) == 3
  90. assert at_t(arr, 1, 0) == 4
  91. assert all(mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6])
  92. assert all(mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6])
  93. def test_mutate_data(arr):
  94. from pybind11_tests.array import mutate_data, mutate_data_t
  95. assert all(mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12])
  96. assert all(mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24])
  97. assert all(mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48])
  98. assert all(mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96])
  99. assert all(mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192])
  100. assert all(mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193])
  101. assert all(mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194])
  102. assert all(mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195])
  103. assert all(mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196])
  104. assert all(mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197])
  105. def test_bounds_check(arr):
  106. from pybind11_tests.array import (index_at, index_at_t, data, data_t,
  107. mutate_data, mutate_data_t, at_t, mutate_at_t)
  108. funcs = (index_at, index_at_t, data, data_t,
  109. mutate_data, mutate_data_t, at_t, mutate_at_t)
  110. for func in funcs:
  111. with pytest.raises(IndexError) as excinfo:
  112. func(arr, 2, 0)
  113. assert str(excinfo.value) == 'index 2 is out of bounds for axis 0 with size 2'
  114. with pytest.raises(IndexError) as excinfo:
  115. func(arr, 0, 4)
  116. assert str(excinfo.value) == 'index 4 is out of bounds for axis 1 with size 3'
  117. def test_make_c_f_array():
  118. from pybind11_tests.array import (
  119. make_c_array, make_f_array
  120. )
  121. assert make_c_array().flags.c_contiguous
  122. assert not make_c_array().flags.f_contiguous
  123. assert make_f_array().flags.f_contiguous
  124. assert not make_f_array().flags.c_contiguous
  125. def test_wrap():
  126. from pybind11_tests.array import wrap
  127. def assert_references(a, b, base=None):
  128. if base is None:
  129. base = a
  130. assert a is not b
  131. assert a.__array_interface__['data'][0] == b.__array_interface__['data'][0]
  132. assert a.shape == b.shape
  133. assert a.strides == b.strides
  134. assert a.flags.c_contiguous == b.flags.c_contiguous
  135. assert a.flags.f_contiguous == b.flags.f_contiguous
  136. assert a.flags.writeable == b.flags.writeable
  137. assert a.flags.aligned == b.flags.aligned
  138. assert a.flags.updateifcopy == b.flags.updateifcopy
  139. assert np.all(a == b)
  140. assert not b.flags.owndata
  141. assert b.base is base
  142. if a.flags.writeable and a.ndim == 2:
  143. a[0, 0] = 1234
  144. assert b[0, 0] == 1234
  145. a1 = np.array([1, 2], dtype=np.int16)
  146. assert a1.flags.owndata and a1.base is None
  147. a2 = wrap(a1)
  148. assert_references(a1, a2)
  149. a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order='F')
  150. assert a1.flags.owndata and a1.base is None
  151. a2 = wrap(a1)
  152. assert_references(a1, a2)
  153. a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order='C')
  154. a1.flags.writeable = False
  155. a2 = wrap(a1)
  156. assert_references(a1, a2)
  157. a1 = np.random.random((4, 4, 4))
  158. a2 = wrap(a1)
  159. assert_references(a1, a2)
  160. a1t = a1.transpose()
  161. a2 = wrap(a1t)
  162. assert_references(a1t, a2, a1)
  163. a1d = a1.diagonal()
  164. a2 = wrap(a1d)
  165. assert_references(a1d, a2, a1)
  166. a1m = a1[::-1, ::-1, ::-1]
  167. a2 = wrap(a1m)
  168. assert_references(a1m, a2, a1)
  169. def test_numpy_view(capture):
  170. from pybind11_tests.array import ArrayClass
  171. with capture:
  172. ac = ArrayClass()
  173. ac_view_1 = ac.numpy_view()
  174. ac_view_2 = ac.numpy_view()
  175. assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))
  176. del ac
  177. pytest.gc_collect()
  178. assert capture == """
  179. ArrayClass()
  180. ArrayClass::numpy_view()
  181. ArrayClass::numpy_view()
  182. """
  183. ac_view_1[0] = 4
  184. ac_view_1[1] = 3
  185. assert ac_view_2[0] == 4
  186. assert ac_view_2[1] == 3
  187. with capture:
  188. del ac_view_1
  189. del ac_view_2
  190. pytest.gc_collect()
  191. pytest.gc_collect()
  192. assert capture == """
  193. ~ArrayClass()
  194. """
  195. @pytest.unsupported_on_pypy
  196. def test_cast_numpy_int64_to_uint64():
  197. from pybind11_tests.array import function_taking_uint64
  198. function_taking_uint64(123)
  199. function_taking_uint64(np.uint64(123))
  200. def test_isinstance():
  201. from pybind11_tests.array import isinstance_untyped, isinstance_typed
  202. assert isinstance_untyped(np.array([1, 2, 3]), "not an array")
  203. assert isinstance_typed(np.array([1.0, 2.0, 3.0]))
  204. def test_constructors():
  205. from pybind11_tests.array import default_constructors, converting_constructors
  206. defaults = default_constructors()
  207. for a in defaults.values():
  208. assert a.size == 0
  209. assert defaults["array"].dtype == np.array([]).dtype
  210. assert defaults["array_t<int32>"].dtype == np.int32
  211. assert defaults["array_t<double>"].dtype == np.float64
  212. results = converting_constructors([1, 2, 3])
  213. for a in results.values():
  214. np.testing.assert_array_equal(a, [1, 2, 3])
  215. assert results["array"].dtype == np.int_
  216. assert results["array_t<int32>"].dtype == np.int32
  217. assert results["array_t<double>"].dtype == np.float64
  218. def test_overload_resolution(msg):
  219. from pybind11_tests.array import overloaded, overloaded2, overloaded3, overloaded4, overloaded5
  220. # Exact overload matches:
  221. assert overloaded(np.array([1], dtype='float64')) == 'double'
  222. assert overloaded(np.array([1], dtype='float32')) == 'float'
  223. assert overloaded(np.array([1], dtype='ushort')) == 'unsigned short'
  224. assert overloaded(np.array([1], dtype='intc')) == 'int'
  225. assert overloaded(np.array([1], dtype='longlong')) == 'long long'
  226. assert overloaded(np.array([1], dtype='complex')) == 'double complex'
  227. assert overloaded(np.array([1], dtype='csingle')) == 'float complex'
  228. # No exact match, should call first convertible version:
  229. assert overloaded(np.array([1], dtype='uint8')) == 'double'
  230. with pytest.raises(TypeError) as excinfo:
  231. overloaded("not an array")
  232. assert msg(excinfo.value) == """
  233. overloaded(): incompatible function arguments. The following argument types are supported:
  234. 1. (arg0: numpy.ndarray[float64]) -> str
  235. 2. (arg0: numpy.ndarray[float32]) -> str
  236. 3. (arg0: numpy.ndarray[int32]) -> str
  237. 4. (arg0: numpy.ndarray[uint16]) -> str
  238. 5. (arg0: numpy.ndarray[int64]) -> str
  239. 6. (arg0: numpy.ndarray[complex128]) -> str
  240. 7. (arg0: numpy.ndarray[complex64]) -> str
  241. Invoked with: 'not an array'
  242. """
  243. assert overloaded2(np.array([1], dtype='float64')) == 'double'
  244. assert overloaded2(np.array([1], dtype='float32')) == 'float'
  245. assert overloaded2(np.array([1], dtype='complex64')) == 'float complex'
  246. assert overloaded2(np.array([1], dtype='complex128')) == 'double complex'
  247. assert overloaded2(np.array([1], dtype='float32')) == 'float'
  248. assert overloaded3(np.array([1], dtype='float64')) == 'double'
  249. assert overloaded3(np.array([1], dtype='intc')) == 'int'
  250. expected_exc = """
  251. overloaded3(): incompatible function arguments. The following argument types are supported:
  252. 1. (arg0: numpy.ndarray[int32]) -> str
  253. 2. (arg0: numpy.ndarray[float64]) -> str
  254. Invoked with:"""
  255. with pytest.raises(TypeError) as excinfo:
  256. overloaded3(np.array([1], dtype='uintc'))
  257. assert msg(excinfo.value) == expected_exc + " array([1], dtype=uint32)"
  258. with pytest.raises(TypeError) as excinfo:
  259. overloaded3(np.array([1], dtype='float32'))
  260. assert msg(excinfo.value) == expected_exc + " array([ 1.], dtype=float32)"
  261. with pytest.raises(TypeError) as excinfo:
  262. overloaded3(np.array([1], dtype='complex'))
  263. assert msg(excinfo.value) == expected_exc + " array([ 1.+0.j])"
  264. # Exact matches:
  265. assert overloaded4(np.array([1], dtype='double')) == 'double'
  266. assert overloaded4(np.array([1], dtype='longlong')) == 'long long'
  267. # Non-exact matches requiring conversion. Since float to integer isn't a
  268. # save conversion, it should go to the double overload, but short can go to
  269. # either (and so should end up on the first-registered, the long long).
  270. assert overloaded4(np.array([1], dtype='float32')) == 'double'
  271. assert overloaded4(np.array([1], dtype='short')) == 'long long'
  272. assert overloaded5(np.array([1], dtype='double')) == 'double'
  273. assert overloaded5(np.array([1], dtype='uintc')) == 'unsigned int'
  274. assert overloaded5(np.array([1], dtype='float32')) == 'unsigned int'
  275. def test_greedy_string_overload(): # issue 685
  276. from pybind11_tests.array import issue685
  277. assert issue685("abc") == "string"
  278. assert issue685(np.array([97, 98, 99], dtype='b')) == "array"
  279. assert issue685(123) == "other"
  280. def test_array_unchecked_fixed_dims(msg):
  281. from pybind11_tests.array import (proxy_add2, proxy_init3F, proxy_init3, proxy_squared_L2_norm,
  282. proxy_auxiliaries2, array_auxiliaries2)
  283. z1 = np.array([[1, 2], [3, 4]], dtype='float64')
  284. proxy_add2(z1, 10)
  285. assert np.all(z1 == [[11, 12], [13, 14]])
  286. with pytest.raises(ValueError) as excinfo:
  287. proxy_add2(np.array([1., 2, 3]), 5.0)
  288. assert msg(excinfo.value) == "array has incorrect number of dimensions: 1; expected 2"
  289. expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype='int')
  290. assert np.all(proxy_init3(3.0) == expect_c)
  291. expect_f = np.transpose(expect_c)
  292. assert np.all(proxy_init3F(3.0) == expect_f)
  293. assert proxy_squared_L2_norm(np.array(range(6))) == 55
  294. assert proxy_squared_L2_norm(np.array(range(6), dtype="float64")) == 55
  295. assert proxy_auxiliaries2(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
  296. assert proxy_auxiliaries2(z1) == array_auxiliaries2(z1)
  297. def test_array_unchecked_dyn_dims(msg):
  298. from pybind11_tests.array import (proxy_add2_dyn, proxy_init3_dyn, proxy_auxiliaries2_dyn,
  299. array_auxiliaries2)
  300. z1 = np.array([[1, 2], [3, 4]], dtype='float64')
  301. proxy_add2_dyn(z1, 10)
  302. assert np.all(z1 == [[11, 12], [13, 14]])
  303. expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype='int')
  304. assert np.all(proxy_init3_dyn(3.0) == expect_c)
  305. assert proxy_auxiliaries2_dyn(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
  306. assert proxy_auxiliaries2_dyn(z1) == array_auxiliaries2(z1)
  307. def test_array_failure():
  308. from pybind11_tests.array import (array_fail_test, array_t_fail_test,
  309. array_fail_test_negative_size)
  310. with pytest.raises(ValueError) as excinfo:
  311. array_fail_test()
  312. assert str(excinfo.value) == 'cannot create a pybind11::array from a nullptr'
  313. with pytest.raises(ValueError) as excinfo:
  314. array_t_fail_test()
  315. assert str(excinfo.value) == 'cannot create a pybind11::array_t from a nullptr'
  316. with pytest.raises(ValueError) as excinfo:
  317. array_fail_test_negative_size()
  318. assert str(excinfo.value) == 'negative dimensions are not allowed'
  319. def test_array_resize(msg):
  320. from pybind11_tests.array import (array_reshape2, array_resize3)
  321. a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='float64')
  322. array_reshape2(a)
  323. assert(a.size == 9)
  324. assert(np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
  325. # total size change should succced with refcheck off
  326. array_resize3(a, 4, False)
  327. assert(a.size == 64)
  328. # ... and fail with refcheck on
  329. try:
  330. array_resize3(a, 3, True)
  331. except ValueError as e:
  332. assert(str(e).startswith("cannot resize an array"))
  333. # transposed array doesn't own data
  334. b = a.transpose()
  335. try:
  336. array_resize3(b, 3, False)
  337. except ValueError as e:
  338. assert(str(e).startswith("cannot resize this array: it does not own its data"))
  339. # ... but reshape should be fine
  340. array_reshape2(b)
  341. assert(b.shape == (8, 8))
  342. @pytest.unsupported_on_pypy
  343. def test_array_create_and_resize(msg):
  344. from pybind11_tests.array import create_and_resize
  345. a = create_and_resize(2)
  346. assert(a.size == 4)
  347. assert(np.all(a == 42.))