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.

626 lines
24 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
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_eigen_and_numpy
  3. with pytest.suppress(ImportError):
  4. import numpy as np
  5. ref = np.array([[ 0., 3, 0, 0, 0, 11],
  6. [22, 0, 0, 0, 17, 11],
  7. [ 7, 5, 0, 1, 0, 11],
  8. [ 0, 0, 0, 0, 0, 11],
  9. [ 0, 0, 14, 0, 8, 11]])
  10. def assert_equal_ref(mat):
  11. np.testing.assert_array_equal(mat, ref)
  12. def assert_sparse_equal_ref(sparse_mat):
  13. assert_equal_ref(sparse_mat.todense())
  14. def test_fixed():
  15. from pybind11_tests import fixed_r, fixed_c, fixed_copy_r, fixed_copy_c
  16. assert_equal_ref(fixed_c())
  17. assert_equal_ref(fixed_r())
  18. assert_equal_ref(fixed_copy_r(fixed_r()))
  19. assert_equal_ref(fixed_copy_c(fixed_c()))
  20. assert_equal_ref(fixed_copy_r(fixed_c()))
  21. assert_equal_ref(fixed_copy_c(fixed_r()))
  22. def test_dense():
  23. from pybind11_tests import dense_r, dense_c, dense_copy_r, dense_copy_c
  24. assert_equal_ref(dense_r())
  25. assert_equal_ref(dense_c())
  26. assert_equal_ref(dense_copy_r(dense_r()))
  27. assert_equal_ref(dense_copy_c(dense_c()))
  28. assert_equal_ref(dense_copy_r(dense_c()))
  29. assert_equal_ref(dense_copy_c(dense_r()))
  30. def test_partially_fixed():
  31. from pybind11_tests import (partial_copy_four_rm_r, partial_copy_four_rm_c,
  32. partial_copy_four_cm_r, partial_copy_four_cm_c)
  33. ref2 = np.array([[0., 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
  34. np.testing.assert_array_equal(partial_copy_four_rm_r(ref2), ref2)
  35. np.testing.assert_array_equal(partial_copy_four_rm_c(ref2), ref2)
  36. np.testing.assert_array_equal(partial_copy_four_rm_r(ref2[:, 1]), ref2[:, [1]])
  37. np.testing.assert_array_equal(partial_copy_four_rm_c(ref2[0, :]), ref2[[0], :])
  38. np.testing.assert_array_equal(partial_copy_four_rm_r(ref2[:, (0, 2)]), ref2[:, (0, 2)])
  39. np.testing.assert_array_equal(
  40. partial_copy_four_rm_c(ref2[(3, 1, 2), :]), ref2[(3, 1, 2), :])
  41. np.testing.assert_array_equal(partial_copy_four_cm_r(ref2), ref2)
  42. np.testing.assert_array_equal(partial_copy_four_cm_c(ref2), ref2)
  43. np.testing.assert_array_equal(partial_copy_four_cm_r(ref2[:, 1]), ref2[:, [1]])
  44. np.testing.assert_array_equal(partial_copy_four_cm_c(ref2[0, :]), ref2[[0], :])
  45. np.testing.assert_array_equal(partial_copy_four_cm_r(ref2[:, (0, 2)]), ref2[:, (0, 2)])
  46. np.testing.assert_array_equal(
  47. partial_copy_four_cm_c(ref2[(3, 1, 2), :]), ref2[(3, 1, 2), :])
  48. def test_mutator_descriptors():
  49. from pybind11_tests import fixed_mutator_r, fixed_mutator_c, fixed_mutator_a
  50. zr = np.arange(30, dtype='float32').reshape(5, 6) # row-major
  51. zc = zr.reshape(6, 5).transpose() # column-major
  52. fixed_mutator_r(zr)
  53. fixed_mutator_c(zc)
  54. fixed_mutator_a(zr)
  55. fixed_mutator_a(zc)
  56. with pytest.raises(TypeError) as excinfo:
  57. fixed_mutator_r(zc)
  58. assert ('(numpy.ndarray[float32[5, 6], flags.writeable, flags.c_contiguous]) -> arg0: None'
  59. in str(excinfo.value))
  60. with pytest.raises(TypeError) as excinfo:
  61. fixed_mutator_c(zr)
  62. assert ('(numpy.ndarray[float32[5, 6], flags.writeable, flags.f_contiguous]) -> arg0: None'
  63. in str(excinfo.value))
  64. with pytest.raises(TypeError) as excinfo:
  65. fixed_mutator_a(np.array([[1, 2], [3, 4]], dtype='float32'))
  66. assert ('(numpy.ndarray[float32[5, 6], flags.writeable]) -> arg0: None'
  67. in str(excinfo.value))
  68. zr.flags.writeable = False
  69. with pytest.raises(TypeError):
  70. fixed_mutator_r(zr)
  71. with pytest.raises(TypeError):
  72. fixed_mutator_a(zr)
  73. def test_cpp_casting():
  74. from pybind11_tests import (cpp_copy, cpp_ref_c, cpp_ref_r, cpp_ref_any,
  75. fixed_r, fixed_c, get_cm_ref, get_rm_ref, ReturnTester)
  76. assert cpp_copy(fixed_r()) == 22.
  77. assert cpp_copy(fixed_c()) == 22.
  78. z = np.array([[5., 6], [7, 8]])
  79. assert cpp_copy(z) == 7.
  80. assert cpp_copy(get_cm_ref()) == 21.
  81. assert cpp_copy(get_rm_ref()) == 21.
  82. assert cpp_ref_c(get_cm_ref()) == 21.
  83. assert cpp_ref_r(get_rm_ref()) == 21.
  84. with pytest.raises(RuntimeError) as excinfo:
  85. # Can't reference fixed_c: it contains floats, cpp_ref_any wants doubles
  86. cpp_ref_any(fixed_c())
  87. assert 'Unable to cast Python instance' in str(excinfo.value)
  88. with pytest.raises(RuntimeError) as excinfo:
  89. # Can't reference fixed_r: it contains floats, cpp_ref_any wants doubles
  90. cpp_ref_any(fixed_r())
  91. assert 'Unable to cast Python instance' in str(excinfo.value)
  92. assert cpp_ref_any(ReturnTester.create()) == 1.
  93. assert cpp_ref_any(get_cm_ref()) == 21.
  94. assert cpp_ref_any(get_cm_ref()) == 21.
  95. def test_pass_readonly_array():
  96. from pybind11_tests import fixed_copy_r, fixed_r, fixed_r_const
  97. z = np.full((5, 6), 42.0)
  98. z.flags.writeable = False
  99. np.testing.assert_array_equal(z, fixed_copy_r(z))
  100. np.testing.assert_array_equal(fixed_r_const(), fixed_r())
  101. assert not fixed_r_const().flags.writeable
  102. np.testing.assert_array_equal(fixed_copy_r(fixed_r_const()), fixed_r_const())
  103. def test_nonunit_stride_from_python():
  104. from pybind11_tests import (
  105. double_row, double_col, double_complex, double_mat_cm, double_mat_rm,
  106. double_threec, double_threer)
  107. counting_mat = np.arange(9.0, dtype=np.float32).reshape((3, 3))
  108. second_row = counting_mat[1, :]
  109. second_col = counting_mat[:, 1]
  110. np.testing.assert_array_equal(double_row(second_row), 2.0 * second_row)
  111. np.testing.assert_array_equal(double_col(second_row), 2.0 * second_row)
  112. np.testing.assert_array_equal(double_complex(second_row), 2.0 * second_row)
  113. np.testing.assert_array_equal(double_row(second_col), 2.0 * second_col)
  114. np.testing.assert_array_equal(double_col(second_col), 2.0 * second_col)
  115. np.testing.assert_array_equal(double_complex(second_col), 2.0 * second_col)
  116. counting_3d = np.arange(27.0, dtype=np.float32).reshape((3, 3, 3))
  117. slices = [counting_3d[0, :, :], counting_3d[:, 0, :], counting_3d[:, :, 0]]
  118. for slice_idx, ref_mat in enumerate(slices):
  119. np.testing.assert_array_equal(double_mat_cm(ref_mat), 2.0 * ref_mat)
  120. np.testing.assert_array_equal(double_mat_rm(ref_mat), 2.0 * ref_mat)
  121. # Mutator:
  122. double_threer(second_row)
  123. double_threec(second_col)
  124. np.testing.assert_array_equal(counting_mat, [[0., 2, 2], [6, 16, 10], [6, 14, 8]])
  125. def test_nonunit_stride_to_python():
  126. from pybind11_tests import diagonal, diagonal_1, diagonal_n, block
  127. assert np.all(diagonal(ref) == ref.diagonal())
  128. assert np.all(diagonal_1(ref) == ref.diagonal(1))
  129. for i in range(-5, 7):
  130. assert np.all(diagonal_n(ref, i) == ref.diagonal(i)), "diagonal_n({})".format(i)
  131. assert np.all(block(ref, 2, 1, 3, 3) == ref[2:5, 1:4])
  132. assert np.all(block(ref, 1, 4, 4, 2) == ref[1:, 4:])
  133. assert np.all(block(ref, 1, 4, 3, 2) == ref[1:4, 4:])
  134. def test_eigen_ref_to_python():
  135. from pybind11_tests import cholesky1, cholesky2, cholesky3, cholesky4
  136. chols = [cholesky1, cholesky2, cholesky3, cholesky4]
  137. for i, chol in enumerate(chols, start=1):
  138. mymat = chol(np.array([[1., 2, 4], [2, 13, 23], [4, 23, 77]]))
  139. assert np.all(mymat == np.array([[1, 0, 0], [2, 3, 0], [4, 5, 6]])), "cholesky{}".format(i)
  140. def assign_both(a1, a2, r, c, v):
  141. a1[r, c] = v
  142. a2[r, c] = v
  143. def array_copy_but_one(a, r, c, v):
  144. z = np.array(a, copy=True)
  145. z[r, c] = v
  146. return z
  147. def test_eigen_return_references():
  148. """Tests various ways of returning references and non-referencing copies"""
  149. from pybind11_tests import ReturnTester
  150. master = np.ones((10, 10))
  151. a = ReturnTester()
  152. a_get1 = a.get()
  153. assert not a_get1.flags.owndata and a_get1.flags.writeable
  154. assign_both(a_get1, master, 3, 3, 5)
  155. a_get2 = a.get_ptr()
  156. assert not a_get2.flags.owndata and a_get2.flags.writeable
  157. assign_both(a_get1, master, 2, 3, 6)
  158. a_view1 = a.view()
  159. assert not a_view1.flags.owndata and not a_view1.flags.writeable
  160. with pytest.raises(ValueError):
  161. a_view1[2, 3] = 4
  162. a_view2 = a.view_ptr()
  163. assert not a_view2.flags.owndata and not a_view2.flags.writeable
  164. with pytest.raises(ValueError):
  165. a_view2[2, 3] = 4
  166. a_copy1 = a.copy_get()
  167. assert a_copy1.flags.owndata and a_copy1.flags.writeable
  168. np.testing.assert_array_equal(a_copy1, master)
  169. a_copy1[7, 7] = -44 # Shouldn't affect anything else
  170. c1want = array_copy_but_one(master, 7, 7, -44)
  171. a_copy2 = a.copy_view()
  172. assert a_copy2.flags.owndata and a_copy2.flags.writeable
  173. np.testing.assert_array_equal(a_copy2, master)
  174. a_copy2[4, 4] = -22 # Shouldn't affect anything else
  175. c2want = array_copy_but_one(master, 4, 4, -22)
  176. a_ref1 = a.ref()
  177. assert not a_ref1.flags.owndata and a_ref1.flags.writeable
  178. assign_both(a_ref1, master, 1, 1, 15)
  179. a_ref2 = a.ref_const()
  180. assert not a_ref2.flags.owndata and not a_ref2.flags.writeable
  181. with pytest.raises(ValueError):
  182. a_ref2[5, 5] = 33
  183. a_ref3 = a.ref_safe()
  184. assert not a_ref3.flags.owndata and a_ref3.flags.writeable
  185. assign_both(a_ref3, master, 0, 7, 99)
  186. a_ref4 = a.ref_const_safe()
  187. assert not a_ref4.flags.owndata and not a_ref4.flags.writeable
  188. with pytest.raises(ValueError):
  189. a_ref4[7, 0] = 987654321
  190. a_copy3 = a.copy_ref()
  191. assert a_copy3.flags.owndata and a_copy3.flags.writeable
  192. np.testing.assert_array_equal(a_copy3, master)
  193. a_copy3[8, 1] = 11
  194. c3want = array_copy_but_one(master, 8, 1, 11)
  195. a_copy4 = a.copy_ref_const()
  196. assert a_copy4.flags.owndata and a_copy4.flags.writeable
  197. np.testing.assert_array_equal(a_copy4, master)
  198. a_copy4[8, 4] = 88
  199. c4want = array_copy_but_one(master, 8, 4, 88)
  200. a_block1 = a.block(3, 3, 2, 2)
  201. assert not a_block1.flags.owndata and a_block1.flags.writeable
  202. a_block1[0, 0] = 55
  203. master[3, 3] = 55
  204. a_block2 = a.block_safe(2, 2, 3, 2)
  205. assert not a_block2.flags.owndata and a_block2.flags.writeable
  206. a_block2[2, 1] = -123
  207. master[4, 3] = -123
  208. a_block3 = a.block_const(6, 7, 4, 3)
  209. assert not a_block3.flags.owndata and not a_block3.flags.writeable
  210. with pytest.raises(ValueError):
  211. a_block3[2, 2] = -44444
  212. a_copy5 = a.copy_block(2, 2, 2, 3)
  213. assert a_copy5.flags.owndata and a_copy5.flags.writeable
  214. np.testing.assert_array_equal(a_copy5, master[2:4, 2:5])
  215. a_copy5[1, 1] = 777
  216. c5want = array_copy_but_one(master[2:4, 2:5], 1, 1, 777)
  217. a_corn1 = a.corners()
  218. assert not a_corn1.flags.owndata and a_corn1.flags.writeable
  219. a_corn1 *= 50
  220. a_corn1[1, 1] = 999
  221. master[0, 0] = 50
  222. master[0, 9] = 50
  223. master[9, 0] = 50
  224. master[9, 9] = 999
  225. a_corn2 = a.corners_const()
  226. assert not a_corn2.flags.owndata and not a_corn2.flags.writeable
  227. with pytest.raises(ValueError):
  228. a_corn2[1, 0] = 51
  229. # All of the changes made all the way along should be visible everywhere
  230. # now (except for the copies, of course)
  231. np.testing.assert_array_equal(a_get1, master)
  232. np.testing.assert_array_equal(a_get2, master)
  233. np.testing.assert_array_equal(a_view1, master)
  234. np.testing.assert_array_equal(a_view2, master)
  235. np.testing.assert_array_equal(a_ref1, master)
  236. np.testing.assert_array_equal(a_ref2, master)
  237. np.testing.assert_array_equal(a_ref3, master)
  238. np.testing.assert_array_equal(a_ref4, master)
  239. np.testing.assert_array_equal(a_block1, master[3:5, 3:5])
  240. np.testing.assert_array_equal(a_block2, master[2:5, 2:4])
  241. np.testing.assert_array_equal(a_block3, master[6:10, 7:10])
  242. np.testing.assert_array_equal(a_corn1, master[0::master.shape[0] - 1, 0::master.shape[1] - 1])
  243. np.testing.assert_array_equal(a_corn2, master[0::master.shape[0] - 1, 0::master.shape[1] - 1])
  244. np.testing.assert_array_equal(a_copy1, c1want)
  245. np.testing.assert_array_equal(a_copy2, c2want)
  246. np.testing.assert_array_equal(a_copy3, c3want)
  247. np.testing.assert_array_equal(a_copy4, c4want)
  248. np.testing.assert_array_equal(a_copy5, c5want)
  249. def assert_keeps_alive(cl, method, *args):
  250. from pybind11_tests import ConstructorStats
  251. cstats = ConstructorStats.get(cl)
  252. start_with = cstats.alive()
  253. a = cl()
  254. assert cstats.alive() == start_with + 1
  255. z = method(a, *args)
  256. assert cstats.alive() == start_with + 1
  257. del a
  258. # Here's the keep alive in action:
  259. assert cstats.alive() == start_with + 1
  260. del z
  261. # Keep alive should have expired:
  262. assert cstats.alive() == start_with
  263. def test_eigen_keepalive():
  264. from pybind11_tests import ReturnTester, ConstructorStats
  265. a = ReturnTester()
  266. cstats = ConstructorStats.get(ReturnTester)
  267. assert cstats.alive() == 1
  268. unsafe = [a.ref(), a.ref_const(), a.block(1, 2, 3, 4)]
  269. copies = [a.copy_get(), a.copy_view(), a.copy_ref(), a.copy_ref_const(),
  270. a.copy_block(4, 3, 2, 1)]
  271. del a
  272. assert cstats.alive() == 0
  273. del unsafe
  274. del copies
  275. for meth in [ReturnTester.get, ReturnTester.get_ptr, ReturnTester.view,
  276. ReturnTester.view_ptr, ReturnTester.ref_safe, ReturnTester.ref_const_safe,
  277. ReturnTester.corners, ReturnTester.corners_const]:
  278. assert_keeps_alive(ReturnTester, meth)
  279. for meth in [ReturnTester.block_safe, ReturnTester.block_const]:
  280. assert_keeps_alive(ReturnTester, meth, 4, 3, 2, 1)
  281. def test_eigen_ref_mutators():
  282. """Tests whether Eigen can mutate numpy values"""
  283. from pybind11_tests import add_rm, add_cm, add_any, add1, add2
  284. orig = np.array([[1., 2, 3], [4, 5, 6], [7, 8, 9]])
  285. zr = np.array(orig)
  286. zc = np.array(orig, order='F')
  287. add_rm(zr, 1, 0, 100)
  288. assert np.all(zr == np.array([[1., 2, 3], [104, 5, 6], [7, 8, 9]]))
  289. add_cm(zc, 1, 0, 200)
  290. assert np.all(zc == np.array([[1., 2, 3], [204, 5, 6], [7, 8, 9]]))
  291. add_any(zr, 1, 0, 20)
  292. assert np.all(zr == np.array([[1., 2, 3], [124, 5, 6], [7, 8, 9]]))
  293. add_any(zc, 1, 0, 10)
  294. assert np.all(zc == np.array([[1., 2, 3], [214, 5, 6], [7, 8, 9]]))
  295. # Can't reference a col-major array with a row-major Ref, and vice versa:
  296. with pytest.raises(TypeError):
  297. add_rm(zc, 1, 0, 1)
  298. with pytest.raises(TypeError):
  299. add_cm(zr, 1, 0, 1)
  300. # Overloads:
  301. add1(zr, 1, 0, -100)
  302. add2(zr, 1, 0, -20)
  303. assert np.all(zr == orig)
  304. add1(zc, 1, 0, -200)
  305. add2(zc, 1, 0, -10)
  306. assert np.all(zc == orig)
  307. # a non-contiguous slice (this won't work on either the row- or
  308. # column-contiguous refs, but should work for the any)
  309. cornersr = zr[0::2, 0::2]
  310. cornersc = zc[0::2, 0::2]
  311. assert np.all(cornersr == np.array([[1., 3], [7, 9]]))
  312. assert np.all(cornersc == np.array([[1., 3], [7, 9]]))
  313. with pytest.raises(TypeError):
  314. add_rm(cornersr, 0, 1, 25)
  315. with pytest.raises(TypeError):
  316. add_cm(cornersr, 0, 1, 25)
  317. with pytest.raises(TypeError):
  318. add_rm(cornersc, 0, 1, 25)
  319. with pytest.raises(TypeError):
  320. add_cm(cornersc, 0, 1, 25)
  321. add_any(cornersr, 0, 1, 25)
  322. add_any(cornersc, 0, 1, 44)
  323. assert np.all(zr == np.array([[1., 2, 28], [4, 5, 6], [7, 8, 9]]))
  324. assert np.all(zc == np.array([[1., 2, 47], [4, 5, 6], [7, 8, 9]]))
  325. # You shouldn't be allowed to pass a non-writeable array to a mutating Eigen method:
  326. zro = zr[0:4, 0:4]
  327. zro.flags.writeable = False
  328. with pytest.raises(TypeError):
  329. add_rm(zro, 0, 0, 0)
  330. with pytest.raises(TypeError):
  331. add_any(zro, 0, 0, 0)
  332. with pytest.raises(TypeError):
  333. add1(zro, 0, 0, 0)
  334. with pytest.raises(TypeError):
  335. add2(zro, 0, 0, 0)
  336. # integer array shouldn't be passable to a double-matrix-accepting mutating func:
  337. zi = np.array([[1, 2], [3, 4]])
  338. with pytest.raises(TypeError):
  339. add_rm(zi)
  340. def test_numpy_ref_mutators():
  341. """Tests numpy mutating Eigen matrices (for returned Eigen::Ref<...>s)"""
  342. from pybind11_tests import (
  343. get_cm_ref, get_cm_const_ref, get_rm_ref, get_rm_const_ref, reset_refs)
  344. reset_refs() # In case another test already changed it
  345. zc = get_cm_ref()
  346. zcro = get_cm_const_ref()
  347. zr = get_rm_ref()
  348. zrro = get_rm_const_ref()
  349. assert [zc[1, 2], zcro[1, 2], zr[1, 2], zrro[1, 2]] == [23] * 4
  350. assert not zc.flags.owndata and zc.flags.writeable
  351. assert not zr.flags.owndata and zr.flags.writeable
  352. assert not zcro.flags.owndata and not zcro.flags.writeable
  353. assert not zrro.flags.owndata and not zrro.flags.writeable
  354. zc[1, 2] = 99
  355. expect = np.array([[11., 12, 13], [21, 22, 99], [31, 32, 33]])
  356. # We should have just changed zc, of course, but also zcro and the original eigen matrix
  357. assert np.all(zc == expect)
  358. assert np.all(zcro == expect)
  359. assert np.all(get_cm_ref() == expect)
  360. zr[1, 2] = 99
  361. assert np.all(zr == expect)
  362. assert np.all(zrro == expect)
  363. assert np.all(get_rm_ref() == expect)
  364. # Make sure the readonly ones are numpy-readonly:
  365. with pytest.raises(ValueError):
  366. zcro[1, 2] = 6
  367. with pytest.raises(ValueError):
  368. zrro[1, 2] = 6
  369. # We should be able to explicitly copy like this (and since we're copying,
  370. # the const should drop away)
  371. y1 = np.array(get_cm_const_ref())
  372. assert y1.flags.owndata and y1.flags.writeable
  373. # We should get copies of the eigen data, which was modified above:
  374. assert y1[1, 2] == 99
  375. y1[1, 2] += 12
  376. assert y1[1, 2] == 111
  377. assert zc[1, 2] == 99 # Make sure we aren't referencing the original
  378. def test_both_ref_mutators():
  379. """Tests a complex chain of nested eigen/numpy references"""
  380. from pybind11_tests import (
  381. incr_matrix, get_cm_ref, incr_matrix_any, even_cols, even_rows, reset_refs)
  382. reset_refs() # In case another test already changed it
  383. z = get_cm_ref() # numpy -> eigen
  384. z[0, 2] -= 3
  385. z2 = incr_matrix(z, 1) # numpy -> eigen -> numpy -> eigen
  386. z2[1, 1] += 6
  387. z3 = incr_matrix(z, 2) # (numpy -> eigen)^3
  388. z3[2, 2] += -5
  389. z4 = incr_matrix(z, 3) # (numpy -> eigen)^4
  390. z4[1, 1] -= 1
  391. z5 = incr_matrix(z, 4) # (numpy -> eigen)^5
  392. z5[0, 0] = 0
  393. assert np.all(z == z2)
  394. assert np.all(z == z3)
  395. assert np.all(z == z4)
  396. assert np.all(z == z5)
  397. expect = np.array([[0., 22, 20], [31, 37, 33], [41, 42, 38]])
  398. assert np.all(z == expect)
  399. y = np.array(range(100), dtype='float64').reshape(10, 10)
  400. y2 = incr_matrix_any(y, 10) # np -> eigen -> np
  401. y3 = incr_matrix_any(y2[0::2, 0::2], -33) # np -> eigen -> np slice -> np -> eigen -> np
  402. y4 = even_rows(y3) # numpy -> eigen slice -> (... y3)
  403. y5 = even_cols(y4) # numpy -> eigen slice -> (... y4)
  404. y6 = incr_matrix_any(y5, 1000) # numpy -> eigen -> (... y5)
  405. # Apply same mutations using just numpy:
  406. yexpect = np.array(range(100), dtype='float64').reshape(10, 10)
  407. yexpect += 10
  408. yexpect[0::2, 0::2] -= 33
  409. yexpect[0::4, 0::4] += 1000
  410. assert np.all(y6 == yexpect[0::4, 0::4])
  411. assert np.all(y5 == yexpect[0::4, 0::4])
  412. assert np.all(y4 == yexpect[0::4, 0::2])
  413. assert np.all(y3 == yexpect[0::2, 0::2])
  414. assert np.all(y2 == yexpect)
  415. assert np.all(y == yexpect)
  416. def test_nocopy_wrapper():
  417. from pybind11_tests import get_elem, get_elem_nocopy, get_elem_rm_nocopy
  418. # get_elem requires a column-contiguous matrix reference, but should be
  419. # callable with other types of matrix (via copying):
  420. int_matrix_colmajor = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], order='F')
  421. dbl_matrix_colmajor = np.array(int_matrix_colmajor, dtype='double', order='F', copy=True)
  422. int_matrix_rowmajor = np.array(int_matrix_colmajor, order='C', copy=True)
  423. dbl_matrix_rowmajor = np.array(int_matrix_rowmajor, dtype='double', order='C', copy=True)
  424. # All should be callable via get_elem:
  425. assert get_elem(int_matrix_colmajor) == 8
  426. assert get_elem(dbl_matrix_colmajor) == 8
  427. assert get_elem(int_matrix_rowmajor) == 8
  428. assert get_elem(dbl_matrix_rowmajor) == 8
  429. # All but the second should fail with get_elem_nocopy:
  430. with pytest.raises(TypeError) as excinfo:
  431. get_elem_nocopy(int_matrix_colmajor)
  432. assert ('get_elem_nocopy(): incompatible function arguments.' in str(excinfo.value) and
  433. ', flags.f_contiguous' in str(excinfo.value))
  434. assert get_elem_nocopy(dbl_matrix_colmajor) == 8
  435. with pytest.raises(TypeError) as excinfo:
  436. get_elem_nocopy(int_matrix_rowmajor)
  437. assert ('get_elem_nocopy(): incompatible function arguments.' in str(excinfo.value) and
  438. ', flags.f_contiguous' in str(excinfo.value))
  439. with pytest.raises(TypeError) as excinfo:
  440. get_elem_nocopy(dbl_matrix_rowmajor)
  441. assert ('get_elem_nocopy(): incompatible function arguments.' in str(excinfo.value) and
  442. ', flags.f_contiguous' in str(excinfo.value))
  443. # For the row-major test, we take a long matrix in row-major, so only the third is allowed:
  444. with pytest.raises(TypeError) as excinfo:
  445. get_elem_rm_nocopy(int_matrix_colmajor)
  446. assert ('get_elem_rm_nocopy(): incompatible function arguments.' in str(excinfo.value) and
  447. ', flags.c_contiguous' in str(excinfo.value))
  448. with pytest.raises(TypeError) as excinfo:
  449. get_elem_rm_nocopy(dbl_matrix_colmajor)
  450. assert ('get_elem_rm_nocopy(): incompatible function arguments.' in str(excinfo.value) and
  451. ', flags.c_contiguous' in str(excinfo.value))
  452. assert get_elem_rm_nocopy(int_matrix_rowmajor) == 8
  453. with pytest.raises(TypeError) as excinfo:
  454. get_elem_rm_nocopy(dbl_matrix_rowmajor)
  455. assert ('get_elem_rm_nocopy(): incompatible function arguments.' in str(excinfo.value) and
  456. ', flags.c_contiguous' in str(excinfo.value))
  457. def test_special_matrix_objects():
  458. from pybind11_tests import incr_diag, symmetric_upper, symmetric_lower
  459. assert np.all(incr_diag(7) == np.diag([1., 2, 3, 4, 5, 6, 7]))
  460. asymm = np.array([[ 1., 2, 3, 4],
  461. [ 5, 6, 7, 8],
  462. [ 9, 10, 11, 12],
  463. [13, 14, 15, 16]])
  464. symm_lower = np.array(asymm)
  465. symm_upper = np.array(asymm)
  466. for i in range(4):
  467. for j in range(i + 1, 4):
  468. symm_lower[i, j] = symm_lower[j, i]
  469. symm_upper[j, i] = symm_upper[i, j]
  470. assert np.all(symmetric_lower(asymm) == symm_lower)
  471. assert np.all(symmetric_upper(asymm) == symm_upper)
  472. def test_dense_signature(doc):
  473. from pybind11_tests import double_col, double_row, double_complex, double_mat_rm
  474. assert doc(double_col) == """
  475. double_col(arg0: numpy.ndarray[float32[m, 1]]) -> numpy.ndarray[float32[m, 1]]
  476. """
  477. assert doc(double_row) == """
  478. double_row(arg0: numpy.ndarray[float32[1, n]]) -> numpy.ndarray[float32[1, n]]
  479. """
  480. assert doc(double_complex) == """
  481. double_complex(arg0: numpy.ndarray[complex64[m, 1]]) -> numpy.ndarray[complex64[m, 1]]
  482. """
  483. assert doc(double_mat_rm) == """
  484. double_mat_rm(arg0: numpy.ndarray[float32[m, n]]) -> numpy.ndarray[float32[m, n]]
  485. """
  486. @pytest.requires_eigen_and_scipy
  487. def test_sparse():
  488. from pybind11_tests import sparse_r, sparse_c, sparse_copy_r, sparse_copy_c
  489. assert_sparse_equal_ref(sparse_r())
  490. assert_sparse_equal_ref(sparse_c())
  491. assert_sparse_equal_ref(sparse_copy_r(sparse_r()))
  492. assert_sparse_equal_ref(sparse_copy_c(sparse_c()))
  493. assert_sparse_equal_ref(sparse_copy_r(sparse_c()))
  494. assert_sparse_equal_ref(sparse_copy_c(sparse_r()))
  495. @pytest.requires_eigen_and_scipy
  496. def test_sparse_signature(doc):
  497. from pybind11_tests import sparse_copy_r, sparse_copy_c
  498. assert doc(sparse_copy_r) == """
  499. sparse_copy_r(arg0: scipy.sparse.csr_matrix[float32]) -> scipy.sparse.csr_matrix[float32]
  500. """ # noqa: E501 line too long
  501. assert doc(sparse_copy_c) == """
  502. sparse_copy_c(arg0: scipy.sparse.csc_matrix[float32]) -> scipy.sparse.csc_matrix[float32]
  503. """ # noqa: E501 line too long
  504. def test_issue738():
  505. from pybind11_tests import iss738_f1, iss738_f2
  506. assert np.all(iss738_f1(np.array([[1., 2, 3]])) == np.array([[1., 102, 203]]))
  507. assert np.all(iss738_f1(np.array([[1.], [2], [3]])) == np.array([[1.], [12], [23]]))
  508. assert np.all(iss738_f2(np.array([[1., 2, 3]])) == np.array([[1., 102, 203]]))
  509. assert np.all(iss738_f2(np.array([[1.], [2], [3]])) == np.array([[1.], [12], [23]]))
  510. def test_custom_operator_new():
  511. """Using Eigen types as member variables requires a class-specific
  512. operator new with proper alignment"""
  513. from pybind11_tests import CustomOperatorNew
  514. o = CustomOperatorNew()
  515. np.testing.assert_allclose(o.a, 0.0)
  516. np.testing.assert_allclose(o.b.diagonal(), 1.0)