test_eigen.py 27 KB

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