The source code and dockerfile for the GSW2024 AI Lab.
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

721 lines
28 KiB

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