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