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


gtsam
Author(s):
autogenerated on Sat May 8 2021 02:46:03