py_vector.cpp 20 KB

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