μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
test_eigen_matrix.cpp
Go to the documentation of this file.
1/*
2 tests/eigen.cpp -- automatic conversion of Eigen types
3
4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
11#include <pybind11/stl.h>
12
13#include "constructor_stats.h"
14#include "pybind11_tests.h"
15
17
18#include <Eigen/Cholesky>
19
20using MatrixXdR = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
21
22// Sets/resets a testing reference matrix to have values of 10*r + c, where r and c are the
23// (1-based) row/column number.
24template <typename M>
25void reset_ref(M &x) {
26 for (int i = 0; i < x.rows(); i++) {
27 for (int j = 0; j < x.cols(); j++) {
28 x(i, j) = 11 + 10 * i + j;
29 }
30 }
31}
32
33// Returns a static, column-major matrix
34Eigen::MatrixXd &get_cm() {
35 static Eigen::MatrixXd *x;
36 if (!x) {
37 x = new Eigen::MatrixXd(3, 3);
38 reset_ref(*x);
39 }
40 return *x;
41}
42// Likewise, but row-major
44 static MatrixXdR *x;
45 if (!x) {
46 x = new MatrixXdR(3, 3);
47 reset_ref(*x);
48 }
49 return *x;
50}
51// Resets the values of the static matrices returned by get_cm()/get_rm()
52void reset_refs() {
55}
56
57// Returns element 2,1 from a matrix (used to test copy/nocopy)
58double get_elem(const Eigen::Ref<const Eigen::MatrixXd> &m) { return m(2, 1); };
59
60// Returns a matrix with 10*r + 100*c added to each matrix element (to help test that the matrix
61// reference is referencing rows/columns correctly).
62template <typename MatrixArgType>
63Eigen::MatrixXd adjust_matrix(MatrixArgType m) {
64 Eigen::MatrixXd ret(m);
65 for (int c = 0; c < m.cols(); c++) {
66 for (int r = 0; r < m.rows(); r++) {
67 ret(r, c) += 10 * r + 100 * c; // NOLINT(clang-analyzer-core.uninitialized.Assign)
68 }
69 }
70 return ret;
71}
72
73struct CustomOperatorNew {
74 CustomOperatorNew() = default;
75
76 Eigen::Matrix4d a = Eigen::Matrix4d::Zero();
77 Eigen::Matrix4d b = Eigen::Matrix4d::Identity();
78
80};
81
82TEST_SUBMODULE(eigen_matrix, m) {
83 using FixedMatrixR = Eigen::Matrix<float, 5, 6, Eigen::RowMajor>;
84 using FixedMatrixC = Eigen::Matrix<float, 5, 6>;
85 using DenseMatrixR = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
86 using DenseMatrixC = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>;
87 using FourRowMatrixC = Eigen::Matrix<float, 4, Eigen::Dynamic>;
88 using FourColMatrixC = Eigen::Matrix<float, Eigen::Dynamic, 4>;
89 using FourRowMatrixR = Eigen::Matrix<float, 4, Eigen::Dynamic>;
90 using FourColMatrixR = Eigen::Matrix<float, Eigen::Dynamic, 4>;
91 using SparseMatrixR = Eigen::SparseMatrix<float, Eigen::RowMajor>;
92 using SparseMatrixC = Eigen::SparseMatrix<float>;
93
94 // various tests
95 m.def("double_col", [](const Eigen::VectorXf &x) -> Eigen::VectorXf { return 2.0f * x; });
96 m.def("double_row",
97 [](const Eigen::RowVectorXf &x) -> Eigen::RowVectorXf { return 2.0f * x; });
98 m.def("double_complex",
99 [](const Eigen::VectorXcf &x) -> Eigen::VectorXcf { return 2.0f * x; });
100 m.def("double_threec", [](py::EigenDRef<Eigen::Vector3f> x) { x *= 2; });
101 m.def("double_threer", [](py::EigenDRef<Eigen::RowVector3f> x) { x *= 2; });
102 m.def("double_mat_cm", [](const Eigen::MatrixXf &x) -> Eigen::MatrixXf { return 2.0f * x; });
103 m.def("double_mat_rm", [](const DenseMatrixR &x) -> DenseMatrixR { return 2.0f * x; });
104
105 // test_eigen_ref_to_python
106 // Different ways of passing via Eigen::Ref; the first and second are the Eigen-recommended
107 m.def("cholesky1",
108 [](const Eigen::Ref<MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });
109 m.def("cholesky2", [](const Eigen::Ref<const MatrixXdR> &x) -> Eigen::MatrixXd {
110 return x.llt().matrixL();
111 });
112 m.def("cholesky3",
113 [](const Eigen::Ref<MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });
114 m.def("cholesky4", [](const Eigen::Ref<const MatrixXdR> &x) -> Eigen::MatrixXd {
115 return x.llt().matrixL();
116 });
117
118 // test_eigen_ref_mutators
119 // Mutators: these add some value to the given element using Eigen, but Eigen should be mapping
120 // into the numpy array data and so the result should show up there. There are three versions:
121 // one that works on a contiguous-row matrix (numpy's default), one for a contiguous-column
122 // matrix, and one for any matrix.
123 auto add_rm = [](Eigen::Ref<MatrixXdR> x, int r, int c, double v) { x(r, c) += v; };
124 auto add_cm = [](Eigen::Ref<Eigen::MatrixXd> x, int r, int c, double v) { x(r, c) += v; };
125
126 // Mutators (Eigen maps into numpy variables):
127 m.def("add_rm", add_rm); // Only takes row-contiguous
128 m.def("add_cm", add_cm); // Only takes column-contiguous
129 // Overloaded versions that will accept either row or column contiguous:
130 m.def("add1", add_rm);
131 m.def("add1", add_cm);
132 m.def("add2", add_cm);
133 m.def("add2", add_rm);
134 // This one accepts a matrix of any stride:
135 m.def("add_any",
136 [](py::EigenDRef<Eigen::MatrixXd> x, int r, int c, double v) { x(r, c) += v; });
137
138 // Return mutable references (numpy maps into eigen variables)
139 m.def("get_cm_ref", []() { return Eigen::Ref<Eigen::MatrixXd>(get_cm()); });
140 m.def("get_rm_ref", []() { return Eigen::Ref<MatrixXdR>(get_rm()); });
141 // The same references, but non-mutable (numpy maps into eigen variables, but is !writeable)
142 m.def("get_cm_const_ref", []() { return Eigen::Ref<const Eigen::MatrixXd>(get_cm()); });
143 m.def("get_rm_const_ref", []() { return Eigen::Ref<const MatrixXdR>(get_rm()); });
144
145 m.def("reset_refs", reset_refs); // Restores get_{cm,rm}_ref to original values
146
147 // Increments and returns ref to (same) matrix
148 m.def(
149 "incr_matrix",
150 [](Eigen::Ref<Eigen::MatrixXd> m, double v) {
151 m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);
152 return m;
153 },
154 py::return_value_policy::reference);
155
156 // Same, but accepts a matrix of any strides
157 m.def(
158 "incr_matrix_any",
159 [](py::EigenDRef<Eigen::MatrixXd> m, double v) {
160 m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);
161 return m;
162 },
163 py::return_value_policy::reference);
164
165 // Returns an eigen slice of even rows
166 m.def(
167 "even_rows",
168 [](py::EigenDRef<Eigen::MatrixXd> m) {
169 return py::EigenDMap<Eigen::MatrixXd>(
170 m.data(),
171 (m.rows() + 1) / 2,
172 m.cols(),
173 py::EigenDStride(m.outerStride(), 2 * m.innerStride()));
174 },
175 py::return_value_policy::reference);
176
177 // Returns an eigen slice of even columns
178 m.def(
179 "even_cols",
180 [](py::EigenDRef<Eigen::MatrixXd> m) {
181 return py::EigenDMap<Eigen::MatrixXd>(
182 m.data(),
183 m.rows(),
184 (m.cols() + 1) / 2,
185 py::EigenDStride(2 * m.outerStride(), m.innerStride()));
186 },
187 py::return_value_policy::reference);
188
189 // Returns diagonals: a vector-like object with an inner stride != 1
190 m.def("diagonal", [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal(); });
191 m.def("diagonal_1",
192 [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal<1>(); });
193 m.def("diagonal_n",
194 [](const Eigen::Ref<const Eigen::MatrixXd> &x, int index) { return x.diagonal(index); });
195
196 // Return a block of a matrix (gives non-standard strides)
197 m.def("block",
198 [m](const py::object &x_obj,
199 int start_row,
200 int start_col,
201 int block_rows,
202 int block_cols) {
203 return m.attr("_block")(x_obj, x_obj, start_row, start_col, block_rows, block_cols);
204 });
205
206 m.def(
207 "_block",
208 [](const py::object &x_obj,
209 const Eigen::Ref<const Eigen::MatrixXd> &x,
210 int start_row,
211 int start_col,
212 int block_rows,
213 int block_cols) {
214 // See PR #4217 for background. This test is a bit over the top, but might be useful
215 // as a concrete example to point to when explaining the dangling reference trap.
216 auto i0 = py::make_tuple(0, 0);
217 auto x0_orig = x_obj[*i0].cast<double>();
218 if (x(0, 0) != x0_orig) {
219 throw std::runtime_error(
220 "Something in the type_caster for Eigen::Ref is terribly wrong.");
221 }
222 double x0_mod = x0_orig + 1;
223 x_obj[*i0] = x0_mod;
224 auto copy_detected = (x(0, 0) != x0_mod);
225 x_obj[*i0] = x0_orig;
226 if (copy_detected) {
227 throw std::runtime_error("type_caster for Eigen::Ref made a copy.");
228 }
229 return x.block(start_row, start_col, block_rows, block_cols);
230 },
231 py::keep_alive<0, 1>());
232
233 // test_eigen_return_references, test_eigen_keepalive
234 // return value referencing/copying tests:
235 class ReturnTester {
236 Eigen::MatrixXd mat = create();
237
238 public:
239 ReturnTester() { print_created(this); }
240 ~ReturnTester() { print_destroyed(this); }
241 static Eigen::MatrixXd create() { return Eigen::MatrixXd::Ones(10, 10); }
242 // NOLINTNEXTLINE(readability-const-return-type)
243 static const Eigen::MatrixXd createConst() { return Eigen::MatrixXd::Ones(10, 10); }
244 Eigen::MatrixXd &get() { return mat; }
245 Eigen::MatrixXd *getPtr() { return &mat; }
246 const Eigen::MatrixXd &view() { return mat; }
247 const Eigen::MatrixXd *viewPtr() { return &mat; }
248 Eigen::Ref<Eigen::MatrixXd> ref() { return mat; }
249 Eigen::Ref<const Eigen::MatrixXd> refConst() { return mat; }
250 Eigen::Block<Eigen::MatrixXd> block(int r, int c, int nrow, int ncol) {
251 return mat.block(r, c, nrow, ncol);
252 }
253 Eigen::Block<const Eigen::MatrixXd> blockConst(int r, int c, int nrow, int ncol) const {
254 return mat.block(r, c, nrow, ncol);
255 }
256 py::EigenDMap<Eigen::Matrix2d> corners() {
257 return py::EigenDMap<Eigen::Matrix2d>(
258 mat.data(),
259 py::EigenDStride(mat.outerStride() * (mat.outerSize() - 1),
260 mat.innerStride() * (mat.innerSize() - 1)));
261 }
262 py::EigenDMap<const Eigen::Matrix2d> cornersConst() const {
263 return py::EigenDMap<const Eigen::Matrix2d>(
264 mat.data(),
265 py::EigenDStride(mat.outerStride() * (mat.outerSize() - 1),
266 mat.innerStride() * (mat.innerSize() - 1)));
267 }
268 };
269 using rvp = py::return_value_policy;
270 py::class_<ReturnTester>(m, "ReturnTester")
271 .def(py::init<>())
272 .def_static("create", &ReturnTester::create)
273 .def_static("create_const", &ReturnTester::createConst)
274 .def("get", &ReturnTester::get, rvp::reference_internal)
275 .def("get_ptr", &ReturnTester::getPtr, rvp::reference_internal)
276 .def("view", &ReturnTester::view, rvp::reference_internal)
277 .def("view_ptr", &ReturnTester::view, rvp::reference_internal)
278 .def("copy_get", &ReturnTester::get) // Default rvp: copy
279 .def("copy_view", &ReturnTester::view) // "
280 .def("ref", &ReturnTester::ref) // Default for Ref is to reference
281 .def("ref_const", &ReturnTester::refConst) // Likewise, but const
282 .def("ref_safe", &ReturnTester::ref, rvp::reference_internal)
283 .def("ref_const_safe", &ReturnTester::refConst, rvp::reference_internal)
284 .def("copy_ref", &ReturnTester::ref, rvp::copy)
285 .def("copy_ref_const", &ReturnTester::refConst, rvp::copy)
286 .def("block", &ReturnTester::block)
287 .def("block_safe", &ReturnTester::block, rvp::reference_internal)
288 .def("block_const", &ReturnTester::blockConst, rvp::reference_internal)
289 .def("copy_block", &ReturnTester::block, rvp::copy)
290 .def("corners", &ReturnTester::corners, rvp::reference_internal)
291 .def("corners_const", &ReturnTester::cornersConst, rvp::reference_internal);
292
293 // test_special_matrix_objects
294 // Returns a DiagonalMatrix with diagonal (1,2,3,...)
295 m.def("incr_diag", [](int k) {
296 Eigen::DiagonalMatrix<int, Eigen::Dynamic> m(k);
297 for (int i = 0; i < k; i++) {
298 m.diagonal()[i] = i + 1;
299 }
300 return m;
301 });
302
303 // Returns a SelfAdjointView referencing the lower triangle of m
304 m.def("symmetric_lower",
305 [](const Eigen::MatrixXi &m) { return m.selfadjointView<Eigen::Lower>(); });
306 // Returns a SelfAdjointView referencing the lower triangle of m
307 m.def("symmetric_upper",
308 [](const Eigen::MatrixXi &m) { return m.selfadjointView<Eigen::Upper>(); });
309
310 // Test matrix for various functions below.
311 Eigen::MatrixXf mat(5, 6);
312 mat << 0, 3, 0, 0, 0, 11, 22, 0, 0, 0, 17, 11, 7, 5, 0, 1, 0, 11, 0, 0, 0, 0, 0, 11, 0, 0, 14,
313 0, 8, 11;
314
315 // test_fixed, and various other tests
316 m.def("fixed_r", [mat]() -> FixedMatrixR { return FixedMatrixR(mat); });
317 // Our Eigen does a hack which respects constness through the numpy writeable flag.
318 // Therefore, the const return actually affects this type despite being an rvalue.
319 // NOLINTNEXTLINE(readability-const-return-type)
320 m.def("fixed_r_const", [mat]() -> const FixedMatrixR { return FixedMatrixR(mat); });
321 m.def("fixed_c", [mat]() -> FixedMatrixC { return FixedMatrixC(mat); });
322 m.def("fixed_copy_r", [](const FixedMatrixR &m) -> FixedMatrixR { return m; });
323 m.def("fixed_copy_c", [](const FixedMatrixC &m) -> FixedMatrixC { return m; });
324 // test_mutator_descriptors
325 m.def("fixed_mutator_r", [](const Eigen::Ref<FixedMatrixR> &) {});
326 m.def("fixed_mutator_c", [](const Eigen::Ref<FixedMatrixC> &) {});
327 m.def("fixed_mutator_a", [](const py::EigenDRef<FixedMatrixC> &) {});
328 // test_dense
329 m.def("dense_r", [mat]() -> DenseMatrixR { return DenseMatrixR(mat); });
330 m.def("dense_c", [mat]() -> DenseMatrixC { return DenseMatrixC(mat); });
331 m.def("dense_copy_r", [](const DenseMatrixR &m) -> DenseMatrixR { return m; });
332 m.def("dense_copy_c", [](const DenseMatrixC &m) -> DenseMatrixC { return m; });
333 // test_sparse, test_sparse_signature
334 m.def("sparse_r", [mat]() -> SparseMatrixR {
335 // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
336 return Eigen::SparseView<Eigen::MatrixXf>(mat);
337 });
338 m.def("sparse_c",
339 [mat]() -> SparseMatrixC { return Eigen::SparseView<Eigen::MatrixXf>(mat); });
340 m.def("sparse_copy_r", [](const SparseMatrixR &m) -> SparseMatrixR { return m; });
341 m.def("sparse_copy_c", [](const SparseMatrixC &m) -> SparseMatrixC { return m; });
342 // test_partially_fixed
343 m.def("partial_copy_four_rm_r", [](const FourRowMatrixR &m) -> FourRowMatrixR { return m; });
344 m.def("partial_copy_four_rm_c", [](const FourColMatrixR &m) -> FourColMatrixR { return m; });
345 m.def("partial_copy_four_cm_r", [](const FourRowMatrixC &m) -> FourRowMatrixC { return m; });
346 m.def("partial_copy_four_cm_c", [](const FourColMatrixC &m) -> FourColMatrixC { return m; });
347
348 // test_cpp_casting
349 // Test that we can cast a numpy object to a Eigen::MatrixXd explicitly
350 m.def("cpp_copy", [](py::handle m) { return m.cast<Eigen::MatrixXd>()(1, 0); });
351 m.def("cpp_ref_c", [](py::handle m) { return m.cast<Eigen::Ref<Eigen::MatrixXd>>()(1, 0); });
352 m.def("cpp_ref_r", [](py::handle m) { return m.cast<Eigen::Ref<MatrixXdR>>()(1, 0); });
353 m.def("cpp_ref_any",
354 [](py::handle m) { return m.cast<py::EigenDRef<Eigen::MatrixXd>>()(1, 0); });
355
356 // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
357
358 // test_nocopy_wrapper
359 // Test that we can prevent copying into an argument that would normally copy: First a version
360 // that would allow copying (if types or strides don't match) for comparison:
361 m.def("get_elem", &get_elem);
362 // Now this alternative that calls the tells pybind to fail rather than copy:
363 m.def(
364 "get_elem_nocopy",
365 [](const Eigen::Ref<const Eigen::MatrixXd> &m) -> double { return get_elem(m); },
366 py::arg{}.noconvert());
367 // Also test a row-major-only no-copy const ref:
368 m.def(
369 "get_elem_rm_nocopy",
370 [](Eigen::Ref<const Eigen::Matrix<long, -1, -1, Eigen::RowMajor>> &m) -> long {
371 return m(2, 1);
372 },
373 py::arg{}.noconvert());
374
375 // test_issue738, test_zero_length
376 // Issue #738: 1×N or N×1 2D matrices were neither accepted nor properly copied with an
377 // incompatible stride value on the length-1 dimension--but that should be allowed (without
378 // requiring a copy!) because the stride value can be safely ignored on a size-1 dimension.
379 // Similarly, 0×N or N×0 matrices were not accepted--again, these should be allowed since
380 // they contain no data. This particularly affects numpy ≥ 1.23, which sets the strides to
381 // 0 if any dimension size is 0.
382 m.def("iss738_f1",
383 &adjust_matrix<const Eigen::Ref<const Eigen::MatrixXd> &>,
384 py::arg{}.noconvert());
385 m.def("iss738_f2",
386 &adjust_matrix<const Eigen::Ref<const Eigen::Matrix<double, -1, -1, Eigen::RowMajor>> &>,
387 py::arg{}.noconvert());
388
389 // test_issue1105
390 // Issue #1105: when converting from a numpy two-dimensional (Nx1) or (1xN) value into a dense
391 // eigen Vector or RowVector, the argument would fail to load because the numpy copy would
392 // fail: numpy won't broadcast a Nx1 into a 1-dimensional vector.
393 m.def("iss1105_col", [](const Eigen::VectorXd &) { return true; });
394 m.def("iss1105_row", [](const Eigen::RowVectorXd &) { return true; });
395
396 // test_named_arguments
397 // Make sure named arguments are working properly:
398 m.def(
399 "matrix_multiply",
400 [](const py::EigenDRef<const Eigen::MatrixXd> &A,
401 const py::EigenDRef<const Eigen::MatrixXd> &B) -> Eigen::MatrixXd {
402 if (A.cols() != B.rows()) {
403 throw std::domain_error("Nonconformable matrices!");
404 }
405 return A * B;
406 },
407 py::arg("A"),
408 py::arg("B"));
409
410 // test_custom_operator_new
411 py::class_<CustomOperatorNew>(m, "CustomOperatorNew")
412 .def(py::init<>())
413 .def_readonly("a", &CustomOperatorNew::a)
414 .def_readonly("b", &CustomOperatorNew::b);
415
416 // test_eigen_ref_life_support
417 // In case of a failure (the caster's temp array does not live long enough), creating
418 // a new array (np.ones(10)) increases the chances that the temp array will be garbage
419 // collected and/or that its memory will be overridden with different values.
420 m.def("get_elem_direct", [](const Eigen::Ref<const Eigen::VectorXd> &v) {
421 py::module_::import("numpy").attr("ones")(10);
422 return v(5);
423 });
424 m.def("get_elem_indirect", [](std::vector<Eigen::Ref<const Eigen::VectorXd>> v) {
425 py::module_::import("numpy").attr("ones")(10);
426 return v[0](5);
427 });
428}
Reference counting helper.
Definition: object.h:67
void print_created(T *inst, Values &&...values)
void print_destroyed(T *inst, Values &&...values)
#define TEST_SUBMODULE(name, variable)
#define PYBIND11_WARNING_DISABLE_MSVC(name)
Definition: common.h:55
CustomOperatorNew()=default
Eigen::Matrix4d a
Definition: test_eigen.cpp:81
Eigen::Matrix4d b
Definition: test_eigen.cpp:82
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > MatrixXdR
Definition: test_eigen.cpp:25
MatrixXdR & get_rm()
Eigen::MatrixXd adjust_matrix(MatrixArgType m)
void reset_ref(M &x)
void reset_refs()
double get_elem(const Eigen::Ref< const Eigen::MatrixXd > &m)
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > MatrixXdR
Eigen::MatrixXd & get_cm()