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


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:37:45