py_vector.cpp 26 KB

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