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.

379 lines
14 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years 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. def test_numpy_view(capture):
  167. from pybind11_tests.array import ArrayClass
  168. with capture:
  169. ac = ArrayClass()
  170. ac_view_1 = ac.numpy_view()
  171. ac_view_2 = ac.numpy_view()
  172. assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32))
  173. del ac
  174. pytest.gc_collect()
  175. assert capture == """
  176. ArrayClass()
  177. ArrayClass::numpy_view()
  178. ArrayClass::numpy_view()
  179. """
  180. ac_view_1[0] = 4
  181. ac_view_1[1] = 3
  182. assert ac_view_2[0] == 4
  183. assert ac_view_2[1] == 3
  184. with capture:
  185. del ac_view_1
  186. del ac_view_2
  187. pytest.gc_collect()
  188. pytest.gc_collect()
  189. assert capture == """
  190. ~ArrayClass()
  191. """
  192. @pytest.unsupported_on_pypy
  193. def test_cast_numpy_int64_to_uint64():
  194. from pybind11_tests.array import function_taking_uint64
  195. function_taking_uint64(123)
  196. function_taking_uint64(np.uint64(123))
  197. def test_isinstance():
  198. from pybind11_tests.array import isinstance_untyped, isinstance_typed
  199. assert isinstance_untyped(np.array([1, 2, 3]), "not an array")
  200. assert isinstance_typed(np.array([1.0, 2.0, 3.0]))
  201. def test_constructors():
  202. from pybind11_tests.array import default_constructors, converting_constructors
  203. defaults = default_constructors()
  204. for a in defaults.values():
  205. assert a.size == 0
  206. assert defaults["array"].dtype == np.array([]).dtype
  207. assert defaults["array_t<int32>"].dtype == np.int32
  208. assert defaults["array_t<double>"].dtype == np.float64
  209. results = converting_constructors([1, 2, 3])
  210. for a in results.values():
  211. np.testing.assert_array_equal(a, [1, 2, 3])
  212. assert results["array"].dtype == np.int_
  213. assert results["array_t<int32>"].dtype == np.int32
  214. assert results["array_t<double>"].dtype == np.float64
  215. def test_overload_resolution(msg):
  216. from pybind11_tests.array import overloaded, overloaded2, overloaded3, overloaded4, overloaded5
  217. # Exact overload matches:
  218. assert overloaded(np.array([1], dtype='float64')) == 'double'
  219. assert overloaded(np.array([1], dtype='float32')) == 'float'
  220. assert overloaded(np.array([1], dtype='ushort')) == 'unsigned short'
  221. assert overloaded(np.array([1], dtype='intc')) == 'int'
  222. assert overloaded(np.array([1], dtype='longlong')) == 'long long'
  223. assert overloaded(np.array([1], dtype='complex')) == 'double complex'
  224. assert overloaded(np.array([1], dtype='csingle')) == 'float complex'
  225. # No exact match, should call first convertible version:
  226. assert overloaded(np.array([1], dtype='uint8')) == 'double'
  227. with pytest.raises(TypeError) as excinfo:
  228. overloaded("not an array")
  229. assert msg(excinfo.value) == """
  230. overloaded(): incompatible function arguments. The following argument types are supported:
  231. 1. (arg0: numpy.ndarray[float64]) -> str
  232. 2. (arg0: numpy.ndarray[float32]) -> str
  233. 3. (arg0: numpy.ndarray[int32]) -> str
  234. 4. (arg0: numpy.ndarray[uint16]) -> str
  235. 5. (arg0: numpy.ndarray[int64]) -> str
  236. 6. (arg0: numpy.ndarray[complex128]) -> str
  237. 7. (arg0: numpy.ndarray[complex64]) -> str
  238. Invoked with: 'not an array'
  239. """
  240. assert overloaded2(np.array([1], dtype='float64')) == 'double'
  241. assert overloaded2(np.array([1], dtype='float32')) == 'float'
  242. assert overloaded2(np.array([1], dtype='complex64')) == 'float complex'
  243. assert overloaded2(np.array([1], dtype='complex128')) == 'double complex'
  244. assert overloaded2(np.array([1], dtype='float32')) == 'float'
  245. assert overloaded3(np.array([1], dtype='float64')) == 'double'
  246. assert overloaded3(np.array([1], dtype='intc')) == 'int'
  247. expected_exc = """
  248. overloaded3(): incompatible function arguments. The following argument types are supported:
  249. 1. (arg0: numpy.ndarray[int32]) -> str
  250. 2. (arg0: numpy.ndarray[float64]) -> str
  251. Invoked with:"""
  252. with pytest.raises(TypeError) as excinfo:
  253. overloaded3(np.array([1], dtype='uintc'))
  254. assert msg(excinfo.value) == expected_exc + " array([1], dtype=uint32)"
  255. with pytest.raises(TypeError) as excinfo:
  256. overloaded3(np.array([1], dtype='float32'))
  257. assert msg(excinfo.value) == expected_exc + " array([ 1.], dtype=float32)"
  258. with pytest.raises(TypeError) as excinfo:
  259. overloaded3(np.array([1], dtype='complex'))
  260. assert msg(excinfo.value) == expected_exc + " array([ 1.+0.j])"
  261. # Exact matches:
  262. assert overloaded4(np.array([1], dtype='double')) == 'double'
  263. assert overloaded4(np.array([1], dtype='longlong')) == 'long long'
  264. # Non-exact matches requiring conversion. Since float to integer isn't a
  265. # save conversion, it should go to the double overload, but short can go to
  266. # either (and so should end up on the first-registered, the long long).
  267. assert overloaded4(np.array([1], dtype='float32')) == 'double'
  268. assert overloaded4(np.array([1], dtype='short')) == 'long long'
  269. assert overloaded5(np.array([1], dtype='double')) == 'double'
  270. assert overloaded5(np.array([1], dtype='uintc')) == 'unsigned int'
  271. assert overloaded5(np.array([1], dtype='float32')) == 'unsigned int'
  272. def test_greedy_string_overload(): # issue 685
  273. from pybind11_tests.array import issue685
  274. assert issue685("abc") == "string"
  275. assert issue685(np.array([97, 98, 99], dtype='b')) == "array"
  276. assert issue685(123) == "other"
  277. def test_array_unchecked_fixed_dims(msg):
  278. from pybind11_tests.array import (proxy_add2, proxy_init3F, proxy_init3, proxy_squared_L2_norm,
  279. proxy_auxiliaries2, array_auxiliaries2)
  280. z1 = np.array([[1, 2], [3, 4]], dtype='float64')
  281. proxy_add2(z1, 10)
  282. assert np.all(z1 == [[11, 12], [13, 14]])
  283. with pytest.raises(ValueError) as excinfo:
  284. proxy_add2(np.array([1., 2, 3]), 5.0)
  285. assert msg(excinfo.value) == "array has incorrect number of dimensions: 1; expected 2"
  286. expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype='int')
  287. assert np.all(proxy_init3(3.0) == expect_c)
  288. expect_f = np.transpose(expect_c)
  289. assert np.all(proxy_init3F(3.0) == expect_f)
  290. assert proxy_squared_L2_norm(np.array(range(6))) == 55
  291. assert proxy_squared_L2_norm(np.array(range(6), dtype="float64")) == 55
  292. assert proxy_auxiliaries2(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
  293. assert proxy_auxiliaries2(z1) == array_auxiliaries2(z1)
  294. def test_array_unchecked_dyn_dims(msg):
  295. from pybind11_tests.array import (proxy_add2_dyn, proxy_init3_dyn, proxy_auxiliaries2_dyn,
  296. array_auxiliaries2)
  297. z1 = np.array([[1, 2], [3, 4]], dtype='float64')
  298. proxy_add2_dyn(z1, 10)
  299. assert np.all(z1 == [[11, 12], [13, 14]])
  300. expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype='int')
  301. assert np.all(proxy_init3_dyn(3.0) == expect_c)
  302. assert proxy_auxiliaries2_dyn(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32]
  303. assert proxy_auxiliaries2_dyn(z1) == array_auxiliaries2(z1)