py_vector.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. #include <Eigen/Geometry>
  2. #include <Eigen/Dense>
  3. #include <Eigen/Sparse>
  4. #include "../python_shared.h"
  5. /// Creates Python bindings for a dynamic Eigen matrix
  6. template <typename Type>
  7. py::class_<Type> bind_eigen_2(py::module &m, const char *name) {
  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, py::buffer_protocol());
  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>::format())
  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. .def("__init__", [](Type &m, std::vector<std::vector< Scalar> >& b) {
  42. if (b.size() == 0)
  43. {
  44. new (&m) Type(0, 0);
  45. return;
  46. }
  47. // Size checks
  48. unsigned rows = b.size();
  49. unsigned cols = b[0].size();
  50. for (unsigned i=0;i<rows;++i)
  51. if (b[i].size() != cols)
  52. throw std::runtime_error("All rows should have the same size!");
  53. new (&m) Type(rows, cols);
  54. m.resize(rows,cols);
  55. for (unsigned i=0;i<rows;++i)
  56. for (unsigned j=0;j<cols;++j)
  57. m(i,j) = b[i][j];
  58. return;
  59. })
  60. .def("__init__", [](Type &m, std::vector<Scalar>& b) {
  61. if (b.size() == 0)
  62. {
  63. new (&m) Type(0, 0);
  64. return;
  65. }
  66. // Size checks
  67. unsigned rows = b.size();
  68. unsigned cols = 1;
  69. new (&m) Type(rows, cols);
  70. m.resize(rows,cols);
  71. for (unsigned i=0;i<rows;++i)
  72. m(i,0) = b[i];
  73. return;
  74. })
  75. /* Size query functions */
  76. .def("size", [](const Type &m) { return m.size(); })
  77. .def("cols", [](const Type &m) { return m.cols(); })
  78. .def("rows", [](const Type &m) { return m.rows(); })
  79. .def("shape", [](const Type &m) { return std::tuple<int,int>(m.rows(), m.cols()); })
  80. /* Extract rows and colums */
  81. .def("col", [](const Type &m, int i) {
  82. if (i<0 || i>=m.cols())
  83. throw std::runtime_error("Column index out of bound.");
  84. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(m.col(i));
  85. })
  86. .def("row", [](const Type &m, int i) {
  87. if (i<0 || i>=m.rows())
  88. throw std::runtime_error("Row index out of bound.");
  89. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(m.row(i));
  90. })
  91. /* Initialization */
  92. .def("setZero", [](Type &m) { m.setZero(); })
  93. .def("setIdentity", [](Type &m) { m.setIdentity(); })
  94. .def("setConstant", [](Type &m, Scalar value) { m.setConstant(value); })
  95. .def("setRandom", [](Type &m) { m.setRandom(); })
  96. .def("setZero", [](Type &m, const int& r, const int& c) { m.setZero(r,c); })
  97. .def("setIdentity", [](Type &m, const int& r, const int& c) { m.setIdentity(r,c); })
  98. .def("setConstant", [](Type &m, const int& r, const int& c, Scalar value) { m.setConstant(r,c,value); })
  99. .def("setRandom", [](Type &m, const int& r, const int& c) { m.setRandom(r,c); })
  100. .def("setCol", [](Type &m, int i, const Type& v) { m.col(i) = v; })
  101. .def("setRow", [](Type &m, int i, const Type& v) { m.row(i) = v; })
  102. .def("setBlock", [](Type &m, int i, int j, int p, int q, const Type& v) { m.block(i,j,p,q) = v; })
  103. .def("block", [](Type &m, int i, int j, int p, int q) { return Type(m.block(i,j,p,q)); })
  104. .def("rightCols", [](Type &m, const int& k) { return Type(m.rightCols(k)); })
  105. .def("leftCols", [](Type &m, const int& k) { return Type(m.leftCols(k)); })
  106. .def("setLeftCols", [](Type &m, const int& k, const Type& v) { return Type(m.leftCols(k) = v); })
  107. .def("setRightCols", [](Type &m, const int& k, const Type& v) { return Type(m.rightCols(k) = v); })
  108. .def("topRows", [](Type &m, const int& k) { return Type(m.topRows(k)); })
  109. .def("bottomRows", [](Type &m, const int& k) { return Type(m.bottomRows(k)); })
  110. .def("setTopRows", [](Type &m, const int& k, const Type& v) { return Type(m.topRows(k) = v); })
  111. .def("setBottomRows", [](Type &m, const int& k, const Type& v) { return Type(m.bottomRows(k) = v); })
  112. .def("topLeftCorner", [](Type &m, const int& p, const int&q) { return Type(m.topLeftCorner(p,q)); })
  113. .def("bottomLeftCorner", [](Type &m, const int& p, const int&q) { return Type(m.bottomLeftCorner(p,q)); })
  114. .def("topRightCorner", [](Type &m, const int& p, const int&q) { return Type(m.topRightCorner(p,q)); })
  115. .def("bottomRightCorner", [](Type &m, const int& p, const int&q) { return Type(m.bottomRightCorner(p,q)); })
  116. /* Resizing */
  117. .def("resize", [](Type &m, size_t s0, size_t s1) { m.resize(s0, s1); })
  118. .def("resizeLike", [](Type &m, const Type &m2) { m.resizeLike(m2); })
  119. .def("conservativeResize", [](Type &m, size_t s0, size_t s1) { m.conservativeResize(s0, s1); })
  120. .def("mean", [](const Type &m) {return m.mean();})
  121. .def("sum", [](const Type &m) {return m.sum();})
  122. .def("prod", [](const Type &m) {return m.prod();})
  123. .def("trace", [](const Type &m) {return m.trace();})
  124. .def("norm", [](const Type &m) {return m.norm();})
  125. .def("squaredNorm", [](const Type &m) {return m.squaredNorm();})
  126. .def("squaredMean", [](const Type &m) {return m.array().square().mean();})
  127. .def("minCoeff", [](const Type &m) {return m.minCoeff();} )
  128. .def("maxCoeff", [](const Type &m) {return m.maxCoeff();} )
  129. .def("castdouble", [](const Type &m) {return Eigen::MatrixXd(m.template cast<double>());})
  130. .def("castint", [](const Type &m) {return Eigen::MatrixXi(m.template cast<int>());})
  131. /* Component-wise operations */
  132. .def("cwiseAbs", &Type::cwiseAbs)
  133. .def("cwiseAbs2", &Type::cwiseAbs2)
  134. .def("cwiseSqrt", &Type::cwiseSqrt)
  135. .def("cwiseInverse", &Type::cwiseInverse)
  136. .def("cwiseMin", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMin(m2); })
  137. .def("cwiseMax", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMax(m2); })
  138. .def("cwiseMin", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMin(s); })
  139. .def("cwiseMax", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMax(s); })
  140. .def("cwiseProduct", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseProduct(m2); })
  141. .def("cwiseQuotient", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseQuotient(m2); })
  142. /* Row and column-wise operations */
  143. .def("rowwiseSet", [](Type &m, const Type &m2) {return Type(m.rowwise() = Eigen::Matrix<Scalar, 1, Eigen::Dynamic>(m2));} )
  144. .def("rowwiseSum", [](const Type &m) {return Type(m.rowwise().sum());} )
  145. .def("rowwiseProd", [](const Type &m) {return Type(m.rowwise().prod());} )
  146. .def("rowwiseMean", [](const Type &m) {return Type(m.rowwise().mean());} )
  147. .def("rowwiseNorm", [](const Type &m) {return Type(m.rowwise().norm());} )
  148. .def("rowwiseNormalized", [](const Type &m) {return Type(m.rowwise().normalized());} )
  149. .def("rowwiseReverse", [](const Type &m) {return Type(m.rowwise().reverse());} )
  150. .def("rowwiseMinCoeff", [](const Type &m) {return Type(m.rowwise().minCoeff());} )
  151. .def("rowwiseMaxCoeff", [](const Type &m) {return Type(m.rowwise().maxCoeff());} )
  152. .def("colwiseSet", [](Type &m, const Type &m2) {return Type(m.colwise() = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>(m2));} )
  153. .def("colwiseSum", [](const Type &m) {return Type(m.colwise().sum());} )
  154. .def("colwiseProd", [](const Type &m) {return Type(m.colwise().prod());} )
  155. .def("colwiseMean", [](const Type &m) {return Type(m.colwise().mean());} )
  156. .def("colwiseNorm", [](const Type &m) {return Type(m.colwise().norm());} )
  157. .def("colwiseNormalized", [](const Type &m) {return Type(m.colwise().normalized());} )
  158. .def("colwiseReverse", [](const Type &m) {return Type(m.colwise().reverse());} )
  159. .def("colwiseMinCoeff", [](const Type &m) {return Type(m.colwise().minCoeff());} )
  160. .def("colwiseMaxCoeff", [](const Type &m) {return Type(m.colwise().maxCoeff());} )
  161. .def("replicate", [](const Type &m, const int& r, const int& c) {return Type(m.replicate(r,c));} )
  162. .def("asDiagonal", [](const Type &m) {return Eigen::DiagonalMatrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(m.asDiagonal());} )
  163. .def("sparseView", [](Type &m) { return Eigen::SparseMatrix<Scalar>(m.sparseView()); })
  164. /* Arithmetic operators (def_cast forcefully casts the result back to a
  165. Type to avoid type issues with Eigen's crazy expression templates) */
  166. .def_cast(-py::self)
  167. .def_cast(py::self + py::self)
  168. .def_cast(py::self - py::self)
  169. .def_cast(py::self * py::self)
  170. // .def_cast(py::self - Scalar())
  171. // .def_cast(py::self * Scalar())
  172. // .def_cast(py::self / Scalar())
  173. .def("__mul__", []
  174. (const Type &a, const Scalar& b)
  175. {
  176. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  177. })
  178. .def("__rmul__", [](const Type& a, const Scalar& b)
  179. {
  180. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  181. })
  182. .def("__add__", []
  183. (const Type &a, const Scalar& b)
  184. {
  185. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a.array() + b);
  186. })
  187. .def("__radd__", [](const Type& a, const Scalar& b)
  188. {
  189. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b + a.array());
  190. })
  191. .def("__sub__", []
  192. (const Type &a, const Scalar& b)
  193. {
  194. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a.array() - b);
  195. })
  196. .def("__rsub__", [](const Type& a, const Scalar& b)
  197. {
  198. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b - a.array());
  199. })
  200. .def("__div__", []
  201. (const Type &a, const Scalar& b)
  202. {
  203. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a / b);
  204. })
  205. .def("__truediv__", []
  206. (const Type &a, const Scalar& b)
  207. {
  208. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a / b);
  209. })
  210. /* Arithmetic in-place operators */
  211. .def_cast(py::self += py::self)
  212. .def_cast(py::self -= py::self)
  213. .def_cast(py::self *= py::self)
  214. .def_cast(py::self *= Scalar())
  215. .def_cast(py::self /= Scalar())
  216. /* Comparison operators */
  217. .def(py::self == py::self)
  218. .def(py::self != py::self)
  219. .def("__lt__", []
  220. (const Type &a, const Scalar& b) -> Eigen::Matrix<bool,Eigen::Dynamic,Eigen::Dynamic>
  221. {
  222. return Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>(a.array() < b);
  223. })
  224. .def("__gt__", []
  225. (const Type &a, const Scalar& b) -> Eigen::Matrix<bool,Eigen::Dynamic,Eigen::Dynamic>
  226. {
  227. return Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>(a.array() > b);
  228. })
  229. .def("__le__", []
  230. (const Type &a, const Scalar& b) -> Eigen::Matrix<bool,Eigen::Dynamic,Eigen::Dynamic>
  231. {
  232. return Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>(a.array() <= b);
  233. })
  234. .def("__ge__", []
  235. (const Type &a, const Scalar& b) -> Eigen::Matrix<bool,Eigen::Dynamic,Eigen::Dynamic>
  236. {
  237. return Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>(a.array() >= b);
  238. })
  239. .def("transposeInPlace", [](Type &m) { m.transposeInPlace(); })
  240. /* Other transformations */
  241. .def("transpose", [](Type &m) -> Type { return m.transpose(); })
  242. /* Python protocol implementations */
  243. .def("__repr__", [](const Type &v) {
  244. std::ostringstream oss;
  245. oss << v;
  246. return oss.str();
  247. })
  248. .def("__getitem__", [](const Type &m, std::pair<size_t, size_t> i) {
  249. if (i.first >= (size_t) m.rows() || i.second >= (size_t) m.cols())
  250. throw py::index_error();
  251. return m(i.first, i.second);
  252. })
  253. .def("__setitem__", [](Type &m, std::pair<size_t, size_t> i, Scalar v) {
  254. if (i.first >= (size_t) m.rows() || i.second >= (size_t) m.cols())
  255. throw py::index_error();
  256. m(i.first, i.second) = v;
  257. })
  258. .def("__getitem__", [](const Type &m, size_t i) {
  259. if (i >= (size_t) m.size())
  260. throw py::index_error();
  261. return m(i);
  262. })
  263. .def("__setitem__", [](Type &m, size_t i, Scalar v) {
  264. if (i >= (size_t) m.size())
  265. throw py::index_error();
  266. m(i) = v;
  267. })
  268. /* Buffer access for interacting with NumPy */
  269. .def_buffer([](Type &m) -> py::buffer_info {
  270. return py::buffer_info(
  271. m.data(), /* Pointer to buffer */
  272. sizeof(Scalar), /* Size of one scalar */
  273. /* Python struct-style format descriptor */
  274. py::format_descriptor<Scalar>::format(),
  275. 2, /* Number of dimensions */
  276. { (size_t) m.rows(), /* Buffer dimensions */
  277. (size_t) m.cols() },
  278. { sizeof(Scalar), /* Strides (in bytes) for each index */
  279. sizeof(Scalar) * m.rows() }
  280. );
  281. })
  282. /* Static initializers */
  283. .def_static("Zero", [](size_t n, size_t m) { return Type(Type::Zero(n, m)); })
  284. .def_static("Random", [](size_t n, size_t m) { return Type(Type::Random(n, m)); })
  285. .def_static("Ones", [](size_t n, size_t m) { return Type(Type::Ones(n, m)); })
  286. .def_static("Constant", [](size_t n, size_t m, Scalar value) { return Type(Type::Constant(n, m, value)); })
  287. .def_static("Identity", [](size_t n, size_t m) { return Type(Type::Identity(n, m)); })
  288. .def("MapMatrix", [](const Type& m, size_t r, size_t c)
  289. {
  290. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>>(m.data(),r,c));
  291. })
  292. .def("copy", [](const Type &m) { return Type(m); })
  293. ;
  294. return matrix;
  295. }
  296. /// Creates Python bindings for a dynamic Eigen sparse order-2 tensor (i.e. a matrix)
  297. template <typename Type>
  298. py::class_<Type> bind_eigen_sparse_2(py::module &m, const char *name) {
  299. typedef typename Type::Scalar Scalar;
  300. /* Many Eigen functions are templated and can't easily be referenced using
  301. a function pointer, thus a big portion of the binding code below
  302. instantiates Eigen code using small anonymous wrapper functions */
  303. py::class_<Type> matrix(m, name, py::buffer_protocol());
  304. matrix
  305. /* Constructors */
  306. .def(py::init<>())
  307. .def(py::init<size_t, size_t>())
  308. // .def("__init__", [](Type &m, Scalar f) {
  309. // new (&m) Type(1, 1);
  310. // m(0, 0) = f;
  311. // })
  312. // .def("__init__", [](Type &m, py::buffer b) {
  313. // py::buffer_info info = b.request();
  314. // if (info.format != py::format_descriptor<Scalar>::value())
  315. // throw std::runtime_error("Incompatible buffer format!");
  316. // if (info.ndim == 1) {
  317. // new (&m) Type(info.shape[0], 1);
  318. // memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  319. // } else if (info.ndim == 2) {
  320. // if (info.strides[0] == sizeof(Scalar)) {
  321. // new (&m) Type(info.shape[0], info.shape[1]);
  322. // memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  323. // } else {
  324. // new (&m) Type(info.shape[1], info.shape[0]);
  325. // memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  326. // m.transposeInPlace();
  327. // }
  328. // } else {
  329. // throw std::runtime_error("Incompatible buffer dimension!");
  330. // }
  331. // })
  332. /* Size query functions */
  333. .def("size", [](const Type &m) { return m.size(); })
  334. .def("cols", [](const Type &m) { return m.cols(); })
  335. .def("rows", [](const Type &m) { return m.rows(); })
  336. .def("shape", [](const Type &m) { return std::tuple<int,int>(m.rows(), m.cols()); })
  337. /* Initialization */
  338. .def("setZero", [](Type &m) { m.setZero(); })
  339. .def("setIdentity", [](Type &m) { m.setIdentity(); })
  340. .def("transpose", [](Type &m) { return Type(m.transpose()); })
  341. .def("norm", [](Type &m) { return m.norm(); })
  342. /* Resizing */
  343. // .def("resize", [](Type &m, size_t s0, size_t s1) { m.resize(s0, s1); })
  344. // .def("resizeLike", [](Type &m, const Type &m2) { m.resizeLike(m2); })
  345. // .def("conservativeResize", [](Type &m, size_t s0, size_t s1) { m.conservativeResize(s0, s1); })
  346. /* Component-wise operations */
  347. // .def("cwiseAbs", &Type::cwiseAbs)
  348. // .def("cwiseAbs2", &Type::cwiseAbs2)
  349. // .def("cwiseSqrt", &Type::cwiseSqrt)
  350. // .def("cwiseInverse", &Type::cwiseInverse)
  351. // .def("cwiseMin", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMin(m2); })
  352. // .def("cwiseMax", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMax(m2); })
  353. // .def("cwiseMin", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMin(s); })
  354. // .def("cwiseMax", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMax(s); })
  355. // .def("cwiseProduct", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseProduct(m2); })
  356. // .def("cwiseQuotient", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseQuotient(m2); })
  357. /* Arithmetic operators (def_cast forcefully casts the result back to a
  358. Type to avoid type issues with Eigen's crazy expression templates) */
  359. .def_cast(-py::self)
  360. .def_cast(py::self + py::self)
  361. .def_cast(py::self - py::self)
  362. .def_cast(py::self * py::self)
  363. .def_cast(py::self * Scalar())
  364. .def_cast(Scalar() * py::self)
  365. // Special case, sparse * dense produces a dense matrix
  366. // .def("__mul__", []
  367. // (const Type &a, const Scalar& b)
  368. // {
  369. // return Type(a * b);
  370. // })
  371. // .def("__rmul__", [](const Type& a, const Scalar& b)
  372. // {
  373. // return Type(b * a);
  374. // })
  375. .def("__mul__", []
  376. (const Type &a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  377. {
  378. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  379. })
  380. .def("__rmul__", [](const Type& a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  381. {
  382. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  383. })
  384. .def("__mul__", []
  385. (const Type &a, const Eigen::DiagonalMatrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  386. {
  387. return Type(a * b);
  388. })
  389. .def("__rmul__", [](const Type& a, const Eigen::DiagonalMatrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  390. {
  391. return Type(b * a);
  392. })
  393. //.def(py::self * Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>())
  394. // .def_cast(py::self / Scalar())
  395. /* Arithmetic in-place operators */
  396. // .def_cast(py::self += py::self)
  397. // .def_cast(py::self -= py::self)
  398. // .def_cast(py::self *= py::self)
  399. // .def_cast(py::self *= Scalar())
  400. // .def_cast(py::self /= Scalar())
  401. /* Comparison operators */
  402. // .def(py::self == py::self)
  403. // .def(py::self != py::self)
  404. // .def("transposeInPlace", [](Type &m) { m.transposeInPlace(); })
  405. // /* Other transformations */
  406. // .def("transpose", [](Type &m) -> Type { return m.transpose(); })
  407. /* Python protocol implementations */
  408. .def("__repr__", [](const Type &v) {
  409. std::ostringstream oss;
  410. oss << v;
  411. return oss.str();
  412. })
  413. /* Static initializers */
  414. // .def_static("Zero", [](size_t n, size_t m) { return Type(Type::Zero(n, m)); })
  415. // .def_static("Ones", [](size_t n, size_t m) { return Type(Type::Ones(n, m)); })
  416. // .def_static("Constant", [](size_t n, size_t m, Scalar value) { return Type(Type::Constant(n, m, value)); })
  417. // .def_static("Identity", [](size_t n, size_t m) { return Type(Type::Identity(n, m)); })
  418. .def("toCOO",[](const Type& m)
  419. {
  420. Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> t(m.nonZeros(),3);
  421. int count = 0;
  422. for (int k=0; k<m.outerSize(); ++k)
  423. for (typename Type::InnerIterator it(m,k); it; ++it)
  424. t.row(count++) << it.row(), it.col(), it.value();
  425. return t;
  426. })
  427. .def("fromCOO",[](Type& m, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& t, int rows, int cols)
  428. {
  429. typedef Eigen::Triplet<Scalar> T;
  430. std::vector<T> tripletList;
  431. tripletList.reserve(t.rows());
  432. for(unsigned i=0;i<t.rows();++i)
  433. tripletList.push_back(T(round(t(i,0)),round(t(i,1)),t(i,2)));
  434. if (rows == -1)
  435. rows = t.col(0).maxCoeff()+1;
  436. if (cols == -1)
  437. cols = t.col(1).maxCoeff()+1;
  438. m.resize(rows,cols);
  439. m.setFromTriplets(tripletList.begin(), tripletList.end());
  440. }, py::arg("t"), py::arg("rows") = -1, py::arg("cols") = -1)
  441. .def("insert",[](Type& m, const int row, const int col, const Scalar value)
  442. {
  443. return m.insert(row,col) = value;
  444. }, py::arg("row"), py::arg("col"), py::arg("value"))
  445. .def("makeCompressed",[](Type& m)
  446. {
  447. return m.makeCompressed();
  448. })
  449. .def("diagonal", [](const Type &m) {return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(m.diagonal());} )
  450. ;
  451. return matrix;
  452. }
  453. /// Creates Python bindings for a diagonal Eigen sparse order-2 tensor (i.e. a matrix)
  454. template <typename Type>
  455. py::class_<Type> bind_eigen_diagonal_2(py::module &m, const char *name) {
  456. typedef typename Type::Scalar Scalar;
  457. /* Many Eigen functions are templated and can't easily be referenced using
  458. a function pointer, thus a big portion of the binding code below
  459. instantiates Eigen code using small anonymous wrapper functions */
  460. py::class_<Type> matrix(m, name, py::buffer_protocol());
  461. matrix
  462. /* Constructors */
  463. .def(py::init<>())
  464. //.def(py::init<size_t, size_t>())
  465. /* Size query functions */
  466. .def("size", [](const Type &m) { return m.size(); })
  467. .def("cols", [](const Type &m) { return m.cols(); })
  468. .def("rows", [](const Type &m) { return m.rows(); })
  469. .def("shape", [](const Type &m) { return std::tuple<int,int>(m.rows(), m.cols()); })
  470. /* Initialization */
  471. .def("setZero", [](Type &m) { m.setZero(); })
  472. .def("setIdentity", [](Type &m) { m.setIdentity(); })
  473. /* Arithmetic operators (def_cast forcefully casts the result back to a
  474. Type to avoid type issues with Eigen's crazy expression templates) */
  475. // .def_cast(-py::self)
  476. // .def_cast(py::self + py::self)
  477. // .def_cast(py::self - py::self)
  478. // .def_cast(py::self * py::self)
  479. .def_cast(py::self * Scalar())
  480. .def_cast(Scalar() * py::self)
  481. // // Special case, sparse * dense produces a dense matrix
  482. // .def("__mul__", []
  483. // (const Type &a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  484. // {
  485. // return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  486. // })
  487. // .def("__rmul__", [](const Type& a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  488. // {
  489. // return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  490. // })
  491. .def("__mul__", []
  492. (const Type &a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  493. {
  494. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  495. })
  496. .def("__rmul__", [](const Type& a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  497. {
  498. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  499. })
  500. .def("__mul__", []
  501. (const Type &a, const Eigen::SparseMatrix<Scalar>& b)
  502. {
  503. return Eigen::SparseMatrix<Scalar>(a * b);
  504. })
  505. .def("__rmul__", [](const Type& a, const Eigen::SparseMatrix<Scalar>& b)
  506. {
  507. return Eigen::SparseMatrix<Scalar>(b * a);
  508. })
  509. /* Python protocol implementations */
  510. .def("__repr__", [](const Type &/*v*/) {
  511. std::ostringstream oss;
  512. oss << "<< operator undefined for diagonal matrices";
  513. return oss.str();
  514. })
  515. /* Other transformations */
  516. ;
  517. return matrix;
  518. }
  519. void python_export_vector(py::module &m) {
  520. py::module me = m.def_submodule(
  521. "eigen", "Wrappers for Eigen types");
  522. /* Bindings for VectorXd */
  523. // bind_eigen_1<Eigen::VectorXd> (me, "VectorXd");
  524. // py::implicitly_convertible<py::buffer, Eigen::VectorXd>();
  525. // py::implicitly_convertible<double, Eigen::VectorXd>();
  526. /* Bindings for VectorXi */
  527. // bind_eigen_1<Eigen::VectorXi> (me, "VectorXi");
  528. // py::implicitly_convertible<py::buffer, Eigen::VectorXi>();
  529. // py::implicitly_convertible<double, Eigen::VectorXi>();
  530. /* Bindings for MatrixXd */
  531. bind_eigen_2<Eigen::MatrixXd> (me, "MatrixXd");
  532. //py::implicitly_convertible<py::buffer, Eigen::MatrixXd>();
  533. //py::implicitly_convertible<double, Eigen::MatrixXd>();
  534. /* Bindings for MatrixXi */
  535. bind_eigen_2<Eigen::MatrixXi> (me, "MatrixXi");
  536. //py::implicitly_convertible<py::buffer, Eigen::MatrixXi>();
  537. //py::implicitly_convertible<double, Eigen::MatrixXi>();
  538. /* Bindings for MatrixXb */
  539. bind_eigen_2<Eigen::Matrix<bool,Eigen::Dynamic,Eigen::Dynamic> > (me, "MatrixXb");
  540. /* Bindings for MatrixXuc */
  541. bind_eigen_2<Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> > (me, "MatrixXuc");
  542. // py::implicitly_convertible<py::buffer, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> >();
  543. // py::implicitly_convertible<double, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> >();
  544. // /* Bindings for Vector3d */
  545. // auto vector3 = bind_eigen_1_3<Eigen::Vector3d>(me, "Vector3d");
  546. // vector3
  547. // .def("norm", [](const Eigen::Vector3d &v) { return v.norm(); })
  548. // .def("squaredNorm", [](const Eigen::Vector3d &v) { return v.squaredNorm(); })
  549. // .def("normalize", [](Eigen::Vector3d &v) { v.normalize(); })
  550. // .def("normalized", [](const Eigen::Vector3d &v) -> Eigen::Vector3d { return v.normalized(); })
  551. // .def("dot", [](const Eigen::Vector3d &v1, const Eigen::Vector3d &v2) { return v1.dot(v2); })
  552. // .def("cross", [](const Eigen::Vector3d &v1, const Eigen::Vector3d &v2) -> Eigen::Vector3d { return v1.cross(v2); })
  553. // .def_property("x", [](const Eigen::Vector3d &v) -> double { return v.x(); },
  554. // [](Eigen::Vector3d &v, double x) { v.x() = x; }, "X coordinate")
  555. // .def_property("y", [](const Eigen::Vector3d &v) -> double { return v.y(); },
  556. // [](Eigen::Vector3d &v, double y) { v.y() = y; }, "Y coordinate")
  557. // .def_property("z", [](const Eigen::Vector3d &v) -> double { return v.z(); },
  558. // [](Eigen::Vector3d &v, double z) { v.z() = z; }, "Z coordinate");
  559. //
  560. // py::implicitly_convertible<py::buffer, Eigen::Vector3d>();
  561. // py::implicitly_convertible<double, Eigen::Vector3d>();
  562. /* Bindings for SparseMatrix<double> */
  563. bind_eigen_sparse_2< Eigen::SparseMatrix<double> > (me, "SparseMatrixd");
  564. /* Bindings for SparseMatrix<int> */
  565. bind_eigen_sparse_2< Eigen::SparseMatrix<int> > (me, "SparseMatrixi");
  566. /* Bindings for DiagonalMatrix<double> */
  567. bind_eigen_diagonal_2< Eigen::DiagonalMatrix<double,Eigen::Dynamic,Eigen::Dynamic> > (me, "DiagonalMatrixd");
  568. /* Bindings for DiagonalMatrix<int> */
  569. bind_eigen_diagonal_2< Eigen::DiagonalMatrix<int,Eigen::Dynamic,Eigen::Dynamic> > (me, "DiagonalMatrixi");
  570. /* Bindings for SimplicialLLT*/
  571. py::class_<Eigen::SimplicialLLT<Eigen::SparseMatrix<double > >> simpliciallltsparse(me, "SimplicialLLTsparse");
  572. simpliciallltsparse
  573. .def(py::init<>())
  574. .def(py::init<Eigen::SparseMatrix<double>>())
  575. .def("info",[](const Eigen::SimplicialLLT<Eigen::SparseMatrix<double > >& s)
  576. {
  577. if (s.info() == Eigen::Success)
  578. return "Success";
  579. else
  580. return "Numerical Issue";
  581. })
  582. .def("analyzePattern",[](Eigen::SimplicialLLT<Eigen::SparseMatrix<double > >& s, const Eigen::SparseMatrix<double>& a) { return s.analyzePattern(a); })
  583. .def("factorize",[](Eigen::SimplicialLLT<Eigen::SparseMatrix<double > >& s, const Eigen::SparseMatrix<double>& a) { return s.factorize(a); })
  584. .def("solve",[](const Eigen::SimplicialLLT<Eigen::SparseMatrix<double > >& s, const Eigen::MatrixXd& rhs) { return Eigen::MatrixXd(s.solve(rhs)); })
  585. ;
  586. // Bindings for Affine3d
  587. py::class_<Eigen::Affine3d > affine3d(me, "Affine3d");
  588. affine3d
  589. .def(py::init<>())
  590. .def_static("Identity", []() { return Eigen::Affine3d::Identity(); })
  591. .def("setIdentity",[](Eigen::Affine3d& a){
  592. return a.setIdentity();
  593. })
  594. .def("rotate",[](Eigen::Affine3d& a, double angle, Eigen::MatrixXd axis) {
  595. assert_is_Vector3("axis", axis);
  596. return a.rotate(Eigen::AngleAxisd(angle, Eigen::Vector3d(axis)));
  597. })
  598. .def("rotate",[](Eigen::Affine3d& a, Eigen::Quaterniond quat) {
  599. return a.rotate(quat);
  600. })
  601. .def("translate",[](Eigen::Affine3d& a, Eigen::MatrixXd offset) {
  602. assert_is_Vector3("offset", offset);
  603. return a.translate(Eigen::Vector3d(offset));
  604. })
  605. .def("matrix", [](Eigen::Affine3d& a) -> Eigen::MatrixXd {
  606. return Eigen::MatrixXd(a.matrix());
  607. })
  608. ;
  609. // Bindings for Quaterniond
  610. py::class_<Eigen::Quaterniond > quaterniond(me, "Quaterniond");
  611. quaterniond
  612. .def(py::init<>())
  613. .def(py::init<double, double, double, double>())
  614. .def("__init__", [](Eigen::Quaterniond &q, double angle, Eigen::MatrixXd axis) {
  615. assert_is_Vector3("axis", axis);
  616. new (&q) Eigen::Quaterniond(Eigen::AngleAxisd(angle, Eigen::Vector3d(axis)));
  617. })
  618. .def_static("Identity", []() { return Eigen::Quaterniond::Identity(); })
  619. .def("__repr__", [](const Eigen::Quaterniond &v) {
  620. std::ostringstream oss;
  621. oss << "(" << v.w() << ", " << v.x() << ", " << v.y() << ", " << v.z() << ")";
  622. return oss.str();
  623. })
  624. .def("conjugate",[](Eigen::Quaterniond& q) {
  625. return q.conjugate();
  626. })
  627. .def("normalize",[](Eigen::Quaterniond& q) {
  628. return q.normalize();
  629. })
  630. .def("slerp",[](Eigen::Quaterniond& q, double & t, Eigen::Quaterniond other) {
  631. return q.slerp(t, other);
  632. })
  633. // .def_cast(-py::self)
  634. // .def_cast(py::self + py::self)
  635. // .def_cast(py::self - py::self)
  636. .def_cast(py::self * py::self)
  637. // .def_cast(py::self - Scalar())
  638. // .def_cast(py::self * Scalar())
  639. // .def_cast(py::self / Scalar())
  640. // .def("__mul__", []
  641. // (const Type &a, const Scalar& b)
  642. // {
  643. // return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  644. // })
  645. // .def("__rmul__", [](const Type& a, const Scalar& b)
  646. // {
  647. // return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  648. // })
  649. ;
  650. }