py_vector.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. #include <Eigen/Geometry>
  2. #include <Eigen/Dense>
  3. #include <Eigen/Sparse>
  4. #include "python.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. /* 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("topRows", [](Type &m, const int& k) { return Type(m.topRows(k)); })
  107. .def("bottomRows", [](Type &m, const int& k) { return Type(m.bottomRows(k)); })
  108. .def("topLeftCorner", [](Type &m, const int& p, const int&q) { return Type(m.topLeftCorner(p,q)); })
  109. .def("bottomLeftCorner", [](Type &m, const int& p, const int&q) { return Type(m.bottomLeftCorner(p,q)); })
  110. .def("topRightCorner", [](Type &m, const int& p, const int&q) { return Type(m.topRightCorner(p,q)); })
  111. .def("bottomRightCorner", [](Type &m, const int& p, const int&q) { return Type(m.bottomRightCorner(p,q)); })
  112. /* Resizing */
  113. .def("resize", [](Type &m, size_t s0, size_t s1) { m.resize(s0, s1); })
  114. .def("resizeLike", [](Type &m, const Type &m2) { m.resizeLike(m2); })
  115. .def("conservativeResize", [](Type &m, size_t s0, size_t s1) { m.conservativeResize(s0, s1); })
  116. .def("mean", [](const Type &m) {return m.mean();})
  117. .def("sum", [](const Type &m) {return m.sum();})
  118. .def("prod", [](const Type &m) {return m.prod();})
  119. .def("trace", [](const Type &m) {return m.trace();})
  120. .def("norm", [](const Type &m) {return m.norm();})
  121. .def("squaredNorm", [](const Type &m) {return m.squaredNorm();})
  122. .def("minCoeff", [](const Type &m) {return m.minCoeff();} )
  123. .def("maxCoeff", [](const Type &m) {return m.maxCoeff();} )
  124. .def("castdouble", [](const Type &m) {return Eigen::MatrixXd(m.template cast<double>());})
  125. .def("castint", [](const Type &m) {return Eigen::MatrixXi(m.template cast<int>());})
  126. /* Component-wise operations */
  127. .def("cwiseAbs", &Type::cwiseAbs)
  128. .def("cwiseAbs2", &Type::cwiseAbs2)
  129. .def("cwiseSqrt", &Type::cwiseSqrt)
  130. .def("cwiseInverse", &Type::cwiseInverse)
  131. .def("cwiseMin", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMin(m2); })
  132. .def("cwiseMax", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMax(m2); })
  133. .def("cwiseMin", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMin(s); })
  134. .def("cwiseMax", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMax(s); })
  135. .def("cwiseProduct", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseProduct(m2); })
  136. .def("cwiseQuotient", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseQuotient(m2); })
  137. /* Row and column-wise operations */
  138. .def("rowwiseSum", [](const Type &m) {return Type(m.rowwise().sum());} )
  139. .def("rowwiseProd", [](const Type &m) {return Type(m.rowwise().prod());} )
  140. .def("rowwiseMean", [](const Type &m) {return Type(m.rowwise().mean());} )
  141. .def("rowwiseNorm", [](const Type &m) {return Type(m.rowwise().norm());} )
  142. .def("rowwiseNormalized", [](const Type &m) {return Type(m.rowwise().normalized());} )
  143. .def("rowwiseMinCoeff", [](const Type &m) {return Type(m.rowwise().minCoeff());} )
  144. .def("rowwiseMaxCoeff", [](const Type &m) {return Type(m.rowwise().maxCoeff());} )
  145. .def("colwiseSum", [](const Type &m) {return Type(m.colwise().sum());} )
  146. .def("colwiseProd", [](const Type &m) {return Type(m.colwise().prod());} )
  147. .def("colwiseMean", [](const Type &m) {return Type(m.colwise().mean());} )
  148. .def("colwiseNorm", [](const Type &m) {return Type(m.colwise().norm());} )
  149. .def("colwiseMinCoeff", [](const Type &m) {return Type(m.colwise().minCoeff());} )
  150. .def("colwiseMaxCoeff", [](const Type &m) {return Type(m.colwise().maxCoeff());} )
  151. .def("replicate", [](const Type &m, const int& r, const int& c) {return Type(m.replicate(r,c));} )
  152. .def("asDiagonal", [](const Type &m) {return Eigen::DiagonalMatrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(m.asDiagonal());} )
  153. .def("sparseView", [](Type &m) { return Eigen::SparseMatrix<Scalar>(m.sparseView()); })
  154. /* Arithmetic operators (def_cast forcefully casts the result back to a
  155. Type to avoid type issues with Eigen's crazy expression templates) */
  156. .def_cast(-py::self)
  157. .def_cast(py::self + py::self)
  158. .def_cast(py::self - py::self)
  159. .def_cast(py::self * py::self)
  160. // .def_cast(py::self - Scalar())
  161. // .def_cast(py::self * Scalar())
  162. // .def_cast(py::self / Scalar())
  163. .def("__mul__", []
  164. (const Type &a, const Scalar& b)
  165. {
  166. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  167. })
  168. .def("__rmul__", [](const Type& a, const Scalar& b)
  169. {
  170. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  171. })
  172. .def("__add__", []
  173. (const Type &a, const Scalar& b)
  174. {
  175. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a.array() + b);
  176. })
  177. .def("__radd__", [](const Type& a, const Scalar& b)
  178. {
  179. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b + a.array());
  180. })
  181. .def("__sub__", []
  182. (const Type &a, const Scalar& b)
  183. {
  184. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a.array() - b);
  185. })
  186. .def("__rsub__", [](const Type& a, const Scalar& b)
  187. {
  188. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b - a.array());
  189. })
  190. .def("__div__", []
  191. (const Type &a, const Scalar& b)
  192. {
  193. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a / b);
  194. })
  195. .def("__truediv__", []
  196. (const Type &a, const Scalar& b)
  197. {
  198. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a / b);
  199. })
  200. /* Arithmetic in-place operators */
  201. .def_cast(py::self += py::self)
  202. .def_cast(py::self -= py::self)
  203. .def_cast(py::self *= py::self)
  204. .def_cast(py::self *= Scalar())
  205. .def_cast(py::self /= Scalar())
  206. /* Comparison operators */
  207. .def(py::self == py::self)
  208. .def(py::self != py::self)
  209. .def("transposeInPlace", [](Type &m) { m.transposeInPlace(); })
  210. /* Other transformations */
  211. .def("transpose", [](Type &m) -> Type { return m.transpose(); })
  212. /* Python protocol implementations */
  213. .def("__repr__", [](const Type &v) {
  214. std::ostringstream oss;
  215. oss << v;
  216. return oss.str();
  217. })
  218. .def("__getitem__", [](const Type &m, std::pair<size_t, size_t> i) {
  219. if (i.first >= (size_t) m.rows() || i.second >= (size_t) m.cols())
  220. throw py::index_error();
  221. return m(i.first, i.second);
  222. })
  223. .def("__setitem__", [](Type &m, std::pair<size_t, size_t> i, Scalar v) {
  224. if (i.first >= (size_t) m.rows() || i.second >= (size_t) m.cols())
  225. throw py::index_error();
  226. m(i.first, i.second) = v;
  227. })
  228. .def("__getitem__", [](const Type &m, size_t i) {
  229. if (i >= (size_t) m.size())
  230. throw py::index_error();
  231. return m(i);
  232. })
  233. .def("__setitem__", [](Type &m, size_t i, Scalar v) {
  234. if (i >= (size_t) m.size())
  235. throw py::index_error();
  236. m(i) = v;
  237. })
  238. /* Buffer access for interacting with NumPy */
  239. .def_buffer([](Type &m) -> py::buffer_info {
  240. return py::buffer_info(
  241. m.data(), /* Pointer to buffer */
  242. sizeof(Scalar), /* Size of one scalar */
  243. /* Python struct-style format descriptor */
  244. py::format_descriptor<Scalar>::value(),
  245. 2, /* Number of dimensions */
  246. { (size_t) m.rows(), /* Buffer dimensions */
  247. (size_t) m.cols() },
  248. { sizeof(Scalar), /* Strides (in bytes) for each index */
  249. sizeof(Scalar) * m.rows() }
  250. );
  251. })
  252. /* Static initializers */
  253. .def_static("Zero", [](size_t n, size_t m) { return Type(Type::Zero(n, m)); })
  254. .def_static("Random", [](size_t n, size_t m) { return Type(Type::Random(n, m)); })
  255. .def_static("Ones", [](size_t n, size_t m) { return Type(Type::Ones(n, m)); })
  256. .def_static("Constant", [](size_t n, size_t m, Scalar value) { return Type(Type::Constant(n, m, value)); })
  257. .def_static("Identity", [](size_t n, size_t m) { return Type(Type::Identity(n, m)); })
  258. .def("MapMatrix", [](const Type& m, size_t r, size_t c)
  259. {
  260. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>>(m.data(),r,c));
  261. })
  262. .def("copy", [](const Type &m) { return Type(m); })
  263. ;
  264. return matrix;
  265. }
  266. /// Creates Python bindings for a dynamic Eigen sparse order-2 tensor (i.e. a matrix)
  267. template <typename Type>
  268. py::class_<Type> bind_eigen_sparse_2(py::module &m, const char *name,
  269. py::object parent = py::object()) {
  270. typedef typename Type::Scalar Scalar;
  271. /* Many Eigen functions are templated and can't easily be referenced using
  272. a function pointer, thus a big portion of the binding code below
  273. instantiates Eigen code using small anonymous wrapper functions */
  274. py::class_<Type> matrix(m, name, parent);
  275. matrix
  276. /* Constructors */
  277. .def(py::init<>())
  278. .def(py::init<size_t, size_t>())
  279. // .def("__init__", [](Type &m, Scalar f) {
  280. // new (&m) Type(1, 1);
  281. // m(0, 0) = f;
  282. // })
  283. // .def("__init__", [](Type &m, py::buffer b) {
  284. // py::buffer_info info = b.request();
  285. // if (info.format != py::format_descriptor<Scalar>::value())
  286. // throw std::runtime_error("Incompatible buffer format!");
  287. // if (info.ndim == 1) {
  288. // new (&m) Type(info.shape[0], 1);
  289. // memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  290. // } else if (info.ndim == 2) {
  291. // if (info.strides[0] == sizeof(Scalar)) {
  292. // new (&m) Type(info.shape[0], info.shape[1]);
  293. // memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  294. // } else {
  295. // new (&m) Type(info.shape[1], info.shape[0]);
  296. // memcpy(m.data(), info.ptr, sizeof(Scalar) * m.size());
  297. // m.transposeInPlace();
  298. // }
  299. // } else {
  300. // throw std::runtime_error("Incompatible buffer dimension!");
  301. // }
  302. // })
  303. /* Size query functions */
  304. .def("size", [](const Type &m) { return m.size(); })
  305. .def("cols", [](const Type &m) { return m.cols(); })
  306. .def("rows", [](const Type &m) { return m.rows(); })
  307. /* Initialization */
  308. .def("setZero", [](Type &m) { m.setZero(); })
  309. .def("setIdentity", [](Type &m) { m.setIdentity(); })
  310. .def("transpose", [](Type &m) { return Type(m.transpose()); })
  311. .def("norm", [](Type &m) { return m.norm(); })
  312. /* Resizing */
  313. // .def("resize", [](Type &m, size_t s0, size_t s1) { m.resize(s0, s1); })
  314. // .def("resizeLike", [](Type &m, const Type &m2) { m.resizeLike(m2); })
  315. // .def("conservativeResize", [](Type &m, size_t s0, size_t s1) { m.conservativeResize(s0, s1); })
  316. /* Component-wise operations */
  317. // .def("cwiseAbs", &Type::cwiseAbs)
  318. // .def("cwiseAbs2", &Type::cwiseAbs2)
  319. // .def("cwiseSqrt", &Type::cwiseSqrt)
  320. // .def("cwiseInverse", &Type::cwiseInverse)
  321. // .def("cwiseMin", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMin(m2); })
  322. // .def("cwiseMax", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseMax(m2); })
  323. // .def("cwiseMin", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMin(s); })
  324. // .def("cwiseMax", [](const Type &m1, Scalar s) -> Type { return m1.cwiseMax(s); })
  325. // .def("cwiseProduct", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseProduct(m2); })
  326. // .def("cwiseQuotient", [](const Type &m1, const Type &m2) -> Type { return m1.cwiseQuotient(m2); })
  327. /* Arithmetic operators (def_cast forcefully casts the result back to a
  328. Type to avoid type issues with Eigen's crazy expression templates) */
  329. .def_cast(-py::self)
  330. .def_cast(py::self + py::self)
  331. .def_cast(py::self - py::self)
  332. .def_cast(py::self * py::self)
  333. .def_cast(py::self * Scalar())
  334. .def_cast(Scalar() * py::self)
  335. // Special case, sparse * dense produces a dense matrix
  336. // .def("__mul__", []
  337. // (const Type &a, const Scalar& b)
  338. // {
  339. // return Type(a * b);
  340. // })
  341. // .def("__rmul__", [](const Type& a, const Scalar& b)
  342. // {
  343. // return Type(b * a);
  344. // })
  345. .def("__mul__", []
  346. (const Type &a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  347. {
  348. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  349. })
  350. .def("__rmul__", [](const Type& a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  351. {
  352. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  353. })
  354. .def("__mul__", []
  355. (const Type &a, const Eigen::DiagonalMatrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  356. {
  357. return Type(a * b);
  358. })
  359. .def("__rmul__", [](const Type& a, const Eigen::DiagonalMatrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  360. {
  361. return Type(b * a);
  362. })
  363. //.def(py::self * Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>())
  364. // .def_cast(py::self / Scalar())
  365. /* Arithmetic in-place operators */
  366. // .def_cast(py::self += py::self)
  367. // .def_cast(py::self -= py::self)
  368. // .def_cast(py::self *= py::self)
  369. // .def_cast(py::self *= Scalar())
  370. // .def_cast(py::self /= Scalar())
  371. /* Comparison operators */
  372. // .def(py::self == py::self)
  373. // .def(py::self != py::self)
  374. // .def("transposeInPlace", [](Type &m) { m.transposeInPlace(); })
  375. // /* Other transformations */
  376. // .def("transpose", [](Type &m) -> Type { return m.transpose(); })
  377. /* Python protocol implementations */
  378. .def("__repr__", [](const Type &v) {
  379. std::ostringstream oss;
  380. oss << v;
  381. return oss.str();
  382. })
  383. /* Static initializers */
  384. // .def_static("Zero", [](size_t n, size_t m) { return Type(Type::Zero(n, m)); })
  385. // .def_static("Ones", [](size_t n, size_t m) { return Type(Type::Ones(n, m)); })
  386. // .def_static("Constant", [](size_t n, size_t m, Scalar value) { return Type(Type::Constant(n, m, value)); })
  387. // .def_static("Identity", [](size_t n, size_t m) { return Type(Type::Identity(n, m)); })
  388. .def("toCOO",[](const Type& m)
  389. {
  390. Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> t(m.nonZeros(),3);
  391. int count = 0;
  392. for (int k=0; k<m.outerSize(); ++k)
  393. for (typename Type::InnerIterator it(m,k); it; ++it)
  394. t.row(count++) << it.row(), it.col(), it.value();
  395. return t;
  396. })
  397. .def("fromCOO",[](Type& m, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& t, int rows, int cols)
  398. {
  399. typedef Eigen::Triplet<Scalar> T;
  400. std::vector<T> tripletList;
  401. tripletList.reserve(t.rows());
  402. for(unsigned i=0;i<t.rows();++i)
  403. tripletList.push_back(T(round(t(i,0)),round(t(i,1)),t(i,2)));
  404. if (rows == -1)
  405. rows = t.col(0).maxCoeff()+1;
  406. if (cols == -1)
  407. cols = t.col(1).maxCoeff()+1;
  408. m.resize(rows,cols);
  409. m.setFromTriplets(tripletList.begin(), tripletList.end());
  410. }, py::arg("t"), py::arg("rows") = -1, py::arg("cols") = -1)
  411. .def("insert",[](Type& m, const int row, const int col, const Scalar value)
  412. {
  413. return m.insert(row,col) = value;
  414. }, py::arg("row"), py::arg("col"), py::arg("value"))
  415. .def("makeCompressed",[](Type& m)
  416. {
  417. return m.makeCompressed();
  418. })
  419. .def("diagonal", [](const Type &m) {return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(m.diagonal());} )
  420. ;
  421. return matrix;
  422. }
  423. /// Creates Python bindings for a diagonal Eigen sparse order-2 tensor (i.e. a matrix)
  424. template <typename Type>
  425. py::class_<Type> bind_eigen_diagonal_2(py::module &m, const char *name,
  426. py::object parent = py::object()) {
  427. typedef typename Type::Scalar Scalar;
  428. /* Many Eigen functions are templated and can't easily be referenced using
  429. a function pointer, thus a big portion of the binding code below
  430. instantiates Eigen code using small anonymous wrapper functions */
  431. py::class_<Type> matrix(m, name, parent);
  432. matrix
  433. /* Constructors */
  434. .def(py::init<>())
  435. //.def(py::init<size_t, size_t>())
  436. /* Size query functions */
  437. .def("size", [](const Type &m) { return m.size(); })
  438. .def("cols", [](const Type &m) { return m.cols(); })
  439. .def("rows", [](const Type &m) { return m.rows(); })
  440. /* Initialization */
  441. .def("setZero", [](Type &m) { m.setZero(); })
  442. .def("setIdentity", [](Type &m) { m.setIdentity(); })
  443. /* Arithmetic operators (def_cast forcefully casts the result back to a
  444. Type to avoid type issues with Eigen's crazy expression templates) */
  445. // .def_cast(-py::self)
  446. // .def_cast(py::self + py::self)
  447. // .def_cast(py::self - py::self)
  448. // .def_cast(py::self * py::self)
  449. .def_cast(py::self * Scalar())
  450. .def_cast(Scalar() * py::self)
  451. // // Special case, sparse * dense produces a dense matrix
  452. // .def("__mul__", []
  453. // (const Type &a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  454. // {
  455. // return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  456. // })
  457. // .def("__rmul__", [](const Type& a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  458. // {
  459. // return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  460. // })
  461. .def("__mul__", []
  462. (const Type &a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  463. {
  464. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(a * b);
  465. })
  466. .def("__rmul__", [](const Type& a, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& b)
  467. {
  468. return Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>(b * a);
  469. })
  470. .def("__mul__", []
  471. (const Type &a, const Eigen::SparseMatrix<Scalar>& b)
  472. {
  473. return Eigen::SparseMatrix<Scalar>(a * b);
  474. })
  475. .def("__rmul__", [](const Type& a, const Eigen::SparseMatrix<Scalar>& b)
  476. {
  477. return Eigen::SparseMatrix<Scalar>(b * a);
  478. })
  479. /* Python protocol implementations */
  480. .def("__repr__", [](const Type &/*v*/) {
  481. std::ostringstream oss;
  482. oss << "<< operator undefined for diagonal matrices";
  483. return oss.str();
  484. })
  485. /* Other transformations */
  486. ;
  487. return matrix;
  488. }
  489. void python_export_vector(py::module &m) {
  490. py::module me = m.def_submodule(
  491. "eigen", "Wrappers for Eigen types");
  492. /* Bindings for VectorXd */
  493. // bind_eigen_1<Eigen::VectorXd> (me, "VectorXd");
  494. // py::implicitly_convertible<py::buffer, Eigen::VectorXd>();
  495. // py::implicitly_convertible<double, Eigen::VectorXd>();
  496. /* Bindings for VectorXi */
  497. // bind_eigen_1<Eigen::VectorXi> (me, "VectorXi");
  498. // py::implicitly_convertible<py::buffer, Eigen::VectorXi>();
  499. // py::implicitly_convertible<double, Eigen::VectorXi>();
  500. /* Bindings for MatrixXd */
  501. bind_eigen_2<Eigen::MatrixXd> (me, "MatrixXd");
  502. //py::implicitly_convertible<py::buffer, Eigen::MatrixXd>();
  503. //py::implicitly_convertible<double, Eigen::MatrixXd>();
  504. /* Bindings for MatrixXi */
  505. bind_eigen_2<Eigen::MatrixXi> (me, "MatrixXi");
  506. // py::implicitly_convertible<py::buffer, Eigen::MatrixXi>();
  507. //py::implicitly_convertible<double, Eigen::MatrixXi>();
  508. /* Bindings for MatrixXuc */
  509. bind_eigen_2<Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> > (me, "MatrixXuc");
  510. // py::implicitly_convertible<py::buffer, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> >();
  511. // py::implicitly_convertible<double, Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> >();
  512. // /* Bindings for Vector3d */
  513. // auto vector3 = bind_eigen_1_3<Eigen::Vector3d>(me, "Vector3d");
  514. // vector3
  515. // .def("norm", [](const Eigen::Vector3d &v) { return v.norm(); })
  516. // .def("squaredNorm", [](const Eigen::Vector3d &v) { return v.squaredNorm(); })
  517. // .def("normalize", [](Eigen::Vector3d &v) { v.normalize(); })
  518. // .def("normalized", [](const Eigen::Vector3d &v) -> Eigen::Vector3d { return v.normalized(); })
  519. // .def("dot", [](const Eigen::Vector3d &v1, const Eigen::Vector3d &v2) { return v1.dot(v2); })
  520. // .def("cross", [](const Eigen::Vector3d &v1, const Eigen::Vector3d &v2) -> Eigen::Vector3d { return v1.cross(v2); })
  521. // .def_property("x", [](const Eigen::Vector3d &v) -> double { return v.x(); },
  522. // [](Eigen::Vector3d &v, double x) { v.x() = x; }, "X coordinate")
  523. // .def_property("y", [](const Eigen::Vector3d &v) -> double { return v.y(); },
  524. // [](Eigen::Vector3d &v, double y) { v.y() = y; }, "Y coordinate")
  525. // .def_property("z", [](const Eigen::Vector3d &v) -> double { return v.z(); },
  526. // [](Eigen::Vector3d &v, double z) { v.z() = z; }, "Z coordinate");
  527. //
  528. // py::implicitly_convertible<py::buffer, Eigen::Vector3d>();
  529. // py::implicitly_convertible<double, Eigen::Vector3d>();
  530. /* Bindings for SparseMatrix<double> */
  531. bind_eigen_sparse_2< Eigen::SparseMatrix<double> > (me, "SparseMatrixd");
  532. /* Bindings for SparseMatrix<int> */
  533. bind_eigen_sparse_2< Eigen::SparseMatrix<int> > (me, "SparseMatrixi");
  534. /* Bindings for DiagonalMatrix<double> */
  535. bind_eigen_diagonal_2< Eigen::DiagonalMatrix<double,Eigen::Dynamic,Eigen::Dynamic> > (me, "DiagonalMatrixd");
  536. /* Bindings for DiagonalMatrix<int> */
  537. bind_eigen_diagonal_2< Eigen::DiagonalMatrix<int,Eigen::Dynamic,Eigen::Dynamic> > (me, "DiagonalMatrixi");
  538. /* Bindings for SimplicialLLT*/
  539. py::class_<Eigen::SimplicialLLT<Eigen::SparseMatrix<double > >> simpliciallltsparse(me, "SimplicialLLTsparse");
  540. simpliciallltsparse
  541. .def(py::init<>())
  542. .def(py::init<Eigen::SparseMatrix<double>>())
  543. .def("info",[](const Eigen::SimplicialLLT<Eigen::SparseMatrix<double > >& s)
  544. {
  545. if (s.info() == Eigen::Success)
  546. return "Success";
  547. else
  548. return "Numerical Issue";
  549. })
  550. .def("solve",[](const Eigen::SimplicialLLT<Eigen::SparseMatrix<double > >& s, const Eigen::MatrixXd& rhs) { return Eigen::MatrixXd(s.solve(rhs)); })
  551. ;
  552. /* Bindings for Quaterniond*/
  553. //py::class_<Eigen::Quaterniond > quaterniond(me, "Quaterniond");
  554. //
  555. // quaterniond
  556. // .def(py::init<>())
  557. // .def(py::init<double, double, double, double>())
  558. // ;
  559. }