py_vector.cpp 27 KB

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