py_vector.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #include <Eigen/Dense>
  2. #include <Eigen/Sparse>
  3. #include "python.h"
  4. /// Creates Python bindings for a dynamic Eigen matrix
  5. template <typename Type>
  6. py::class_<Type> bind_eigen_2(py::module &m, const char *name,
  7. py::object parent = py::object()) {
  8. typedef typename Type::Scalar Scalar;
  9. /* Many Eigen functions are templated and can't easily be referenced using
  10. a function pointer, thus a big portion of the binding code below
  11. instantiates Eigen code using small anonymous wrapper functions */
  12. py::class_<Type> matrix(m, name, parent);
  13. matrix
  14. /* Constructors */
  15. .def(py::init<>())
  16. .def(py::init<size_t, size_t>())
  17. .def("__init__", [](Type &m, Scalar f) {
  18. new (&m) Type(1, 1);
  19. m(0, 0) = f;
  20. })
  21. .def("__init__", [](Type &m, py::buffer b) {
  22. py::buffer_info info = b.request();
  23. if (info.format != py::format_descriptor<Scalar>::value())
  24. throw std::runtime_error("Incompatible buffer format!");
  25. if (info.ndim == 1) {
  26. new (&m) Type(info.shape[0], 1);
  27. memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  28. } else if (info.ndim == 2) {
  29. if (info.strides[0] == sizeof(Scalar)) {
  30. new (&m) Type(info.shape[0], info.shape[1]);
  31. memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  32. } else {
  33. new (&m) Type(info.shape[1], info.shape[0]);
  34. memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  35. m.transposeInPlace();
  36. }
  37. } else {
  38. throw std::runtime_error("Incompatible buffer dimension!");
  39. }
  40. })
  41. /* Size query functions */
  42. .def("size", [](const Type &m) { return m.size(); })
  43. .def("cols", [](const Type &m) { return m.cols(); })
  44. .def("rows", [](const Type &m) { return m.rows(); })
  45. /* Extract rows and colums */
  46. .def("col", [](const Type &m, int i) {
  47. if (i<0 || i>=m.cols())
  48. throw std::runtime_error("Column index out of bound.");
  49. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(m.col(i));
  50. })
  51. .def("row", [](const Type &m, int i) {
  52. if (i<0 || i>=m.rows())
  53. throw std::runtime_error("Row index out of bound.");
  54. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(m.row(i));
  55. })
  56. /* Initialization */
  57. .def("setZero", [](Type &m) { m.setZero(); })
  58. .def("setIdentity", [](Type &m) { m.setIdentity(); })
  59. .def("setConstant", [](Type &m, Scalar value) { m.setConstant(value); })
  60. /* Resizing */
  61. .def("resize", [](Type &m, size_t s0, size_t s1) { m.resize(s0, s1); })
  62. .def("resizeLike", [](Type &m, const Type &m2) { m.resizeLike(m2); })
  63. .def("conservativeResize", [](Type &m, size_t s0, size_t s1) { m.conservativeResize(s0, s1); })
  64. /* Component-wise operations */
  65. .def("cwiseAbs", &Type::cwiseAbs)
  66. .def("cwiseAbs2", &Type::cwiseAbs2)
  67. .def("cwiseSqrt", &Type::cwiseSqrt)
  68. .def("cwiseInverse", &Type::cwiseInverse)
  69. .def("cwiseMin", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMin(m2); })
  70. .def("cwiseMax", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMax(m2); })
  71. .def("cwiseMin", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMin(s); })
  72. .def("cwiseMax", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMax(s); })
  73. .def("cwiseProduct", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseProduct(m2); })
  74. .def("cwiseQuotient", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseQuotient(m2); })
  75. /* Row and column-wise operations */
  76. .def("rowwiseSum", [](const Type &m) {return Type(m.rowwise().sum());} )
  77. .def("rowwiseProd", [](const Type &m) {return Type(m.rowwise().prod());} )
  78. .def("rowwiseMean", [](const Type &m) {return Type(m.rowwise().mean());} )
  79. .def("rowwiseNorm", [](const Type &m) {return Type(m.rowwise().norm());} )
  80. .def("rowwiseMinCoeff", [](const Type &m) {return Type(m.rowwise().minCoeff());} )
  81. .def("rowwiseMaxCoeff", [](const Type &m) {return Type(m.rowwise().maxCoeff());} )
  82. .def("colwiseSum", [](const Type &m) {return Type(m.colwise().sum());} )
  83. .def("colwiseProd", [](const Type &m) {return Type(m.colwise().prod());} )
  84. .def("colwiseMean", [](const Type &m) {return Type(m.colwise().mean());} )
  85. .def("colwiseNorm", [](const Type &m) {return Type(m.colwise().norm());} )
  86. .def("colwiseMinCoeff", [](const Type &m) {return Type(m.colwise().minCoeff());} )
  87. .def("colwiseMaxCoeff", [](const Type &m) {return Type(m.colwise().maxCoeff());} )
  88. /* Arithmetic operators (def_cast forcefully casts the result back to a
  89. Type to avoid type issues with Eigen's crazy expression templates) */
  90. .def_cast(-py::self)
  91. .def_cast(py::self + py::self)
  92. .def_cast(py::self - py::self)
  93. .def_cast(py::self * py::self)
  94. // .def_cast(py::self - Scalar())
  95. // .def_cast(py::self * Scalar())
  96. // .def_cast(py::self / Scalar())
  97. .def("__mul__", []
  98. (const Type &a, const Scalar& b)
  99. {
  100. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  101. })
  102. .def("__rmul__", [](const Type& a, const Scalar& b)
  103. {
  104. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  105. })
  106. .def("__add__", []
  107. (const Type &a, const Scalar& b)
  108. {
  109. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a.array() + b);
  110. })
  111. .def("__radd__", [](const Type& a, const Scalar& b)
  112. {
  113. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b + a.array());
  114. })
  115. .def("__sub__", []
  116. (const Type &a, const Scalar& b)
  117. {
  118. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a.array() - b);
  119. })
  120. .def("__rsub__", [](const Type& a, const Scalar& b)
  121. {
  122. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b - a.array());
  123. })
  124. .def("__div__", []
  125. (const Type &a, const Scalar& b)
  126. {
  127. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a / b);
  128. })
  129. .def("__truediv__", []
  130. (const Type &a, const Scalar& b)
  131. {
  132. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a / b);
  133. })
  134. /* Arithmetic in-place operators */
  135. .def_cast(py::self += py::self)
  136. .def_cast(py::self -= py::self)
  137. .def_cast(py::self *= py::self)
  138. // .def_cast(py::self *= Scalar())
  139. // .def_cast(py::self /= Scalar())
  140. /* Comparison operators */
  141. .def(py::self == py::self)
  142. .def(py::self != py::self)
  143. .def("transposeInPlace", [](Type &m) { m.transposeInPlace(); })
  144. /* Other transformations */
  145. .def("transpose", [](Type &m) -> Type { return m.transpose(); })
  146. /* Python protocol implementations */
  147. .def("__repr__", [](const Type &v) {
  148. std::ostringstream oss;
  149. oss << v;
  150. return oss.str();
  151. })
  152. .def("__getitem__", [](const Type &m, std::pair<size_t, size_t> i) {
  153. if (i.first >= (size_t) m.rows() || i.second >= (size_t) m.cols())
  154. throw py::index_error();
  155. return m(i.first, i.second);
  156. })
  157. .def("__setitem__", [](Type &m, std::pair<size_t, size_t> i, Scalar v) {
  158. if (i.first >= (size_t) m.rows() || i.second >= (size_t) m.cols())
  159. throw py::index_error();
  160. m(i.first, i.second) = v;
  161. })
  162. /* Buffer access for interacting with NumPy */
  163. .def_buffer([](Type &m) -> py::buffer_info {
  164. return py::buffer_info(
  165. m.data(), /* Pointer to buffer */
  166. sizeof(Scalar), /* Size of one scalar */
  167. /* Python struct-style format descriptor */
  168. py::format_descriptor<Scalar>::value(),
  169. 2, /* Number of dimensions */
  170. { (size_t) m.rows(), /* Buffer dimensions */
  171. (size_t) m.cols() },
  172. { sizeof(Scalar), /* Strides (in bytes) for each index */
  173. sizeof(Scalar) * m.rows() }
  174. );
  175. })
  176. /* Static initializers */
  177. .def_static("Zero", [](size_t n, size_t m) { return Type(Type::Zero(n, m)); })
  178. .def_static("Ones", [](size_t n, size_t m) { return Type(Type::Ones(n, m)); })
  179. .def_static("Constant", [](size_t n, size_t m, Scalar value) { return Type(Type::Constant(n, m, value)); })
  180. .def_static("Identity", [](size_t n, size_t m) { return Type(Type::Identity(n, m)); })
  181. .def("MapMatrix", [](const Type& m, size_t r, size_t c)
  182. {
  183. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>>(m.data(),r,c));
  184. })
  185. ;
  186. return matrix;
  187. }
  188. /// Creates Python bindings for a dynamic Eigen sparse order-2 tensor (i.e. a matrix)
  189. template <typename Type>
  190. py::class_<Type> bind_eigen_sparse_2(py::module &m, const char *name,
  191. py::object parent = py::object()) {
  192. typedef typename Type::Scalar Scalar;
  193. /* Many Eigen functions are templated and can't easily be referenced using
  194. a function pointer, thus a big portion of the binding code below
  195. instantiates Eigen code using small anonymous wrapper functions */
  196. py::class_<Type> matrix(m, name, parent);
  197. matrix
  198. /* Constructors */
  199. .def(py::init<>())
  200. .def(py::init<size_t, size_t>())
  201. // .def("__init__", [](Type &m, Scalar f) {
  202. // new (&m) Type(1, 1);
  203. // m(0, 0) = f;
  204. // })
  205. // .def("__init__", [](Type &m, py::buffer b) {
  206. // py::buffer_info info = b.request();
  207. // if (info.format != py::format_descriptor<Scalar>::value())
  208. // throw std::runtime_error("Incompatible buffer format!");
  209. // if (info.ndim == 1) {
  210. // new (&m) Type(info.shape[0], 1);
  211. // memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  212. // } else if (info.ndim == 2) {
  213. // if (info.strides[0] == sizeof(Scalar)) {
  214. // new (&m) Type(info.shape[0], info.shape[1]);
  215. // memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  216. // } else {
  217. // new (&m) Type(info.shape[1], info.shape[0]);
  218. // memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  219. // m.transposeInPlace();
  220. // }
  221. // } else {
  222. // throw std::runtime_error("Incompatible buffer dimension!");
  223. // }
  224. // })
  225. /* Size query functions */
  226. .def("size", [](const Type &m) { return m.size(); })
  227. .def("cols", [](const Type &m) { return m.cols(); })
  228. .def("rows", [](const Type &m) { return m.rows(); })
  229. /* Initialization */
  230. // .def("setZero", [](Type &m) { m.setZero(); })
  231. // .def("setIdentity", [](Type &m) { m.setIdentity(); })
  232. // .def("setConstant", [](Type &m, Scalar value) { m.setConstant(value); })
  233. /* Resizing */
  234. // .def("resize", [](Type &m, size_t s0, size_t s1) { m.resize(s0, s1); })
  235. // .def("resizeLike", [](Type &m, const Type &m2) { m.resizeLike(m2); })
  236. // .def("conservativeResize", [](Type &m, size_t s0, size_t s1) { m.conservativeResize(s0, s1); })
  237. /* Component-wise operations */
  238. // .def("cwiseAbs", &Type::cwiseAbs)
  239. // .def("cwiseAbs2", &Type::cwiseAbs2)
  240. // .def("cwiseSqrt", &Type::cwiseSqrt)
  241. // .def("cwiseInverse", &Type::cwiseInverse)
  242. // .def("cwiseMin", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMin(m2); })
  243. // .def("cwiseMax", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMax(m2); })
  244. // .def("cwiseMin", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMin(s); })
  245. // .def("cwiseMax", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMax(s); })
  246. // .def("cwiseProduct", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseProduct(m2); })
  247. // .def("cwiseQuotient", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseQuotient(m2); })
  248. /* Arithmetic operators (def_cast forcefully casts the result back to a
  249. Type to avoid type issues with Eigen's crazy expression templates) */
  250. .def_cast(-py::self)
  251. .def_cast(py::self + py::self)
  252. .def_cast(py::self - py::self)
  253. .def_cast(py::self * py::self)
  254. .def_cast(py::self * Scalar())
  255. // Special case, sparse * dense produces a dense matrix
  256. .def("__mul__", []
  257. (const Type &a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  258. {
  259. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  260. })
  261. .def("__rmul__", [](const Type& a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  262. {
  263. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  264. })
  265. //.def(py::self * Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>())
  266. // .def_cast(py::self / Scalar())
  267. /* Arithmetic in-place operators */
  268. // .def_cast(py::self += py::self)
  269. // .def_cast(py::self -= py::self)
  270. // .def_cast(py::self *= py::self)
  271. // .def_cast(py::self *= Scalar())
  272. // .def_cast(py::self /= Scalar())
  273. /* Comparison operators */
  274. // .def(py::self == py::self)
  275. // .def(py::self != py::self)
  276. // .def("transposeInPlace", [](Type &m) { m.transposeInPlace(); })
  277. // /* Other transformations */
  278. // .def("transpose", [](Type &m) -> Type { return m.transpose(); })
  279. /* Python protocol implementations */
  280. .def("__repr__", [](const Type &v) {
  281. std::ostringstream oss;
  282. oss << v;
  283. return oss.str();
  284. })
  285. // .def("__getitem__", [](const Type &m, std::pair<size_t, size_t> i) {
  286. // if (i.first >= (size_t) m.rows() || i.second >= (size_t) m.cols())
  287. // throw py::index_error();
  288. // return m(i.first, i.second);
  289. // })
  290. // .def("__setitem__", [](Type &m, std::pair<size_t, size_t> i, Scalar v) {
  291. // if (i.first >= (size_t) m.rows() || i.second >= (size_t) m.cols())
  292. // throw py::index_error();
  293. // m(i.first, i.second) = v;
  294. // })
  295. // /* Buffer access for interacting with NumPy */
  296. // .def_buffer([](Type &m) -> py::buffer_info {
  297. // return py::buffer_info(
  298. // m.data(), /* Pointer to buffer */
  299. // sizeof(Scalar), /* Size of one scalar */
  300. // /* Python struct-style format descriptor */
  301. // py::format_descriptor<Scalar>::value(),
  302. // 2, /* Number of dimensions */
  303. // { (size_t) m.rows(), /* Buffer dimensions */
  304. // (size_t) m.cols() },
  305. // { sizeof(Scalar), /* Strides (in bytes) for each index */
  306. // sizeof(Scalar) * m.rows() }
  307. // );
  308. // })
  309. /* Static initializers */
  310. // .def_static("Zero", [](size_t n, size_t m) { return Type(Type::Zero(n, m)); })
  311. // .def_static("Ones", [](size_t n, size_t m) { return Type(Type::Ones(n, m)); })
  312. // .def_static("Constant", [](size_t n, size_t m, Scalar value) { return Type(Type::Constant(n, m, value)); })
  313. // .def_static("Identity", [](size_t n, size_t m) { return Type(Type::Identity(n, m)); })
  314. .def("toCOO",[](const Type& m)
  315. {
  316. Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> t(m.nonZeros(),3);
  317. int count = 0;
  318. for (int k=0; k<m.outerSize(); ++k)
  319. for (typename Type::InnerIterator it(m,k); it; ++it)
  320. t.row(count++) << it.row(), it.col(), it.value();
  321. return t;
  322. })
  323. .def("fromCOO",[](Type& m, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& t, int rows, int cols)
  324. {
  325. typedef Eigen::Triplet<Scalar> T;
  326. std::vector<T> tripletList;
  327. tripletList.reserve(t.rows());
  328. for(unsigned i=0;i<t.rows();++i)
  329. tripletList.push_back(T(round(t(i,0)),round(t(i,1)),t(i,2)));
  330. if (rows == -1)
  331. rows = t.col(0).maxCoeff()+1;
  332. if (cols == -1)
  333. cols = t.col(1).maxCoeff()+1;
  334. m.resize(rows,cols);
  335. m.setFromTriplets(tripletList.begin(), tripletList.end());
  336. }, py::arg("t"), py::arg("rows") = -1, py::arg("cols") = -1)
  337. ;
  338. return matrix;
  339. }
  340. void python_export_vector(py::module &m) {
  341. py::module me = m.def_submodule(
  342. "eigen", "Wrappers for Eigen types");
  343. /* Bindings for VectorXd */
  344. // bind_eigen_1<Eigen::VectorXd> (me, "VectorXd");
  345. // py::implicitly_convertible<py::buffer, Eigen::VectorXd>();
  346. // py::implicitly_convertible<double, Eigen::VectorXd>();
  347. /* Bindings for VectorXi */
  348. // bind_eigen_1<Eigen::VectorXi> (me, "VectorXi");
  349. // py::implicitly_convertible<py::buffer, Eigen::VectorXi>();
  350. // py::implicitly_convertible<double, Eigen::VectorXi>();
  351. /* Bindings for MatrixXd */
  352. bind_eigen_2<Eigen::MatrixXd> (me, "MatrixXd");
  353. //py::implicitly_convertible<py::buffer, Eigen::MatrixXd>();
  354. //py::implicitly_convertible<double, Eigen::MatrixXd>();
  355. /* Bindings for MatrixXi */
  356. bind_eigen_2<Eigen::MatrixXi> (me, "MatrixXi");
  357. // py::implicitly_convertible<py::buffer, Eigen::MatrixXi>();
  358. //py::implicitly_convertible<double, Eigen::MatrixXi>();
  359. /* Bindings for MatrixXuc */
  360. bind_eigen_2<Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> > (me, "MatrixXuc");
  361. // py::implicitly_convertible<py::buffer, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> >();
  362. // py::implicitly_convertible<double, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> >();
  363. // /* Bindings for Vector3d */
  364. // auto vector3 = bind_eigen_1_3<Eigen::Vector3d>(me, "Vector3d");
  365. // vector3
  366. // .def("norm", [](const Eigen::Vector3d &v) { return v.norm(); })
  367. // .def("squaredNorm", [](const Eigen::Vector3d &v) { return v.squaredNorm(); })
  368. // .def("normalize", [](Eigen::Vector3d &v) { v.normalize(); })
  369. // .def("normalized", [](const Eigen::Vector3d &v) -> Eigen::Vector3d { return v.normalized(); })
  370. // .def("dot", [](const Eigen::Vector3d &v1, const Eigen::Vector3d &v2) { return v1.dot(v2); })
  371. // .def("cross", [](const Eigen::Vector3d &v1, const Eigen::Vector3d &v2) -> Eigen::Vector3d { return v1.cross(v2); })
  372. // .def_property("x", [](const Eigen::Vector3d &v) -> double { return v.x(); },
  373. // [](Eigen::Vector3d &v, double x) { v.x() = x; }, "X coordinate")
  374. // .def_property("y", [](const Eigen::Vector3d &v) -> double { return v.y(); },
  375. // [](Eigen::Vector3d &v, double y) { v.y() = y; }, "Y coordinate")
  376. // .def_property("z", [](const Eigen::Vector3d &v) -> double { return v.z(); },
  377. // [](Eigen::Vector3d &v, double z) { v.z() = z; }, "Z coordinate");
  378. //
  379. // py::implicitly_convertible<py::buffer, Eigen::Vector3d>();
  380. // py::implicitly_convertible<double, Eigen::Vector3d>();
  381. /* Bindings for SparseMatrix<double> */
  382. bind_eigen_sparse_2< Eigen::SparseMatrix<double> > (me, "SparseMatrixd");
  383. /* Bindings for SparseMatrix<int> */
  384. bind_eigen_sparse_2< Eigen::SparseMatrix<int> > (me, "SparseMatrixi");
  385. }