py_vector.cpp 27 KB

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