eigen.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. /*
  2. pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices
  3. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #pragma once
  8. /* HINT: To suppress warnings originating from the Eigen headers, use -isystem.
  9. See also:
  10. https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir
  11. https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler
  12. */
  13. #include "numpy.h"
  14. // The C4127 suppression was introduced for Eigen 3.4.0. In theory we could
  15. // make it version specific, or even remove it later, but considering that
  16. // 1. C4127 is generally far more distracting than useful for modern template code, and
  17. // 2. we definitely want to ignore any MSVC warnings originating from Eigen code,
  18. // it is probably best to keep this around indefinitely.
  19. #if defined(_MSC_VER)
  20. # pragma warning(push)
  21. # pragma warning(disable : 4127) // C4127: conditional expression is constant
  22. # pragma warning(disable : 5054) // https://github.com/pybind/pybind11/pull/3741
  23. // C5054: operator '&': deprecated between enumerations of different types
  24. #elif defined(__MINGW32__)
  25. # pragma GCC diagnostic push
  26. # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
  27. #endif
  28. #include <Eigen/Core>
  29. #include <Eigen/SparseCore>
  30. #if defined(_MSC_VER)
  31. # pragma warning(pop)
  32. #elif defined(__MINGW32__)
  33. # pragma GCC diagnostic pop
  34. #endif
  35. // Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
  36. // move constructors that break things. We could detect this an explicitly copy, but an extra copy
  37. // of matrices seems highly undesirable.
  38. static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
  39. "Eigen support in pybind11 requires Eigen >= 3.2.7");
  40. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  41. // Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
  42. using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
  43. template <typename MatrixType>
  44. using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
  45. template <typename MatrixType>
  46. using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
  47. PYBIND11_NAMESPACE_BEGIN(detail)
  48. #if EIGEN_VERSION_AT_LEAST(3, 3, 0)
  49. using EigenIndex = Eigen::Index;
  50. template <typename Scalar, int Flags, typename StorageIndex>
  51. using EigenMapSparseMatrix = Eigen::Map<Eigen::SparseMatrix<Scalar, Flags, StorageIndex>>;
  52. #else
  53. using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
  54. template <typename Scalar, int Flags, typename StorageIndex>
  55. using EigenMapSparseMatrix = Eigen::MappedSparseMatrix<Scalar, Flags, StorageIndex>;
  56. #endif
  57. // Matches Eigen::Map, Eigen::Ref, blocks, etc:
  58. template <typename T>
  59. using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>,
  60. std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
  61. template <typename T>
  62. using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
  63. template <typename T>
  64. using is_eigen_dense_plain
  65. = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;
  66. template <typename T>
  67. using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;
  68. // Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
  69. // basically covers anything that can be assigned to a dense matrix but that don't have a typical
  70. // matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
  71. // SelfAdjointView fall into this category.
  72. template <typename T>
  73. using is_eigen_other
  74. = all_of<is_template_base_of<Eigen::EigenBase, T>,
  75. negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>>;
  76. // Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
  77. template <bool EigenRowMajor>
  78. struct EigenConformable {
  79. bool conformable = false;
  80. EigenIndex rows = 0, cols = 0;
  81. EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
  82. bool negativestrides = false; // If true, do not use stride!
  83. // NOLINTNEXTLINE(google-explicit-constructor)
  84. EigenConformable(bool fits = false) : conformable{fits} {}
  85. // Matrix type:
  86. EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
  87. : conformable{true}, rows{r}, cols{c},
  88. // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
  89. // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
  90. stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
  91. : (cstride > 0 ? cstride : 0) /* outer stride */,
  92. EigenRowMajor ? (cstride > 0 ? cstride : 0)
  93. : (rstride > 0 ? rstride : 0) /* inner stride */},
  94. negativestrides{rstride < 0 || cstride < 0} {}
  95. // Vector type:
  96. EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
  97. : EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
  98. template <typename props>
  99. bool stride_compatible() const {
  100. // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
  101. // matching strides, or a dimension size of 1 (in which case the stride value is
  102. // irrelevant). Alternatively, if any dimension size is 0, the strides are not relevant
  103. // (and numpy ≥ 1.23 sets the strides to 0 in that case, so we need to check explicitly).
  104. if (negativestrides) {
  105. return false;
  106. }
  107. if (rows == 0 || cols == 0) {
  108. return true;
  109. }
  110. return (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
  111. || (EigenRowMajor ? cols : rows) == 1)
  112. && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
  113. || (EigenRowMajor ? rows : cols) == 1);
  114. }
  115. // NOLINTNEXTLINE(google-explicit-constructor)
  116. operator bool() const { return conformable; }
  117. };
  118. template <typename Type>
  119. struct eigen_extract_stride {
  120. using type = Type;
  121. };
  122. template <typename PlainObjectType, int MapOptions, typename StrideType>
  123. struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {
  124. using type = StrideType;
  125. };
  126. template <typename PlainObjectType, int Options, typename StrideType>
  127. struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {
  128. using type = StrideType;
  129. };
  130. // Helper struct for extracting information from an Eigen type
  131. template <typename Type_>
  132. struct EigenProps {
  133. using Type = Type_;
  134. using Scalar = typename Type::Scalar;
  135. using StrideType = typename eigen_extract_stride<Type>::type;
  136. static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
  137. size = Type::SizeAtCompileTime;
  138. static constexpr bool row_major = Type::IsRowMajor,
  139. vector
  140. = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
  141. fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
  142. fixed = size != Eigen::Dynamic, // Fully-fixed size
  143. dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
  144. template <EigenIndex i, EigenIndex ifzero>
  145. using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
  146. static constexpr EigenIndex inner_stride
  147. = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
  148. outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
  149. vector ? size
  150. : row_major ? cols
  151. : rows > ::value;
  152. static constexpr bool dynamic_stride
  153. = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
  154. static constexpr bool requires_row_major
  155. = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
  156. static constexpr bool requires_col_major
  157. = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
  158. // Takes an input array and determines whether we can make it fit into the Eigen type. If
  159. // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
  160. // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
  161. static EigenConformable<row_major> conformable(const array &a) {
  162. const auto dims = a.ndim();
  163. if (dims < 1 || dims > 2) {
  164. return false;
  165. }
  166. if (dims == 2) { // Matrix type: require exact match (or dynamic)
  167. EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
  168. np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
  169. np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
  170. if ((PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && np_rows != rows)
  171. || (PYBIND11_SILENCE_MSVC_C4127(fixed_cols) && np_cols != cols)) {
  172. return false;
  173. }
  174. return {np_rows, np_cols, np_rstride, np_cstride};
  175. }
  176. // Otherwise we're storing an n-vector. Only one of the strides will be used, but
  177. // whichever is used, we want the (single) numpy stride value.
  178. const EigenIndex n = a.shape(0),
  179. stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
  180. if (vector) { // Eigen type is a compile-time vector
  181. if (PYBIND11_SILENCE_MSVC_C4127(fixed) && size != n) {
  182. return false; // Vector size mismatch
  183. }
  184. return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
  185. }
  186. if (fixed) {
  187. // The type has a fixed size, but is not a vector: abort
  188. return false;
  189. }
  190. if (fixed_cols) {
  191. // Since this isn't a vector, cols must be != 1. We allow this only if it exactly
  192. // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
  193. if (cols != n) {
  194. return false;
  195. }
  196. return {1, n, stride};
  197. } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
  198. if (PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && rows != n) {
  199. return false;
  200. }
  201. return {n, 1, stride};
  202. }
  203. static constexpr bool show_writeable
  204. = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
  205. static constexpr bool show_order = is_eigen_dense_map<Type>::value;
  206. static constexpr bool show_c_contiguous = show_order && requires_row_major;
  207. static constexpr bool show_f_contiguous
  208. = !show_c_contiguous && show_order && requires_col_major;
  209. static constexpr auto descriptor
  210. = const_name("numpy.ndarray[") + npy_format_descriptor<Scalar>::name + const_name("[")
  211. + const_name<fixed_rows>(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
  212. + const_name<fixed_cols>(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
  213. +
  214. // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to
  215. // be satisfied: writeable=True (for a mutable reference), and, depending on the map's
  216. // stride options, possibly f_contiguous or c_contiguous. We include them in the
  217. // descriptor output to provide some hint as to why a TypeError is occurring (otherwise
  218. // it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
  219. // an error message that you *gave* a numpy.ndarray of the right type and dimensions.
  220. const_name<show_writeable>(", flags.writeable", "")
  221. + const_name<show_c_contiguous>(", flags.c_contiguous", "")
  222. + const_name<show_f_contiguous>(", flags.f_contiguous", "") + const_name("]");
  223. };
  224. // Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
  225. // otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
  226. template <typename props>
  227. handle
  228. eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
  229. constexpr ssize_t elem_size = sizeof(typename props::Scalar);
  230. array a;
  231. if (props::vector) {
  232. a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
  233. } else {
  234. a = array({src.rows(), src.cols()},
  235. {elem_size * src.rowStride(), elem_size * src.colStride()},
  236. src.data(),
  237. base);
  238. }
  239. if (!writeable) {
  240. array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
  241. }
  242. return a.release();
  243. }
  244. // Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
  245. // reference the Eigen object's data with `base` as the python-registered base class (if omitted,
  246. // the base will be set to None, and lifetime management is up to the caller). The numpy array is
  247. // non-writeable if the given type is const.
  248. template <typename props, typename Type>
  249. handle eigen_ref_array(Type &src, handle parent = none()) {
  250. // none here is to get past array's should-we-copy detection, which currently always
  251. // copies when there is no base. Setting the base to None should be harmless.
  252. return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
  253. }
  254. // Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
  255. // numpy array that references the encapsulated data with a python-side reference to the capsule to
  256. // tie its destruction to that of any dependent python objects. Const-ness is determined by
  257. // whether or not the Type of the pointer given is const.
  258. template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>
  259. handle eigen_encapsulate(Type *src) {
  260. capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
  261. return eigen_ref_array<props>(*src, base);
  262. }
  263. // Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
  264. // types.
  265. template <typename Type>
  266. struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
  267. using Scalar = typename Type::Scalar;
  268. using props = EigenProps<Type>;
  269. bool load(handle src, bool convert) {
  270. // If we're in no-convert mode, only load if given an array of the correct type
  271. if (!convert && !isinstance<array_t<Scalar>>(src)) {
  272. return false;
  273. }
  274. // Coerce into an array, but don't do type conversion yet; the copy below handles it.
  275. auto buf = array::ensure(src);
  276. if (!buf) {
  277. return false;
  278. }
  279. auto dims = buf.ndim();
  280. if (dims < 1 || dims > 2) {
  281. return false;
  282. }
  283. auto fits = props::conformable(buf);
  284. if (!fits) {
  285. return false;
  286. }
  287. // Allocate the new type, then build a numpy reference into it
  288. value = Type(fits.rows, fits.cols);
  289. auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));
  290. if (dims == 1) {
  291. ref = ref.squeeze();
  292. } else if (ref.ndim() == 1) {
  293. buf = buf.squeeze();
  294. }
  295. int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
  296. if (result < 0) { // Copy failed!
  297. PyErr_Clear();
  298. return false;
  299. }
  300. return true;
  301. }
  302. private:
  303. // Cast implementation
  304. template <typename CType>
  305. static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
  306. switch (policy) {
  307. case return_value_policy::take_ownership:
  308. case return_value_policy::automatic:
  309. return eigen_encapsulate<props>(src);
  310. case return_value_policy::move:
  311. return eigen_encapsulate<props>(new CType(std::move(*src)));
  312. case return_value_policy::copy:
  313. return eigen_array_cast<props>(*src);
  314. case return_value_policy::reference:
  315. case return_value_policy::automatic_reference:
  316. return eigen_ref_array<props>(*src);
  317. case return_value_policy::reference_internal:
  318. return eigen_ref_array<props>(*src, parent);
  319. default:
  320. throw cast_error("unhandled return_value_policy: should not happen!");
  321. };
  322. }
  323. public:
  324. // Normal returned non-reference, non-const value:
  325. static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
  326. return cast_impl(&src, return_value_policy::move, parent);
  327. }
  328. // If you return a non-reference const, we mark the numpy array readonly:
  329. static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
  330. return cast_impl(&src, return_value_policy::move, parent);
  331. }
  332. // lvalue reference return; default (automatic) becomes copy
  333. static handle cast(Type &src, return_value_policy policy, handle parent) {
  334. if (policy == return_value_policy::automatic
  335. || policy == return_value_policy::automatic_reference) {
  336. policy = return_value_policy::copy;
  337. }
  338. return cast_impl(&src, policy, parent);
  339. }
  340. // const lvalue reference return; default (automatic) becomes copy
  341. static handle cast(const Type &src, return_value_policy policy, handle parent) {
  342. if (policy == return_value_policy::automatic
  343. || policy == return_value_policy::automatic_reference) {
  344. policy = return_value_policy::copy;
  345. }
  346. return cast(&src, policy, parent);
  347. }
  348. // non-const pointer return
  349. static handle cast(Type *src, return_value_policy policy, handle parent) {
  350. return cast_impl(src, policy, parent);
  351. }
  352. // const pointer return
  353. static handle cast(const Type *src, return_value_policy policy, handle parent) {
  354. return cast_impl(src, policy, parent);
  355. }
  356. static constexpr auto name = props::descriptor;
  357. // NOLINTNEXTLINE(google-explicit-constructor)
  358. operator Type *() { return &value; }
  359. // NOLINTNEXTLINE(google-explicit-constructor)
  360. operator Type &() { return value; }
  361. // NOLINTNEXTLINE(google-explicit-constructor)
  362. operator Type &&() && { return std::move(value); }
  363. template <typename T>
  364. using cast_op_type = movable_cast_op_type<T>;
  365. private:
  366. Type value;
  367. };
  368. // Base class for casting reference/map/block/etc. objects back to python.
  369. template <typename MapType>
  370. struct eigen_map_caster {
  371. private:
  372. using props = EigenProps<MapType>;
  373. public:
  374. // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
  375. // to stay around), but we'll allow it under the assumption that you know what you're doing
  376. // (and have an appropriate keep_alive in place). We return a numpy array pointing directly at
  377. // the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)
  378. // Note that this means you need to ensure you don't destroy the object in some other way (e.g.
  379. // with an appropriate keep_alive, or with a reference to a statically allocated matrix).
  380. static handle cast(const MapType &src, return_value_policy policy, handle parent) {
  381. switch (policy) {
  382. case return_value_policy::copy:
  383. return eigen_array_cast<props>(src);
  384. case return_value_policy::reference_internal:
  385. return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);
  386. case return_value_policy::reference:
  387. case return_value_policy::automatic:
  388. case return_value_policy::automatic_reference:
  389. return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);
  390. default:
  391. // move, take_ownership don't make any sense for a ref/map:
  392. pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
  393. }
  394. }
  395. static constexpr auto name = props::descriptor;
  396. // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
  397. // types but not bound arguments). We still provide them (with an explicitly delete) so that
  398. // you end up here if you try anyway.
  399. bool load(handle, bool) = delete;
  400. operator MapType() = delete;
  401. template <typename>
  402. using cast_op_type = MapType;
  403. };
  404. // We can return any map-like object (but can only load Refs, specialized next):
  405. template <typename Type>
  406. struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {};
  407. // Loader for Ref<...> arguments. See the documentation for info on how to make this work without
  408. // copying (it requires some extra effort in many cases).
  409. template <typename PlainObjectType, typename StrideType>
  410. struct type_caster<
  411. Eigen::Ref<PlainObjectType, 0, StrideType>,
  412. enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>>
  413. : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
  414. private:
  415. using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;
  416. using props = EigenProps<Type>;
  417. using Scalar = typename props::Scalar;
  418. using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;
  419. using Array
  420. = array_t<Scalar,
  421. array::forcecast
  422. | ((props::row_major ? props::inner_stride : props::outer_stride) == 1
  423. ? array::c_style
  424. : (props::row_major ? props::outer_stride : props::inner_stride) == 1
  425. ? array::f_style
  426. : 0)>;
  427. static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
  428. // Delay construction (these have no default constructor)
  429. std::unique_ptr<MapType> map;
  430. std::unique_ptr<Type> ref;
  431. // Our array. When possible, this is just a numpy array pointing to the source data, but
  432. // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
  433. // incompatible layout, or is an array of a type that needs to be converted). Using a numpy
  434. // temporary (rather than an Eigen temporary) saves an extra copy when we need both type
  435. // conversion and storage order conversion. (Note that we refuse to use this temporary copy
  436. // when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).
  437. Array copy_or_ref;
  438. public:
  439. bool load(handle src, bool convert) {
  440. // First check whether what we have is already an array of the right type. If not, we
  441. // can't avoid a copy (because the copy is also going to do type conversion).
  442. bool need_copy = !isinstance<Array>(src);
  443. EigenConformable<props::row_major> fits;
  444. if (!need_copy) {
  445. // We don't need a converting copy, but we also need to check whether the strides are
  446. // compatible with the Ref's stride requirements
  447. auto aref = reinterpret_borrow<Array>(src);
  448. if (aref && (!need_writeable || aref.writeable())) {
  449. fits = props::conformable(aref);
  450. if (!fits) {
  451. return false; // Incompatible dimensions
  452. }
  453. if (!fits.template stride_compatible<props>()) {
  454. need_copy = true;
  455. } else {
  456. copy_or_ref = std::move(aref);
  457. }
  458. } else {
  459. need_copy = true;
  460. }
  461. }
  462. if (need_copy) {
  463. // We need to copy: If we need a mutable reference, or we're not supposed to convert
  464. // (either because we're in the no-convert overload pass, or because we're explicitly
  465. // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
  466. if (!convert || need_writeable) {
  467. return false;
  468. }
  469. Array copy = Array::ensure(src);
  470. if (!copy) {
  471. return false;
  472. }
  473. fits = props::conformable(copy);
  474. if (!fits || !fits.template stride_compatible<props>()) {
  475. return false;
  476. }
  477. copy_or_ref = std::move(copy);
  478. loader_life_support::add_patient(copy_or_ref);
  479. }
  480. ref.reset();
  481. map.reset(new MapType(data(copy_or_ref),
  482. fits.rows,
  483. fits.cols,
  484. make_stride(fits.stride.outer(), fits.stride.inner())));
  485. ref.reset(new Type(*map));
  486. return true;
  487. }
  488. // NOLINTNEXTLINE(google-explicit-constructor)
  489. operator Type *() { return ref.get(); }
  490. // NOLINTNEXTLINE(google-explicit-constructor)
  491. operator Type &() { return *ref; }
  492. template <typename _T>
  493. using cast_op_type = pybind11::detail::cast_op_type<_T>;
  494. private:
  495. template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>
  496. Scalar *data(Array &a) {
  497. return a.mutable_data();
  498. }
  499. template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>
  500. const Scalar *data(Array &a) {
  501. return a.data();
  502. }
  503. // Attempt to figure out a constructor of `Stride` that will work.
  504. // If both strides are fixed, use a default constructor:
  505. template <typename S>
  506. using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic
  507. && S::OuterStrideAtCompileTime != Eigen::Dynamic
  508. && std::is_default_constructible<S>::value>;
  509. // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
  510. // Eigen::Stride, and use it:
  511. template <typename S>
  512. using stride_ctor_dual
  513. = bool_constant<!stride_ctor_default<S>::value
  514. && std::is_constructible<S, EigenIndex, EigenIndex>::value>;
  515. // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
  516. // it (passing whichever stride is dynamic).
  517. template <typename S>
  518. using stride_ctor_outer
  519. = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
  520. && S::OuterStrideAtCompileTime == Eigen::Dynamic
  521. && S::InnerStrideAtCompileTime != Eigen::Dynamic
  522. && std::is_constructible<S, EigenIndex>::value>;
  523. template <typename S>
  524. using stride_ctor_inner
  525. = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
  526. && S::InnerStrideAtCompileTime == Eigen::Dynamic
  527. && S::OuterStrideAtCompileTime != Eigen::Dynamic
  528. && std::is_constructible<S, EigenIndex>::value>;
  529. template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>
  530. static S make_stride(EigenIndex, EigenIndex) {
  531. return S();
  532. }
  533. template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>
  534. static S make_stride(EigenIndex outer, EigenIndex inner) {
  535. return S(outer, inner);
  536. }
  537. template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>
  538. static S make_stride(EigenIndex outer, EigenIndex) {
  539. return S(outer);
  540. }
  541. template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>
  542. static S make_stride(EigenIndex, EigenIndex inner) {
  543. return S(inner);
  544. }
  545. };
  546. // type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
  547. // EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
  548. // load() is not supported, but we can cast them into the python domain by first copying to a
  549. // regular Eigen::Matrix, then casting that.
  550. template <typename Type>
  551. struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
  552. protected:
  553. using Matrix
  554. = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
  555. using props = EigenProps<Matrix>;
  556. public:
  557. static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
  558. handle h = eigen_encapsulate<props>(new Matrix(src));
  559. return h;
  560. }
  561. static handle cast(const Type *src, return_value_policy policy, handle parent) {
  562. return cast(*src, policy, parent);
  563. }
  564. static constexpr auto name = props::descriptor;
  565. // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
  566. // types but not bound arguments). We still provide them (with an explicitly delete) so that
  567. // you end up here if you try anyway.
  568. bool load(handle, bool) = delete;
  569. operator Type() = delete;
  570. template <typename>
  571. using cast_op_type = Type;
  572. };
  573. template <typename Type>
  574. struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
  575. using Scalar = typename Type::Scalar;
  576. using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>;
  577. using Index = typename Type::Index;
  578. static constexpr bool rowMajor = Type::IsRowMajor;
  579. bool load(handle src, bool) {
  580. if (!src) {
  581. return false;
  582. }
  583. auto obj = reinterpret_borrow<object>(src);
  584. object sparse_module = module_::import("scipy.sparse");
  585. object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
  586. if (!type::handle_of(obj).is(matrix_type)) {
  587. try {
  588. obj = matrix_type(obj);
  589. } catch (const error_already_set &) {
  590. return false;
  591. }
  592. }
  593. auto values = array_t<Scalar>((object) obj.attr("data"));
  594. auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
  595. auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
  596. auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
  597. auto nnz = obj.attr("nnz").cast<Index>();
  598. if (!values || !innerIndices || !outerIndices) {
  599. return false;
  600. }
  601. value = EigenMapSparseMatrix<Scalar,
  602. Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),
  603. StorageIndex>(shape[0].cast<Index>(),
  604. shape[1].cast<Index>(),
  605. std::move(nnz),
  606. outerIndices.mutable_data(),
  607. innerIndices.mutable_data(),
  608. values.mutable_data());
  609. return true;
  610. }
  611. static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
  612. const_cast<Type &>(src).makeCompressed();
  613. object matrix_type
  614. = module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
  615. array data(src.nonZeros(), src.valuePtr());
  616. array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
  617. array innerIndices(src.nonZeros(), src.innerIndexPtr());
  618. return matrix_type(pybind11::make_tuple(
  619. std::move(data), std::move(innerIndices), std::move(outerIndices)),
  620. pybind11::make_tuple(src.rows(), src.cols()))
  621. .release();
  622. }
  623. PYBIND11_TYPE_CASTER(Type,
  624. const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
  625. "scipy.sparse.csc_matrix[")
  626. + npy_format_descriptor<Scalar>::name + const_name("]"));
  627. };
  628. PYBIND11_NAMESPACE_END(detail)
  629. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)