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