test_eigen.cpp 16 KB

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