py_vector.cpp 27 KB

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