test_numpy_array.py 15 KB

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