File indexing completed on 2025-01-18 10:17:53
0001 import pytest
0002
0003 from pybind11_tests import ConstructorStats
0004
0005 np = pytest.importorskip("numpy")
0006 m = pytest.importorskip("pybind11_tests.eigen_matrix")
0007
0008
0009 ref = np.array(
0010 [
0011 [0.0, 3, 0, 0, 0, 11],
0012 [22, 0, 0, 0, 17, 11],
0013 [7, 5, 0, 1, 0, 11],
0014 [0, 0, 0, 0, 0, 11],
0015 [0, 0, 14, 0, 8, 11],
0016 ]
0017 )
0018
0019
0020 def assert_equal_ref(mat):
0021 np.testing.assert_array_equal(mat, ref)
0022
0023
0024 def assert_sparse_equal_ref(sparse_mat):
0025 assert_equal_ref(sparse_mat.toarray())
0026
0027
0028 def test_fixed():
0029 assert_equal_ref(m.fixed_c())
0030 assert_equal_ref(m.fixed_r())
0031 assert_equal_ref(m.fixed_copy_r(m.fixed_r()))
0032 assert_equal_ref(m.fixed_copy_c(m.fixed_c()))
0033 assert_equal_ref(m.fixed_copy_r(m.fixed_c()))
0034 assert_equal_ref(m.fixed_copy_c(m.fixed_r()))
0035
0036
0037 def test_dense():
0038 assert_equal_ref(m.dense_r())
0039 assert_equal_ref(m.dense_c())
0040 assert_equal_ref(m.dense_copy_r(m.dense_r()))
0041 assert_equal_ref(m.dense_copy_c(m.dense_c()))
0042 assert_equal_ref(m.dense_copy_r(m.dense_c()))
0043 assert_equal_ref(m.dense_copy_c(m.dense_r()))
0044
0045
0046 def test_partially_fixed():
0047 ref2 = np.array([[0.0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
0048 np.testing.assert_array_equal(m.partial_copy_four_rm_r(ref2), ref2)
0049 np.testing.assert_array_equal(m.partial_copy_four_rm_c(ref2), ref2)
0050 np.testing.assert_array_equal(m.partial_copy_four_rm_r(ref2[:, 1]), ref2[:, [1]])
0051 np.testing.assert_array_equal(m.partial_copy_four_rm_c(ref2[0, :]), ref2[[0], :])
0052 np.testing.assert_array_equal(
0053 m.partial_copy_four_rm_r(ref2[:, (0, 2)]), ref2[:, (0, 2)]
0054 )
0055 np.testing.assert_array_equal(
0056 m.partial_copy_four_rm_c(ref2[(3, 1, 2), :]), ref2[(3, 1, 2), :]
0057 )
0058
0059 np.testing.assert_array_equal(m.partial_copy_four_cm_r(ref2), ref2)
0060 np.testing.assert_array_equal(m.partial_copy_four_cm_c(ref2), ref2)
0061 np.testing.assert_array_equal(m.partial_copy_four_cm_r(ref2[:, 1]), ref2[:, [1]])
0062 np.testing.assert_array_equal(m.partial_copy_four_cm_c(ref2[0, :]), ref2[[0], :])
0063 np.testing.assert_array_equal(
0064 m.partial_copy_four_cm_r(ref2[:, (0, 2)]), ref2[:, (0, 2)]
0065 )
0066 np.testing.assert_array_equal(
0067 m.partial_copy_four_cm_c(ref2[(3, 1, 2), :]), ref2[(3, 1, 2), :]
0068 )
0069
0070
0071 functions = [
0072 m.partial_copy_four_rm_r,
0073 m.partial_copy_four_rm_c,
0074 m.partial_copy_four_cm_r,
0075 m.partial_copy_four_cm_c,
0076 ]
0077 matrix_with_wrong_shape = [[1, 2], [3, 4]]
0078 for f in functions:
0079 with pytest.raises(TypeError) as excinfo:
0080 f(matrix_with_wrong_shape)
0081 assert "incompatible function arguments" in str(excinfo.value)
0082
0083
0084 def test_mutator_descriptors():
0085 zr = np.arange(30, dtype="float32").reshape(5, 6)
0086 zc = zr.reshape(6, 5).transpose()
0087
0088 m.fixed_mutator_r(zr)
0089 m.fixed_mutator_c(zc)
0090 m.fixed_mutator_a(zr)
0091 m.fixed_mutator_a(zc)
0092 with pytest.raises(TypeError) as excinfo:
0093 m.fixed_mutator_r(zc)
0094 assert (
0095 "(arg0: numpy.ndarray[numpy.float32[5, 6],"
0096 " flags.writeable, flags.c_contiguous]) -> None" in str(excinfo.value)
0097 )
0098 with pytest.raises(TypeError) as excinfo:
0099 m.fixed_mutator_c(zr)
0100 assert (
0101 "(arg0: numpy.ndarray[numpy.float32[5, 6],"
0102 " flags.writeable, flags.f_contiguous]) -> None" in str(excinfo.value)
0103 )
0104 with pytest.raises(TypeError) as excinfo:
0105 m.fixed_mutator_a(np.array([[1, 2], [3, 4]], dtype="float32"))
0106 assert "(arg0: numpy.ndarray[numpy.float32[5, 6], flags.writeable]) -> None" in str(
0107 excinfo.value
0108 )
0109 zr.flags.writeable = False
0110 with pytest.raises(TypeError):
0111 m.fixed_mutator_r(zr)
0112 with pytest.raises(TypeError):
0113 m.fixed_mutator_a(zr)
0114
0115
0116 def test_cpp_casting():
0117 assert m.cpp_copy(m.fixed_r()) == 22.0
0118 assert m.cpp_copy(m.fixed_c()) == 22.0
0119 z = np.array([[5.0, 6], [7, 8]])
0120 assert m.cpp_copy(z) == 7.0
0121 assert m.cpp_copy(m.get_cm_ref()) == 21.0
0122 assert m.cpp_copy(m.get_rm_ref()) == 21.0
0123 assert m.cpp_ref_c(m.get_cm_ref()) == 21.0
0124 assert m.cpp_ref_r(m.get_rm_ref()) == 21.0
0125 with pytest.raises(RuntimeError) as excinfo:
0126
0127 m.cpp_ref_any(m.fixed_c())
0128 assert "Unable to cast Python instance" in str(excinfo.value)
0129 with pytest.raises(RuntimeError) as excinfo:
0130
0131 m.cpp_ref_any(m.fixed_r())
0132 assert "Unable to cast Python instance" in str(excinfo.value)
0133 assert m.cpp_ref_any(m.ReturnTester.create()) == 1.0
0134
0135 assert m.cpp_ref_any(m.get_cm_ref()) == 21.0
0136 assert m.cpp_ref_any(m.get_cm_ref()) == 21.0
0137
0138
0139 def test_pass_readonly_array():
0140 z = np.full((5, 6), 42.0)
0141 z.flags.writeable = False
0142 np.testing.assert_array_equal(z, m.fixed_copy_r(z))
0143 np.testing.assert_array_equal(m.fixed_r_const(), m.fixed_r())
0144 assert not m.fixed_r_const().flags.writeable
0145 np.testing.assert_array_equal(m.fixed_copy_r(m.fixed_r_const()), m.fixed_r_const())
0146
0147
0148 def test_nonunit_stride_from_python():
0149 counting_mat = np.arange(9.0, dtype=np.float32).reshape((3, 3))
0150 second_row = counting_mat[1, :]
0151 second_col = counting_mat[:, 1]
0152 np.testing.assert_array_equal(m.double_row(second_row), 2.0 * second_row)
0153 np.testing.assert_array_equal(m.double_col(second_row), 2.0 * second_row)
0154 np.testing.assert_array_equal(m.double_complex(second_row), 2.0 * second_row)
0155 np.testing.assert_array_equal(m.double_row(second_col), 2.0 * second_col)
0156 np.testing.assert_array_equal(m.double_col(second_col), 2.0 * second_col)
0157 np.testing.assert_array_equal(m.double_complex(second_col), 2.0 * second_col)
0158
0159 counting_3d = np.arange(27.0, dtype=np.float32).reshape((3, 3, 3))
0160 slices = [counting_3d[0, :, :], counting_3d[:, 0, :], counting_3d[:, :, 0]]
0161 for ref_mat in slices:
0162 np.testing.assert_array_equal(m.double_mat_cm(ref_mat), 2.0 * ref_mat)
0163 np.testing.assert_array_equal(m.double_mat_rm(ref_mat), 2.0 * ref_mat)
0164
0165
0166 m.double_threer(second_row)
0167 m.double_threec(second_col)
0168 np.testing.assert_array_equal(counting_mat, [[0.0, 2, 2], [6, 16, 10], [6, 14, 8]])
0169
0170
0171 def test_negative_stride_from_python(msg):
0172 """Eigen doesn't support (as of yet) negative strides. When a function takes an Eigen matrix by
0173 copy or const reference, we can pass a numpy array that has negative strides. Otherwise, an
0174 exception will be thrown as Eigen will not be able to map the numpy array."""
0175
0176 counting_mat = np.arange(9.0, dtype=np.float32).reshape((3, 3))
0177 counting_mat = counting_mat[::-1, ::-1]
0178 second_row = counting_mat[1, :]
0179 second_col = counting_mat[:, 1]
0180 np.testing.assert_array_equal(m.double_row(second_row), 2.0 * second_row)
0181 np.testing.assert_array_equal(m.double_col(second_row), 2.0 * second_row)
0182 np.testing.assert_array_equal(m.double_complex(second_row), 2.0 * second_row)
0183 np.testing.assert_array_equal(m.double_row(second_col), 2.0 * second_col)
0184 np.testing.assert_array_equal(m.double_col(second_col), 2.0 * second_col)
0185 np.testing.assert_array_equal(m.double_complex(second_col), 2.0 * second_col)
0186
0187 counting_3d = np.arange(27.0, dtype=np.float32).reshape((3, 3, 3))
0188 counting_3d = counting_3d[::-1, ::-1, ::-1]
0189 slices = [counting_3d[0, :, :], counting_3d[:, 0, :], counting_3d[:, :, 0]]
0190 for ref_mat in slices:
0191 np.testing.assert_array_equal(m.double_mat_cm(ref_mat), 2.0 * ref_mat)
0192 np.testing.assert_array_equal(m.double_mat_rm(ref_mat), 2.0 * ref_mat)
0193
0194
0195 with pytest.raises(TypeError) as excinfo:
0196 m.double_threer(second_row)
0197 assert (
0198 msg(excinfo.value)
0199 == """
0200 double_threer(): incompatible function arguments. The following argument types are supported:
0201 1. (arg0: numpy.ndarray[numpy.float32[1, 3], flags.writeable]) -> None
0202
0203 Invoked with: """
0204 + repr(np.array([5.0, 4.0, 3.0], dtype="float32"))
0205 )
0206
0207 with pytest.raises(TypeError) as excinfo:
0208 m.double_threec(second_col)
0209 assert (
0210 msg(excinfo.value)
0211 == """
0212 double_threec(): incompatible function arguments. The following argument types are supported:
0213 1. (arg0: numpy.ndarray[numpy.float32[3, 1], flags.writeable]) -> None
0214
0215 Invoked with: """
0216 + repr(np.array([7.0, 4.0, 1.0], dtype="float32"))
0217 )
0218
0219
0220 def test_block_runtime_error_type_caster_eigen_ref_made_a_copy():
0221 with pytest.raises(RuntimeError) as excinfo:
0222 m.block(ref, 0, 0, 0, 0)
0223 assert str(excinfo.value) == "type_caster for Eigen::Ref made a copy."
0224
0225
0226 def test_nonunit_stride_to_python():
0227 assert np.all(m.diagonal(ref) == ref.diagonal())
0228 assert np.all(m.diagonal_1(ref) == ref.diagonal(1))
0229 for i in range(-5, 7):
0230 assert np.all(m.diagonal_n(ref, i) == ref.diagonal(i)), f"m.diagonal_n({i})"
0231
0232
0233
0234 rof = np.asarray(ref, order="F")
0235 assert np.all(m.block(rof, 2, 1, 3, 3) == rof[2:5, 1:4])
0236 assert np.all(m.block(rof, 1, 4, 4, 2) == rof[1:, 4:])
0237 assert np.all(m.block(rof, 1, 4, 3, 2) == rof[1:4, 4:])
0238
0239
0240 def test_eigen_ref_to_python():
0241 chols = [m.cholesky1, m.cholesky2, m.cholesky3, m.cholesky4]
0242 for i, chol in enumerate(chols, start=1):
0243 mymat = chol(np.array([[1.0, 2, 4], [2, 13, 23], [4, 23, 77]]))
0244 assert np.all(
0245 mymat == np.array([[1, 0, 0], [2, 3, 0], [4, 5, 6]])
0246 ), f"cholesky{i}"
0247
0248
0249 def assign_both(a1, a2, r, c, v):
0250 a1[r, c] = v
0251 a2[r, c] = v
0252
0253
0254 def array_copy_but_one(a, r, c, v):
0255 z = np.array(a, copy=True)
0256 z[r, c] = v
0257 return z
0258
0259
0260 def test_eigen_return_references():
0261 """Tests various ways of returning references and non-referencing copies"""
0262
0263 primary = np.ones((10, 10))
0264 a = m.ReturnTester()
0265 a_get1 = a.get()
0266 assert not a_get1.flags.owndata and a_get1.flags.writeable
0267 assign_both(a_get1, primary, 3, 3, 5)
0268 a_get2 = a.get_ptr()
0269 assert not a_get2.flags.owndata and a_get2.flags.writeable
0270 assign_both(a_get1, primary, 2, 3, 6)
0271
0272 a_view1 = a.view()
0273 assert not a_view1.flags.owndata and not a_view1.flags.writeable
0274 with pytest.raises(ValueError):
0275 a_view1[2, 3] = 4
0276 a_view2 = a.view_ptr()
0277 assert not a_view2.flags.owndata and not a_view2.flags.writeable
0278 with pytest.raises(ValueError):
0279 a_view2[2, 3] = 4
0280
0281 a_copy1 = a.copy_get()
0282 assert a_copy1.flags.owndata and a_copy1.flags.writeable
0283 np.testing.assert_array_equal(a_copy1, primary)
0284 a_copy1[7, 7] = -44
0285 c1want = array_copy_but_one(primary, 7, 7, -44)
0286 a_copy2 = a.copy_view()
0287 assert a_copy2.flags.owndata and a_copy2.flags.writeable
0288 np.testing.assert_array_equal(a_copy2, primary)
0289 a_copy2[4, 4] = -22
0290 c2want = array_copy_but_one(primary, 4, 4, -22)
0291
0292 a_ref1 = a.ref()
0293 assert not a_ref1.flags.owndata and a_ref1.flags.writeable
0294 assign_both(a_ref1, primary, 1, 1, 15)
0295 a_ref2 = a.ref_const()
0296 assert not a_ref2.flags.owndata and not a_ref2.flags.writeable
0297 with pytest.raises(ValueError):
0298 a_ref2[5, 5] = 33
0299 a_ref3 = a.ref_safe()
0300 assert not a_ref3.flags.owndata and a_ref3.flags.writeable
0301 assign_both(a_ref3, primary, 0, 7, 99)
0302 a_ref4 = a.ref_const_safe()
0303 assert not a_ref4.flags.owndata and not a_ref4.flags.writeable
0304 with pytest.raises(ValueError):
0305 a_ref4[7, 0] = 987654321
0306
0307 a_copy3 = a.copy_ref()
0308 assert a_copy3.flags.owndata and a_copy3.flags.writeable
0309 np.testing.assert_array_equal(a_copy3, primary)
0310 a_copy3[8, 1] = 11
0311 c3want = array_copy_but_one(primary, 8, 1, 11)
0312 a_copy4 = a.copy_ref_const()
0313 assert a_copy4.flags.owndata and a_copy4.flags.writeable
0314 np.testing.assert_array_equal(a_copy4, primary)
0315 a_copy4[8, 4] = 88
0316 c4want = array_copy_but_one(primary, 8, 4, 88)
0317
0318 a_block1 = a.block(3, 3, 2, 2)
0319 assert not a_block1.flags.owndata and a_block1.flags.writeable
0320 a_block1[0, 0] = 55
0321 primary[3, 3] = 55
0322 a_block2 = a.block_safe(2, 2, 3, 2)
0323 assert not a_block2.flags.owndata and a_block2.flags.writeable
0324 a_block2[2, 1] = -123
0325 primary[4, 3] = -123
0326 a_block3 = a.block_const(6, 7, 4, 3)
0327 assert not a_block3.flags.owndata and not a_block3.flags.writeable
0328 with pytest.raises(ValueError):
0329 a_block3[2, 2] = -44444
0330
0331 a_copy5 = a.copy_block(2, 2, 2, 3)
0332 assert a_copy5.flags.owndata and a_copy5.flags.writeable
0333 np.testing.assert_array_equal(a_copy5, primary[2:4, 2:5])
0334 a_copy5[1, 1] = 777
0335 c5want = array_copy_but_one(primary[2:4, 2:5], 1, 1, 777)
0336
0337 a_corn1 = a.corners()
0338 assert not a_corn1.flags.owndata and a_corn1.flags.writeable
0339 a_corn1 *= 50
0340 a_corn1[1, 1] = 999
0341 primary[0, 0] = 50
0342 primary[0, 9] = 50
0343 primary[9, 0] = 50
0344 primary[9, 9] = 999
0345 a_corn2 = a.corners_const()
0346 assert not a_corn2.flags.owndata and not a_corn2.flags.writeable
0347 with pytest.raises(ValueError):
0348 a_corn2[1, 0] = 51
0349
0350
0351
0352 np.testing.assert_array_equal(a_get1, primary)
0353 np.testing.assert_array_equal(a_get2, primary)
0354 np.testing.assert_array_equal(a_view1, primary)
0355 np.testing.assert_array_equal(a_view2, primary)
0356 np.testing.assert_array_equal(a_ref1, primary)
0357 np.testing.assert_array_equal(a_ref2, primary)
0358 np.testing.assert_array_equal(a_ref3, primary)
0359 np.testing.assert_array_equal(a_ref4, primary)
0360 np.testing.assert_array_equal(a_block1, primary[3:5, 3:5])
0361 np.testing.assert_array_equal(a_block2, primary[2:5, 2:4])
0362 np.testing.assert_array_equal(a_block3, primary[6:10, 7:10])
0363 np.testing.assert_array_equal(
0364 a_corn1, primary[0 :: primary.shape[0] - 1, 0 :: primary.shape[1] - 1]
0365 )
0366 np.testing.assert_array_equal(
0367 a_corn2, primary[0 :: primary.shape[0] - 1, 0 :: primary.shape[1] - 1]
0368 )
0369
0370 np.testing.assert_array_equal(a_copy1, c1want)
0371 np.testing.assert_array_equal(a_copy2, c2want)
0372 np.testing.assert_array_equal(a_copy3, c3want)
0373 np.testing.assert_array_equal(a_copy4, c4want)
0374 np.testing.assert_array_equal(a_copy5, c5want)
0375
0376
0377 def assert_keeps_alive(cl, method, *args):
0378 cstats = ConstructorStats.get(cl)
0379 start_with = cstats.alive()
0380 a = cl()
0381 assert cstats.alive() == start_with + 1
0382 z = method(a, *args)
0383 assert cstats.alive() == start_with + 1
0384 del a
0385
0386 assert cstats.alive() == start_with + 1
0387 del z
0388
0389 assert cstats.alive() == start_with
0390
0391
0392 def test_eigen_keepalive():
0393 a = m.ReturnTester()
0394 cstats = ConstructorStats.get(m.ReturnTester)
0395 assert cstats.alive() == 1
0396 unsafe = [a.ref(), a.ref_const(), a.block(1, 2, 3, 4)]
0397 copies = [
0398 a.copy_get(),
0399 a.copy_view(),
0400 a.copy_ref(),
0401 a.copy_ref_const(),
0402 a.copy_block(4, 3, 2, 1),
0403 ]
0404 del a
0405 assert cstats.alive() == 0
0406 del unsafe
0407 del copies
0408
0409 for meth in [
0410 m.ReturnTester.get,
0411 m.ReturnTester.get_ptr,
0412 m.ReturnTester.view,
0413 m.ReturnTester.view_ptr,
0414 m.ReturnTester.ref_safe,
0415 m.ReturnTester.ref_const_safe,
0416 m.ReturnTester.corners,
0417 m.ReturnTester.corners_const,
0418 ]:
0419 assert_keeps_alive(m.ReturnTester, meth)
0420
0421 for meth in [m.ReturnTester.block_safe, m.ReturnTester.block_const]:
0422 assert_keeps_alive(m.ReturnTester, meth, 4, 3, 2, 1)
0423
0424
0425 def test_eigen_ref_mutators():
0426 """Tests Eigen's ability to mutate numpy values"""
0427
0428 orig = np.array([[1.0, 2, 3], [4, 5, 6], [7, 8, 9]])
0429 zr = np.array(orig)
0430 zc = np.array(orig, order="F")
0431 m.add_rm(zr, 1, 0, 100)
0432 assert np.all(zr == np.array([[1.0, 2, 3], [104, 5, 6], [7, 8, 9]]))
0433 m.add_cm(zc, 1, 0, 200)
0434 assert np.all(zc == np.array([[1.0, 2, 3], [204, 5, 6], [7, 8, 9]]))
0435
0436 m.add_any(zr, 1, 0, 20)
0437 assert np.all(zr == np.array([[1.0, 2, 3], [124, 5, 6], [7, 8, 9]]))
0438 m.add_any(zc, 1, 0, 10)
0439 assert np.all(zc == np.array([[1.0, 2, 3], [214, 5, 6], [7, 8, 9]]))
0440
0441
0442 with pytest.raises(TypeError):
0443 m.add_rm(zc, 1, 0, 1)
0444 with pytest.raises(TypeError):
0445 m.add_cm(zr, 1, 0, 1)
0446
0447
0448 m.add1(zr, 1, 0, -100)
0449 m.add2(zr, 1, 0, -20)
0450 assert np.all(zr == orig)
0451 m.add1(zc, 1, 0, -200)
0452 m.add2(zc, 1, 0, -10)
0453 assert np.all(zc == orig)
0454
0455
0456
0457 cornersr = zr[0::2, 0::2]
0458 cornersc = zc[0::2, 0::2]
0459
0460 assert np.all(cornersr == np.array([[1.0, 3], [7, 9]]))
0461 assert np.all(cornersc == np.array([[1.0, 3], [7, 9]]))
0462
0463 with pytest.raises(TypeError):
0464 m.add_rm(cornersr, 0, 1, 25)
0465 with pytest.raises(TypeError):
0466 m.add_cm(cornersr, 0, 1, 25)
0467 with pytest.raises(TypeError):
0468 m.add_rm(cornersc, 0, 1, 25)
0469 with pytest.raises(TypeError):
0470 m.add_cm(cornersc, 0, 1, 25)
0471 m.add_any(cornersr, 0, 1, 25)
0472 m.add_any(cornersc, 0, 1, 44)
0473 assert np.all(zr == np.array([[1.0, 2, 28], [4, 5, 6], [7, 8, 9]]))
0474 assert np.all(zc == np.array([[1.0, 2, 47], [4, 5, 6], [7, 8, 9]]))
0475
0476
0477 zro = zr[0:4, 0:4]
0478 zro.flags.writeable = False
0479 with pytest.raises(TypeError):
0480 m.add_rm(zro, 0, 0, 0)
0481 with pytest.raises(TypeError):
0482 m.add_any(zro, 0, 0, 0)
0483 with pytest.raises(TypeError):
0484 m.add1(zro, 0, 0, 0)
0485 with pytest.raises(TypeError):
0486 m.add2(zro, 0, 0, 0)
0487
0488
0489 zi = np.array([[1, 2], [3, 4]])
0490 with pytest.raises(TypeError):
0491 m.add_rm(zi)
0492
0493
0494 def test_numpy_ref_mutators():
0495 """Tests numpy mutating Eigen matrices (for returned Eigen::Ref<...>s)"""
0496
0497 m.reset_refs()
0498
0499 zc = m.get_cm_ref()
0500 zcro = m.get_cm_const_ref()
0501 zr = m.get_rm_ref()
0502 zrro = m.get_rm_const_ref()
0503
0504 assert [zc[1, 2], zcro[1, 2], zr[1, 2], zrro[1, 2]] == [23] * 4
0505
0506 assert not zc.flags.owndata and zc.flags.writeable
0507 assert not zr.flags.owndata and zr.flags.writeable
0508 assert not zcro.flags.owndata and not zcro.flags.writeable
0509 assert not zrro.flags.owndata and not zrro.flags.writeable
0510
0511 zc[1, 2] = 99
0512 expect = np.array([[11.0, 12, 13], [21, 22, 99], [31, 32, 33]])
0513
0514 assert np.all(zc == expect)
0515 assert np.all(zcro == expect)
0516 assert np.all(m.get_cm_ref() == expect)
0517
0518 zr[1, 2] = 99
0519 assert np.all(zr == expect)
0520 assert np.all(zrro == expect)
0521 assert np.all(m.get_rm_ref() == expect)
0522
0523
0524 with pytest.raises(ValueError):
0525 zcro[1, 2] = 6
0526 with pytest.raises(ValueError):
0527 zrro[1, 2] = 6
0528
0529
0530
0531 y1 = np.array(m.get_cm_const_ref())
0532
0533 assert y1.flags.owndata and y1.flags.writeable
0534
0535 assert y1[1, 2] == 99
0536 y1[1, 2] += 12
0537 assert y1[1, 2] == 111
0538 assert zc[1, 2] == 99
0539
0540
0541 def test_both_ref_mutators():
0542 """Tests a complex chain of nested eigen/numpy references"""
0543
0544 m.reset_refs()
0545
0546 z = m.get_cm_ref()
0547 z[0, 2] -= 3
0548 z2 = m.incr_matrix(z, 1)
0549 z2[1, 1] += 6
0550 z3 = m.incr_matrix(z, 2)
0551 z3[2, 2] += -5
0552 z4 = m.incr_matrix(z, 3)
0553 z4[1, 1] -= 1
0554 z5 = m.incr_matrix(z, 4)
0555 z5[0, 0] = 0
0556 assert np.all(z == z2)
0557 assert np.all(z == z3)
0558 assert np.all(z == z4)
0559 assert np.all(z == z5)
0560 expect = np.array([[0.0, 22, 20], [31, 37, 33], [41, 42, 38]])
0561 assert np.all(z == expect)
0562
0563 y = np.array(range(100), dtype="float64").reshape(10, 10)
0564 y2 = m.incr_matrix_any(y, 10)
0565 y3 = m.incr_matrix_any(
0566 y2[0::2, 0::2], -33
0567 )
0568 y4 = m.even_rows(y3)
0569 y5 = m.even_cols(y4)
0570 y6 = m.incr_matrix_any(y5, 1000)
0571
0572
0573 yexpect = np.array(range(100), dtype="float64").reshape(10, 10)
0574 yexpect += 10
0575 yexpect[0::2, 0::2] -= 33
0576 yexpect[0::4, 0::4] += 1000
0577 assert np.all(y6 == yexpect[0::4, 0::4])
0578 assert np.all(y5 == yexpect[0::4, 0::4])
0579 assert np.all(y4 == yexpect[0::4, 0::2])
0580 assert np.all(y3 == yexpect[0::2, 0::2])
0581 assert np.all(y2 == yexpect)
0582 assert np.all(y == yexpect)
0583
0584
0585 def test_nocopy_wrapper():
0586
0587
0588 int_matrix_colmajor = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], order="F")
0589 dbl_matrix_colmajor = np.array(
0590 int_matrix_colmajor, dtype="double", order="F", copy=True
0591 )
0592 int_matrix_rowmajor = np.array(int_matrix_colmajor, order="C", copy=True)
0593 dbl_matrix_rowmajor = np.array(
0594 int_matrix_rowmajor, dtype="double", order="C", copy=True
0595 )
0596
0597
0598 assert m.get_elem(int_matrix_colmajor) == 8
0599 assert m.get_elem(dbl_matrix_colmajor) == 8
0600 assert m.get_elem(int_matrix_rowmajor) == 8
0601 assert m.get_elem(dbl_matrix_rowmajor) == 8
0602
0603
0604 with pytest.raises(TypeError) as excinfo:
0605 m.get_elem_nocopy(int_matrix_colmajor)
0606 assert "get_elem_nocopy(): incompatible function arguments." in str(
0607 excinfo.value
0608 ) and ", flags.f_contiguous" in str(excinfo.value)
0609 assert m.get_elem_nocopy(dbl_matrix_colmajor) == 8
0610 with pytest.raises(TypeError) as excinfo:
0611 m.get_elem_nocopy(int_matrix_rowmajor)
0612 assert "get_elem_nocopy(): incompatible function arguments." in str(
0613 excinfo.value
0614 ) and ", flags.f_contiguous" in str(excinfo.value)
0615 with pytest.raises(TypeError) as excinfo:
0616 m.get_elem_nocopy(dbl_matrix_rowmajor)
0617 assert "get_elem_nocopy(): incompatible function arguments." in str(
0618 excinfo.value
0619 ) and ", flags.f_contiguous" in str(excinfo.value)
0620
0621
0622 with pytest.raises(TypeError) as excinfo:
0623 m.get_elem_rm_nocopy(int_matrix_colmajor)
0624 assert "get_elem_rm_nocopy(): incompatible function arguments." in str(
0625 excinfo.value
0626 ) and ", flags.c_contiguous" in str(excinfo.value)
0627 with pytest.raises(TypeError) as excinfo:
0628 m.get_elem_rm_nocopy(dbl_matrix_colmajor)
0629 assert "get_elem_rm_nocopy(): incompatible function arguments." in str(
0630 excinfo.value
0631 ) and ", flags.c_contiguous" in str(excinfo.value)
0632 assert m.get_elem_rm_nocopy(int_matrix_rowmajor) == 8
0633 with pytest.raises(TypeError) as excinfo:
0634 m.get_elem_rm_nocopy(dbl_matrix_rowmajor)
0635 assert "get_elem_rm_nocopy(): incompatible function arguments." in str(
0636 excinfo.value
0637 ) and ", flags.c_contiguous" in str(excinfo.value)
0638
0639
0640 def test_eigen_ref_life_support():
0641 """Ensure the lifetime of temporary arrays created by the `Ref` caster
0642
0643 The `Ref` caster sometimes creates a copy which needs to stay alive. This needs to
0644 happen both for directs casts (just the array) or indirectly (e.g. list of arrays).
0645 """
0646
0647 a = np.full(shape=10, fill_value=8, dtype=np.int8)
0648 assert m.get_elem_direct(a) == 8
0649
0650 list_of_a = [a]
0651 assert m.get_elem_indirect(list_of_a) == 8
0652
0653
0654 def test_special_matrix_objects():
0655 assert np.all(m.incr_diag(7) == np.diag([1.0, 2, 3, 4, 5, 6, 7]))
0656
0657 asymm = np.array([[1.0, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]])
0658 symm_lower = np.array(asymm)
0659 symm_upper = np.array(asymm)
0660 for i in range(4):
0661 for j in range(i + 1, 4):
0662 symm_lower[i, j] = symm_lower[j, i]
0663 symm_upper[j, i] = symm_upper[i, j]
0664
0665 assert np.all(m.symmetric_lower(asymm) == symm_lower)
0666 assert np.all(m.symmetric_upper(asymm) == symm_upper)
0667
0668
0669 def test_dense_signature(doc):
0670 assert (
0671 doc(m.double_col)
0672 == """
0673 double_col(arg0: numpy.ndarray[numpy.float32[m, 1]]) -> numpy.ndarray[numpy.float32[m, 1]]
0674 """
0675 )
0676 assert (
0677 doc(m.double_row)
0678 == """
0679 double_row(arg0: numpy.ndarray[numpy.float32[1, n]]) -> numpy.ndarray[numpy.float32[1, n]]
0680 """
0681 )
0682 assert doc(m.double_complex) == (
0683 """
0684 double_complex(arg0: numpy.ndarray[numpy.complex64[m, 1]])"""
0685 """ -> numpy.ndarray[numpy.complex64[m, 1]]
0686 """
0687 )
0688 assert doc(m.double_mat_rm) == (
0689 """
0690 double_mat_rm(arg0: numpy.ndarray[numpy.float32[m, n]])"""
0691 """ -> numpy.ndarray[numpy.float32[m, n]]
0692 """
0693 )
0694
0695
0696 def test_named_arguments():
0697 a = np.array([[1.0, 2], [3, 4], [5, 6]])
0698 b = np.ones((2, 1))
0699
0700 assert np.all(m.matrix_multiply(a, b) == np.array([[3.0], [7], [11]]))
0701 assert np.all(m.matrix_multiply(A=a, B=b) == np.array([[3.0], [7], [11]]))
0702 assert np.all(m.matrix_multiply(B=b, A=a) == np.array([[3.0], [7], [11]]))
0703
0704 with pytest.raises(ValueError) as excinfo:
0705 m.matrix_multiply(b, a)
0706 assert str(excinfo.value) == "Nonconformable matrices!"
0707
0708 with pytest.raises(ValueError) as excinfo:
0709 m.matrix_multiply(A=b, B=a)
0710 assert str(excinfo.value) == "Nonconformable matrices!"
0711
0712 with pytest.raises(ValueError) as excinfo:
0713 m.matrix_multiply(B=a, A=b)
0714 assert str(excinfo.value) == "Nonconformable matrices!"
0715
0716
0717 def test_sparse():
0718 pytest.importorskip("scipy")
0719 assert_sparse_equal_ref(m.sparse_r())
0720 assert_sparse_equal_ref(m.sparse_c())
0721 assert_sparse_equal_ref(m.sparse_copy_r(m.sparse_r()))
0722 assert_sparse_equal_ref(m.sparse_copy_c(m.sparse_c()))
0723 assert_sparse_equal_ref(m.sparse_copy_r(m.sparse_c()))
0724 assert_sparse_equal_ref(m.sparse_copy_c(m.sparse_r()))
0725
0726
0727 def test_sparse_signature(doc):
0728 pytest.importorskip("scipy")
0729 assert (
0730 doc(m.sparse_copy_r)
0731 == """
0732 sparse_copy_r(arg0: scipy.sparse.csr_matrix[numpy.float32]) -> scipy.sparse.csr_matrix[numpy.float32]
0733 """
0734 )
0735 assert (
0736 doc(m.sparse_copy_c)
0737 == """
0738 sparse_copy_c(arg0: scipy.sparse.csc_matrix[numpy.float32]) -> scipy.sparse.csc_matrix[numpy.float32]
0739 """
0740 )
0741
0742
0743 def test_issue738():
0744 """Ignore strides on a length-1 dimension (even if they would be incompatible length > 1)"""
0745 assert np.all(m.iss738_f1(np.array([[1.0, 2, 3]])) == np.array([[1.0, 102, 203]]))
0746 assert np.all(
0747 m.iss738_f1(np.array([[1.0], [2], [3]])) == np.array([[1.0], [12], [23]])
0748 )
0749
0750 assert np.all(m.iss738_f2(np.array([[1.0, 2, 3]])) == np.array([[1.0, 102, 203]]))
0751 assert np.all(
0752 m.iss738_f2(np.array([[1.0], [2], [3]])) == np.array([[1.0], [12], [23]])
0753 )
0754
0755
0756 @pytest.mark.parametrize("func", [m.iss738_f1, m.iss738_f2])
0757 @pytest.mark.parametrize("sizes", [(0, 2), (2, 0)])
0758 def test_zero_length(func, sizes):
0759 """Ignore strides on a length-0 dimension (even if they would be incompatible length > 1)"""
0760 assert np.all(func(np.zeros(sizes)) == np.zeros(sizes))
0761
0762
0763 def test_issue1105():
0764 """Issue 1105: 1xN or Nx1 input arrays weren't accepted for eigen
0765 compile-time row vectors or column vector"""
0766 assert m.iss1105_row(np.ones((1, 7)))
0767 assert m.iss1105_col(np.ones((7, 1)))
0768
0769
0770 with pytest.raises(TypeError) as excinfo:
0771 m.iss1105_row(np.ones((7, 1)))
0772 assert "incompatible function arguments" in str(excinfo.value)
0773 with pytest.raises(TypeError) as excinfo:
0774 m.iss1105_col(np.ones((1, 7)))
0775 assert "incompatible function arguments" in str(excinfo.value)
0776
0777
0778 def test_custom_operator_new():
0779 """Using Eigen types as member variables requires a class-specific
0780 operator new with proper alignment"""
0781
0782 o = m.CustomOperatorNew()
0783 np.testing.assert_allclose(o.a, 0.0)
0784 np.testing.assert_allclose(o.b.diagonal(), 1.0)