blob: 20be0aa11ea8a94ac8a723903f8f6373564128ab [file] [log] [blame]
Wenzel Jakob9e0a0562016-05-05 20:33:54 +02001/*
Dean Moldovana0c1ccf2016-08-12 13:50:00 +02002 tests/eigen.cpp -- automatic conversion of Eigen types
Wenzel Jakob9e0a0562016-05-05 20:33:54 +02003
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
Dean Moldovana0c1ccf2016-08-12 13:50:00 +020010#include "pybind11_tests.h"
Jason Rhinelander17d02832017-01-16 20:35:14 -050011#include "constructor_stats.h"
Wenzel Jakob9e0a0562016-05-05 20:33:54 +020012#include <pybind11/eigen.h>
Dean Moldovan30f6c3b2017-06-26 23:20:39 +020013#include <pybind11/stl.h>
Jason Rhinelander5fd50742016-08-03 16:50:22 -040014#include <Eigen/Cholesky>
Wenzel Jakob9e0a0562016-05-05 20:33:54 +020015
Jason Rhinelander17d02832017-01-16 20:35:14 -050016using MatrixXdR = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
Ben Northb063e642016-07-05 20:01:11 +010017
Ben Northb063e642016-07-05 20:01:11 +010018
Ben North3e0e7792016-07-05 21:00:05 +010019
Jason Rhinelander17d02832017-01-16 20:35:14 -050020// Sets/resets a testing reference matrix to have values of 10*r + c, where r and c are the
21// (1-based) row/column number.
22template <typename M> void reset_ref(M &x) {
23 for (int i = 0; i < x.rows(); i++) for (int j = 0; j < x.cols(); j++)
24 x(i, j) = 11 + 10*i + j;
25}
Jason Rhinelander5fd50742016-08-03 16:50:22 -040026
Jason Rhinelander17d02832017-01-16 20:35:14 -050027// Returns a static, column-major matrix
28Eigen::MatrixXd &get_cm() {
29 static Eigen::MatrixXd *x;
30 if (!x) {
31 x = new Eigen::MatrixXd(3, 3);
32 reset_ref(*x);
33 }
34 return *x;
35}
36// Likewise, but row-major
37MatrixXdR &get_rm() {
38 static MatrixXdR *x;
39 if (!x) {
40 x = new MatrixXdR(3, 3);
41 reset_ref(*x);
42 }
43 return *x;
44}
45// Resets the values of the static matrices returned by get_cm()/get_rm()
46void reset_refs() {
47 reset_ref(get_cm());
48 reset_ref(get_rm());
49}
50
51// Returns element 2,1 from a matrix (used to test copy/nocopy)
52double get_elem(Eigen::Ref<const Eigen::MatrixXd> m) { return m(2, 1); };
Ben North3e0e7792016-07-05 21:00:05 +010053
Jason Rhinelanderefa87262017-03-17 14:51:52 -030054
55// Returns a matrix with 10*r + 100*c added to each matrix element (to help test that the matrix
56// reference is referencing rows/columns correctly).
57template <typename MatrixArgType> Eigen::MatrixXd adjust_matrix(MatrixArgType m) {
58 Eigen::MatrixXd ret(m);
59 for (int c = 0; c < m.cols(); c++) for (int r = 0; r < m.rows(); r++)
60 ret(r, c) += 10*r + 100*c;
61 return ret;
62}
63
Dean Moldovan0d765f42017-03-21 01:15:20 +010064struct CustomOperatorNew {
65 CustomOperatorNew() = default;
66
67 Eigen::Matrix4d a = Eigen::Matrix4d::Zero();
68 Eigen::Matrix4d b = Eigen::Matrix4d::Identity();
69
70 EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
71};
72
Jason Rhinelander391c7542017-07-25 16:47:36 -040073TEST_SUBMODULE(eigen, m) {
74 using FixedMatrixR = Eigen::Matrix<float, 5, 6, Eigen::RowMajor>;
75 using FixedMatrixC = Eigen::Matrix<float, 5, 6>;
76 using DenseMatrixR = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
77 using DenseMatrixC = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>;
78 using FourRowMatrixC = Eigen::Matrix<float, 4, Eigen::Dynamic>;
79 using FourColMatrixC = Eigen::Matrix<float, Eigen::Dynamic, 4>;
80 using FourRowMatrixR = Eigen::Matrix<float, 4, Eigen::Dynamic>;
81 using FourColMatrixR = Eigen::Matrix<float, Eigen::Dynamic, 4>;
82 using SparseMatrixR = Eigen::SparseMatrix<float, Eigen::RowMajor>;
83 using SparseMatrixC = Eigen::SparseMatrix<float>;
Wenzel Jakob9e0a0562016-05-05 20:33:54 +020084
Jason Rhinelander3f1ff3f2016-12-12 17:42:52 -050085 m.attr("have_eigen") = true;
Jason Rhinelander52f4be82016-09-03 14:54:22 -040086
Jason Rhinelander391c7542017-07-25 16:47:36 -040087 // various tests
Jason Rhinelander17d02832017-01-16 20:35:14 -050088 m.def("double_col", [](const Eigen::VectorXf &x) -> Eigen::VectorXf { return 2.0f * x; });
89 m.def("double_row", [](const Eigen::RowVectorXf &x) -> Eigen::RowVectorXf { return 2.0f * x; });
Dean Moldovan51439892017-02-28 18:07:51 +010090 m.def("double_complex", [](const Eigen::VectorXcf &x) -> Eigen::VectorXcf { return 2.0f * x; });
Jason Rhinelander17d02832017-01-16 20:35:14 -050091 m.def("double_threec", [](py::EigenDRef<Eigen::Vector3f> x) { x *= 2; });
92 m.def("double_threer", [](py::EigenDRef<Eigen::RowVector3f> x) { x *= 2; });
93 m.def("double_mat_cm", [](Eigen::MatrixXf x) -> Eigen::MatrixXf { return 2.0f * x; });
94 m.def("double_mat_rm", [](DenseMatrixR x) -> DenseMatrixR { return 2.0f * x; });
Wenzel Jakob9e0a0562016-05-05 20:33:54 +020095
Jason Rhinelander391c7542017-07-25 16:47:36 -040096 // test_eigen_ref_to_python
Jason Rhinelander17d02832017-01-16 20:35:14 -050097 // Different ways of passing via Eigen::Ref; the first and second are the Eigen-recommended
98 m.def("cholesky1", [](Eigen::Ref<MatrixXdR> x) -> Eigen::MatrixXd { return x.llt().matrixL(); });
99 m.def("cholesky2", [](const Eigen::Ref<const MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });
100 m.def("cholesky3", [](const Eigen::Ref<MatrixXdR> &x) -> Eigen::MatrixXd { return x.llt().matrixL(); });
101 m.def("cholesky4", [](Eigen::Ref<const MatrixXdR> x) -> Eigen::MatrixXd { return x.llt().matrixL(); });
102
Jason Rhinelander391c7542017-07-25 16:47:36 -0400103 // test_eigen_ref_mutators
Jason Rhinelander17d02832017-01-16 20:35:14 -0500104 // Mutators: these add some value to the given element using Eigen, but Eigen should be mapping into
105 // the numpy array data and so the result should show up there. There are three versions: one that
106 // works on a contiguous-row matrix (numpy's default), one for a contiguous-column matrix, and one
107 // for any matrix.
108 auto add_rm = [](Eigen::Ref<MatrixXdR> x, int r, int c, double v) { x(r,c) += v; };
109 auto add_cm = [](Eigen::Ref<Eigen::MatrixXd> x, int r, int c, double v) { x(r,c) += v; };
110
111 // Mutators (Eigen maps into numpy variables):
112 m.def("add_rm", add_rm); // Only takes row-contiguous
113 m.def("add_cm", add_cm); // Only takes column-contiguous
114 // Overloaded versions that will accept either row or column contiguous:
115 m.def("add1", add_rm);
116 m.def("add1", add_cm);
117 m.def("add2", add_cm);
118 m.def("add2", add_rm);
119 // This one accepts a matrix of any stride:
120 m.def("add_any", [](py::EigenDRef<Eigen::MatrixXd> x, int r, int c, double v) { x(r,c) += v; });
121
122 // Return mutable references (numpy maps into eigen varibles)
123 m.def("get_cm_ref", []() { return Eigen::Ref<Eigen::MatrixXd>(get_cm()); });
124 m.def("get_rm_ref", []() { return Eigen::Ref<MatrixXdR>(get_rm()); });
125 // The same references, but non-mutable (numpy maps into eigen variables, but is !writeable)
126 m.def("get_cm_const_ref", []() { return Eigen::Ref<const Eigen::MatrixXd>(get_cm()); });
127 m.def("get_rm_const_ref", []() { return Eigen::Ref<const MatrixXdR>(get_rm()); });
Jason Rhinelander17d02832017-01-16 20:35:14 -0500128
129 m.def("reset_refs", reset_refs); // Restores get_{cm,rm}_ref to original values
130
131 // Increments and returns ref to (same) matrix
132 m.def("incr_matrix", [](Eigen::Ref<Eigen::MatrixXd> m, double v) {
133 m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);
134 return m;
135 }, py::return_value_policy::reference);
136
137 // Same, but accepts a matrix of any strides
138 m.def("incr_matrix_any", [](py::EigenDRef<Eigen::MatrixXd> m, double v) {
139 m += Eigen::MatrixXd::Constant(m.rows(), m.cols(), v);
140 return m;
141 }, py::return_value_policy::reference);
142
143 // Returns an eigen slice of even rows
144 m.def("even_rows", [](py::EigenDRef<Eigen::MatrixXd> m) {
145 return py::EigenDMap<Eigen::MatrixXd>(
146 m.data(), (m.rows() + 1) / 2, m.cols(),
147 py::EigenDStride(m.outerStride(), 2 * m.innerStride()));
148 }, py::return_value_policy::reference);
149
150 // Returns an eigen slice of even columns
151 m.def("even_cols", [](py::EigenDRef<Eigen::MatrixXd> m) {
152 return py::EigenDMap<Eigen::MatrixXd>(
153 m.data(), m.rows(), (m.cols() + 1) / 2,
154 py::EigenDStride(2 * m.outerStride(), m.innerStride()));
155 }, py::return_value_policy::reference);
Ben Northb063e642016-07-05 20:01:11 +0100156
Jason Rhinelander8657f302016-08-04 13:21:39 -0400157 // Returns diagonals: a vector-like object with an inner stride != 1
158 m.def("diagonal", [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal(); });
159 m.def("diagonal_1", [](const Eigen::Ref<const Eigen::MatrixXd> &x) { return x.diagonal<1>(); });
160 m.def("diagonal_n", [](const Eigen::Ref<const Eigen::MatrixXd> &x, int index) { return x.diagonal(index); });
161
162 // Return a block of a matrix (gives non-standard strides)
163 m.def("block", [](const Eigen::Ref<const Eigen::MatrixXd> &x, int start_row, int start_col, int block_rows, int block_cols) {
164 return x.block(start_row, start_col, block_rows, block_cols);
165 });
166
Jason Rhinelander391c7542017-07-25 16:47:36 -0400167 // test_eigen_return_references, test_eigen_keepalive
Jason Rhinelander17d02832017-01-16 20:35:14 -0500168 // return value referencing/copying tests:
169 class ReturnTester {
170 Eigen::MatrixXd mat = create();
171 public:
172 ReturnTester() { print_created(this); }
173 ~ReturnTester() { print_destroyed(this); }
174 static Eigen::MatrixXd create() { return Eigen::MatrixXd::Ones(10, 10); }
175 static const Eigen::MatrixXd createConst() { return Eigen::MatrixXd::Ones(10, 10); }
176 Eigen::MatrixXd &get() { return mat; }
177 Eigen::MatrixXd *getPtr() { return &mat; }
178 const Eigen::MatrixXd &view() { return mat; }
179 const Eigen::MatrixXd *viewPtr() { return &mat; }
180 Eigen::Ref<Eigen::MatrixXd> ref() { return mat; }
181 Eigen::Ref<const Eigen::MatrixXd> refConst() { return mat; }
182 Eigen::Block<Eigen::MatrixXd> block(int r, int c, int nrow, int ncol) { return mat.block(r, c, nrow, ncol); }
183 Eigen::Block<const Eigen::MatrixXd> blockConst(int r, int c, int nrow, int ncol) const { return mat.block(r, c, nrow, ncol); }
184 py::EigenDMap<Eigen::Matrix2d> corners() { return py::EigenDMap<Eigen::Matrix2d>(mat.data(),
185 py::EigenDStride(mat.outerStride() * (mat.outerSize()-1), mat.innerStride() * (mat.innerSize()-1))); }
186 py::EigenDMap<const Eigen::Matrix2d> cornersConst() const { return py::EigenDMap<const Eigen::Matrix2d>(mat.data(),
187 py::EigenDStride(mat.outerStride() * (mat.outerSize()-1), mat.innerStride() * (mat.innerSize()-1))); }
188 };
189 using rvp = py::return_value_policy;
190 py::class_<ReturnTester>(m, "ReturnTester")
191 .def(py::init<>())
192 .def_static("create", &ReturnTester::create)
193 .def_static("create_const", &ReturnTester::createConst)
194 .def("get", &ReturnTester::get, rvp::reference_internal)
195 .def("get_ptr", &ReturnTester::getPtr, rvp::reference_internal)
196 .def("view", &ReturnTester::view, rvp::reference_internal)
197 .def("view_ptr", &ReturnTester::view, rvp::reference_internal)
198 .def("copy_get", &ReturnTester::get) // Default rvp: copy
199 .def("copy_view", &ReturnTester::view) // "
200 .def("ref", &ReturnTester::ref) // Default for Ref is to reference
201 .def("ref_const", &ReturnTester::refConst) // Likewise, but const
202 .def("ref_safe", &ReturnTester::ref, rvp::reference_internal)
203 .def("ref_const_safe", &ReturnTester::refConst, rvp::reference_internal)
204 .def("copy_ref", &ReturnTester::ref, rvp::copy)
205 .def("copy_ref_const", &ReturnTester::refConst, rvp::copy)
206 .def("block", &ReturnTester::block)
207 .def("block_safe", &ReturnTester::block, rvp::reference_internal)
208 .def("block_const", &ReturnTester::blockConst, rvp::reference_internal)
209 .def("copy_block", &ReturnTester::block, rvp::copy)
210 .def("corners", &ReturnTester::corners, rvp::reference_internal)
211 .def("corners_const", &ReturnTester::cornersConst, rvp::reference_internal)
212 ;
213
Jason Rhinelander391c7542017-07-25 16:47:36 -0400214 // test_special_matrix_objects
Jason Rhinelander9ffb3dd2016-08-04 15:24:41 -0400215 // Returns a DiagonalMatrix with diagonal (1,2,3,...)
216 m.def("incr_diag", [](int k) {
217 Eigen::DiagonalMatrix<int, Eigen::Dynamic> m(k);
218 for (int i = 0; i < k; i++) m.diagonal()[i] = i+1;
219 return m;
220 });
221
222 // Returns a SelfAdjointView referencing the lower triangle of m
223 m.def("symmetric_lower", [](const Eigen::MatrixXi &m) {
224 return m.selfadjointView<Eigen::Lower>();
225 });
226 // Returns a SelfAdjointView referencing the lower triangle of m
227 m.def("symmetric_upper", [](const Eigen::MatrixXi &m) {
228 return m.selfadjointView<Eigen::Upper>();
229 });
230
Jason Rhinelander17d02832017-01-16 20:35:14 -0500231 // Test matrix for various functions below.
232 Eigen::MatrixXf mat(5, 6);
233 mat << 0, 3, 0, 0, 0, 11,
234 22, 0, 0, 0, 17, 11,
235 7, 5, 0, 1, 0, 11,
236 0, 0, 0, 0, 0, 11,
237 0, 0, 14, 0, 8, 11;
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200238
Jason Rhinelander391c7542017-07-25 16:47:36 -0400239 // test_fixed, and various other tests
Jason Rhinelander17d02832017-01-16 20:35:14 -0500240 m.def("fixed_r", [mat]() -> FixedMatrixR { return FixedMatrixR(mat); });
241 m.def("fixed_r_const", [mat]() -> const FixedMatrixR { return FixedMatrixR(mat); });
242 m.def("fixed_c", [mat]() -> FixedMatrixC { return FixedMatrixC(mat); });
243 m.def("fixed_copy_r", [](const FixedMatrixR &m) -> FixedMatrixR { return m; });
244 m.def("fixed_copy_c", [](const FixedMatrixC &m) -> FixedMatrixC { return m; });
Jason Rhinelander391c7542017-07-25 16:47:36 -0400245 // test_mutator_descriptors
Jason Rhinelander17d02832017-01-16 20:35:14 -0500246 m.def("fixed_mutator_r", [](Eigen::Ref<FixedMatrixR>) {});
247 m.def("fixed_mutator_c", [](Eigen::Ref<FixedMatrixC>) {});
248 m.def("fixed_mutator_a", [](py::EigenDRef<FixedMatrixC>) {});
Jason Rhinelander391c7542017-07-25 16:47:36 -0400249 // test_dense
Jason Rhinelander17d02832017-01-16 20:35:14 -0500250 m.def("dense_r", [mat]() -> DenseMatrixR { return DenseMatrixR(mat); });
251 m.def("dense_c", [mat]() -> DenseMatrixC { return DenseMatrixC(mat); });
252 m.def("dense_copy_r", [](const DenseMatrixR &m) -> DenseMatrixR { return m; });
253 m.def("dense_copy_c", [](const DenseMatrixC &m) -> DenseMatrixC { return m; });
Jason Rhinelander391c7542017-07-25 16:47:36 -0400254 // test_sparse, test_sparse_signature
Jason Rhinelander17d02832017-01-16 20:35:14 -0500255 m.def("sparse_r", [mat]() -> SparseMatrixR { return Eigen::SparseView<Eigen::MatrixXf>(mat); });
256 m.def("sparse_c", [mat]() -> SparseMatrixC { return Eigen::SparseView<Eigen::MatrixXf>(mat); });
257 m.def("sparse_copy_r", [](const SparseMatrixR &m) -> SparseMatrixR { return m; });
258 m.def("sparse_copy_c", [](const SparseMatrixC &m) -> SparseMatrixC { return m; });
Jason Rhinelander391c7542017-07-25 16:47:36 -0400259 // test_partially_fixed
Jason Rhinelander17d02832017-01-16 20:35:14 -0500260 m.def("partial_copy_four_rm_r", [](const FourRowMatrixR &m) -> FourRowMatrixR { return m; });
261 m.def("partial_copy_four_rm_c", [](const FourColMatrixR &m) -> FourColMatrixR { return m; });
262 m.def("partial_copy_four_cm_r", [](const FourRowMatrixC &m) -> FourRowMatrixC { return m; });
263 m.def("partial_copy_four_cm_c", [](const FourColMatrixC &m) -> FourColMatrixC { return m; });
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200264
Jason Rhinelander391c7542017-07-25 16:47:36 -0400265 // test_cpp_casting
Jason Rhinelander17d02832017-01-16 20:35:14 -0500266 // Test that we can cast a numpy object to a Eigen::MatrixXd explicitly
267 m.def("cpp_copy", [](py::handle m) { return m.cast<Eigen::MatrixXd>()(1, 0); });
268 m.def("cpp_ref_c", [](py::handle m) { return m.cast<Eigen::Ref<Eigen::MatrixXd>>()(1, 0); });
269 m.def("cpp_ref_r", [](py::handle m) { return m.cast<Eigen::Ref<MatrixXdR>>()(1, 0); });
270 m.def("cpp_ref_any", [](py::handle m) { return m.cast<py::EigenDRef<Eigen::MatrixXd>>()(1, 0); });
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200271
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200272
Jason Rhinelander391c7542017-07-25 16:47:36 -0400273 // test_nocopy_wrapper
Jason Rhinelander17d02832017-01-16 20:35:14 -0500274 // Test that we can prevent copying into an argument that would normally copy: First a version
275 // that would allow copying (if types or strides don't match) for comparison:
276 m.def("get_elem", &get_elem);
277 // Now this alternative that calls the tells pybind to fail rather than copy:
278 m.def("get_elem_nocopy", [](Eigen::Ref<const Eigen::MatrixXd> m) -> double { return get_elem(m); },
279 py::arg().noconvert());
280 // Also test a row-major-only no-copy const ref:
281 m.def("get_elem_rm_nocopy", [](Eigen::Ref<const Eigen::Matrix<long, -1, -1, Eigen::RowMajor>> &m) -> long { return m(2, 1); },
282 py::arg().noconvert());
Jason Rhinelanderefa87262017-03-17 14:51:52 -0300283
Jason Rhinelander391c7542017-07-25 16:47:36 -0400284 // test_issue738
Jason Rhinelanderefa87262017-03-17 14:51:52 -0300285 // Issue #738: 1xN or Nx1 2D matrices were neither accepted nor properly copied with an
286 // incompatible stride value on the length-1 dimension--but that should be allowed (without
287 // requiring a copy!) because the stride value can be safely ignored on a size-1 dimension.
288 m.def("iss738_f1", &adjust_matrix<const Eigen::Ref<const Eigen::MatrixXd> &>, py::arg().noconvert());
289 m.def("iss738_f2", &adjust_matrix<const Eigen::Ref<const Eigen::Matrix<double, -1, -1, Eigen::RowMajor>> &>, py::arg().noconvert());
Dean Moldovan0d765f42017-03-21 01:15:20 +0100290
Jason Rhinelander6a81dbb2017-09-21 19:09:39 -0300291 // test_issue1105
292 // Issue #1105: when converting from a numpy two-dimensional (Nx1) or (1xN) value into a dense
293 // eigen Vector or RowVector, the argument would fail to load because the numpy copy would fail:
294 // numpy won't broadcast a Nx1 into a 1-dimensional vector.
295 m.def("iss1105_col", [](Eigen::VectorXd) { return true; });
296 m.def("iss1105_row", [](Eigen::RowVectorXd) { return true; });
297
Jason Rhinelander391c7542017-07-25 16:47:36 -0400298 // test_named_arguments
Jason Rhinelandere9e17742017-04-08 19:26:42 -0400299 // Make sure named arguments are working properly:
300 m.def("matrix_multiply", [](const py::EigenDRef<const Eigen::MatrixXd> A, const py::EigenDRef<const Eigen::MatrixXd> B)
301 -> Eigen::MatrixXd {
302 if (A.cols() != B.rows()) throw std::domain_error("Nonconformable matrices!");
303 return A * B;
304 }, py::arg("A"), py::arg("B"));
305
Jason Rhinelander391c7542017-07-25 16:47:36 -0400306 // test_custom_operator_new
Dean Moldovan0d765f42017-03-21 01:15:20 +0100307 py::class_<CustomOperatorNew>(m, "CustomOperatorNew")
308 .def(py::init<>())
309 .def_readonly("a", &CustomOperatorNew::a)
310 .def_readonly("b", &CustomOperatorNew::b);
Dean Moldovan30f6c3b2017-06-26 23:20:39 +0200311
312 // test_eigen_ref_life_support
313 // In case of a failure (the caster's temp array does not live long enough), creating
314 // a new array (np.ones(10)) increases the chances that the temp array will be garbage
315 // collected and/or that its memory will be overridden with different values.
316 m.def("get_elem_direct", [](Eigen::Ref<const Eigen::VectorXd> v) {
317 py::module::import("numpy").attr("ones")(10);
318 return v(5);
319 });
320 m.def("get_elem_indirect", [](std::vector<Eigen::Ref<const Eigen::VectorXd>> v) {
321 py::module::import("numpy").attr("ones")(10);
322 return v[0](5);
323 });
Jason Rhinelander391c7542017-07-25 16:47:36 -0400324}