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