test_eigen.py 28 KB

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