py_vector.cpp 31 KB

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