blob: 71fc6f1dc536f88e8236c444c34edebd4fa32ba8 [file] [log] [blame]
Wenzel Jakob9e0a0562016-05-05 20:33:54 +02001/*
2 pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices
3
4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
10#pragma once
11
12#include "numpy.h"
Wenzel Jakob0a078052016-05-29 13:40:40 +020013
Wenzel Jakob8706fb92016-09-07 23:37:40 +090014#if defined(__INTEL_COMPILER)
15# pragma warning(disable: 1682) // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem)
16#elif defined(__GNUG__) || defined(__clang__)
Wenzel Jakob0a078052016-05-29 13:40:40 +020017# pragma GCC diagnostic push
18# pragma GCC diagnostic ignored "-Wconversion"
Wenzel Jakobb5692722016-05-30 11:37:03 +020019# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
Jason Rhinelandercb637702016-12-13 19:09:08 -050020# if __GNUC__ >= 7
21# pragma GCC diagnostic ignored "-Wint-in-bool-context"
22# endif
Wenzel Jakob0a078052016-05-29 13:40:40 +020023#endif
24
Wenzel Jakob9e0a0562016-05-05 20:33:54 +020025#include <Eigen/Core>
26#include <Eigen/SparseCore>
27
28#if defined(_MSC_VER)
Jason Rhinelandercb637702016-12-13 19:09:08 -050029# pragma warning(push)
30# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
Wenzel Jakob9e0a0562016-05-05 20:33:54 +020031#endif
32
Jason Rhinelander17d02832017-01-16 20:35:14 -050033// Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
34// move constructors that break things. We could detect this an explicitly copy, but an extra copy
35// of matrices seems highly undesirable.
36static_assert(EIGEN_VERSION_AT_LEAST(3,2,7), "Eigen support in pybind11 requires Eigen >= 3.2.7");
37
Wenzel Jakob9e0a0562016-05-05 20:33:54 +020038NAMESPACE_BEGIN(pybind11)
Jason Rhinelander17d02832017-01-16 20:35:14 -050039
40// Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
41using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
42template <typename MatrixType> using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
43template <typename MatrixType> using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
44
Wenzel Jakob9e0a0562016-05-05 20:33:54 +020045NAMESPACE_BEGIN(detail)
46
Jason Rhinelander17d02832017-01-16 20:35:14 -050047#if EIGEN_VERSION_AT_LEAST(3,3,0)
48using EigenIndex = Eigen::Index;
49#else
50using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
51#endif
Wenzel Jakob9e0a0562016-05-05 20:33:54 +020052
Jason Rhinelander17d02832017-01-16 20:35:14 -050053// Matches Eigen::Map, Eigen::Ref, blocks, etc:
54template <typename T> using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>, std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
55template <typename T> using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
56template <typename T> using is_eigen_dense_plain = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;
57template <typename T> using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;
Jason Rhinelander9ffb3dd2016-08-04 15:24:41 -040058// Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
59// basically covers anything that can be assigned to a dense matrix but that don't have a typical
60// matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
61// SelfAdjointView fall into this category.
Jason Rhinelander17d02832017-01-16 20:35:14 -050062template <typename T> using is_eigen_other = all_of<
Jason Rhinelanderfa5d05e2016-12-12 18:11:49 -050063 is_template_base_of<Eigen::EigenBase, T>,
Jason Rhinelander17d02832017-01-16 20:35:14 -050064 negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>
Dean Moldovan71af3b02016-09-24 23:54:02 +020065>;
Jason Rhinelander9ffb3dd2016-08-04 15:24:41 -040066
Jason Rhinelander17d02832017-01-16 20:35:14 -050067// Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
68template <bool EigenRowMajor> struct EigenConformable {
69 bool conformable = false;
70 EigenIndex rows = 0, cols = 0;
71 EigenDStride stride{0, 0};
72
73 EigenConformable(bool fits = false) : conformable{fits} {}
74 // Matrix type:
75 EigenConformable(EigenIndex r, EigenIndex c,
76 EigenIndex rstride, EigenIndex cstride) :
77 conformable{true}, rows{r}, cols{c},
78 stride(EigenRowMajor ? rstride : cstride /* outer stride */,
79 EigenRowMajor ? cstride : rstride /* inner stride */)
80 {}
81 // Vector type:
82 EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride) : EigenConformable(r, c, r == 1 ? c*stride : stride, c == 1 ? r : r*stride) {}
83 template <typename props> bool stride_compatible() const {
84 return
85 (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()) &&
86 (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer());
87 }
88 operator bool() const { return conformable; }
89};
90
91template <typename Type> struct eigen_extract_stride { using type = Type; };
92template <typename PlainObjectType, int MapOptions, typename StrideType>
93struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> { using type = StrideType; };
94template <typename PlainObjectType, int Options, typename StrideType>
95struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> { using type = StrideType; };
96
97// Helper struct for extracting information from an Eigen type
98template <typename Type_> struct EigenProps {
99 using Type = Type_;
100 using Scalar = typename Type::Scalar;
101 using StrideType = typename eigen_extract_stride<Type>::type;
102 static constexpr EigenIndex
103 rows = Type::RowsAtCompileTime,
104 cols = Type::ColsAtCompileTime,
105 size = Type::SizeAtCompileTime;
106 static constexpr bool
107 row_major = Type::IsRowMajor,
108 vector = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
109 fixed_rows = rows != Eigen::Dynamic,
110 fixed_cols = cols != Eigen::Dynamic,
111 fixed = size != Eigen::Dynamic, // Fully-fixed size
112 dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
113
114 template <EigenIndex i, EigenIndex ifzero> using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
115 static constexpr EigenIndex inner_stride = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
116 outer_stride = if_zero<StrideType::OuterStrideAtCompileTime,
117 vector ? size : row_major ? cols : rows>::value;
118 static constexpr bool dynamic_stride = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
119 static constexpr bool requires_row_major = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
120 static constexpr bool requires_col_major = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
121
122 // Takes an input array and determines whether we can make it fit into the Eigen type. If
123 // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
124 // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
125 static EigenConformable<row_major> conformable(const array &a) {
126 const auto dims = a.ndim();
127 if (dims < 1 || dims > 2)
128 return false;
129
130 if (dims == 2) { // Matrix type: require exact match (or dynamic)
131
132 EigenIndex
133 np_rows = a.shape(0),
134 np_cols = a.shape(1),
135 np_rstride = a.strides(0) / sizeof(Scalar),
136 np_cstride = a.strides(1) / sizeof(Scalar);
137 if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols))
138 return false;
139
140 return {np_rows, np_cols, np_rstride, np_cstride};
141 }
142
143 // Otherwise we're storing an n-vector. Only one of the strides will be used, but whichever
144 // is used, we want the (single) numpy stride value.
145 const EigenIndex n = a.shape(0),
146 stride = a.strides(0) / sizeof(Scalar);
147
148 if (vector) { // Eigen type is a compile-time vector
149 if (fixed && size != n)
150 return false; // Vector size mismatch
151 return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
152 }
153 else if (fixed) {
154 // The type has a fixed size, but is not a vector: abort
155 return false;
156 }
157 else if (fixed_cols) {
158 // Since this isn't a vector, cols must be != 1. We allow this only if it exactly
159 // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
160 if (cols != n) return false;
161 return {1, n, stride};
162 }
163 else {
164 // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
165 if (fixed_rows && rows != n) return false;
166 return {n, 1, stride};
167 }
168 }
169
170 static PYBIND11_DESCR descriptor() {
171 constexpr bool show_writeable = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
172 constexpr bool show_order = is_eigen_dense_map<Type>::value;
173 constexpr bool show_c_contiguous = show_order && requires_row_major;
174 constexpr bool show_f_contiguous = !show_c_contiguous && show_order && requires_col_major;
175
176 return _("numpy.ndarray[") + npy_format_descriptor<Scalar>::name() +
177 _("[") + _<fixed_rows>(_<(size_t) rows>(), _("m")) +
178 _(", ") + _<fixed_cols>(_<(size_t) cols>(), _("n")) +
179 _("]") +
180 // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to be
181 // satisfied: writeable=True (for a mutable reference), and, depending on the map's stride
182 // options, possibly f_contiguous or c_contiguous. We include them in the descriptor output
183 // to provide some hint as to why a TypeError is occurring (otherwise it can be confusing to
184 // see that a function accepts a 'numpy.ndarray[float64[3,2]]' and an error message that you
185 // *gave* a numpy.ndarray of the right type and dimensions.
186 _<show_writeable>(", flags.writeable", "") +
187 _<show_c_contiguous>(", flags.c_contiguous", "") +
188 _<show_f_contiguous>(", flags.f_contiguous", "") +
189 _("]");
190 }
191};
192
193// Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
194// otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
195template <typename props> handle eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
196 constexpr size_t elem_size = sizeof(typename props::Scalar);
197 std::vector<size_t> shape, strides;
198 if (props::vector) {
199 shape.push_back(src.size());
200 strides.push_back(elem_size * src.innerStride());
201 }
202 else {
203 shape.push_back(src.rows());
204 shape.push_back(src.cols());
205 strides.push_back(elem_size * src.rowStride());
206 strides.push_back(elem_size * src.colStride());
207 }
208 array a(std::move(shape), std::move(strides), src.data(), base);
209 if (!writeable)
210 array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
211
212 return a.release();
213}
214
215// Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
216// reference the Eigen object's data with `base` as the python-registered base class (if omitted,
217// the base will be set to None, and lifetime management is up to the caller). The numpy array is
218// non-writeable if the given type is const.
219template <typename props, typename Type>
220handle eigen_ref_array(Type &src, handle parent = none()) {
221 // none here is to get past array's should-we-copy detection, which currently always
222 // copies when there is no base. Setting the base to None should be harmless.
223 return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
224}
225
226// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a numpy
227// array that references the encapsulated data with a python-side reference to the capsule to tie
228// its destruction to that of any dependent python objects. Const-ness is determined by whether or
229// not the Type of the pointer given is const.
230template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>
231handle eigen_encapsulate(Type *src) {
Dean Moldovan5687b332017-02-27 23:39:26 +0100232 capsule base(src, [](PyObject *o) { delete static_cast<Type *>(PyCapsule_GetPointer(o, nullptr)); });
Jason Rhinelander17d02832017-01-16 20:35:14 -0500233 return eigen_ref_array<props>(*src, base);
234}
235
236// Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
237// types.
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200238template<typename Type>
Jason Rhinelander17d02832017-01-16 20:35:14 -0500239struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
240 using Scalar = typename Type::Scalar;
241 using props = EigenProps<Type>;
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200242
243 bool load(handle src, bool) {
Dean Moldovan4de27102016-11-16 01:35:22 +0100244 auto buf = array_t<Scalar>::ensure(src);
Dean Moldovanb4498ef2016-10-23 14:50:08 +0200245 if (!buf)
Ivan Smirnov91b3d682016-08-29 02:41:05 +0100246 return false;
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200247
Jason Rhinelander17d02832017-01-16 20:35:14 -0500248 auto dims = buf.ndim();
249 if (dims < 1 || dims > 2)
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200250 return false;
Jason Rhinelander17d02832017-01-16 20:35:14 -0500251
252 auto fits = props::conformable(buf);
253 if (!fits)
254 return false; // Non-comformable vector/matrix types
255
256 value = Eigen::Map<const Type, 0, EigenDStride>(buf.data(), fits.rows, fits.cols, fits.stride);
257
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200258 return true;
259 }
260
Jason Rhinelander17d02832017-01-16 20:35:14 -0500261private:
262
263 // Cast implementation
264 template <typename CType>
265 static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
266 switch (policy) {
267 case return_value_policy::take_ownership:
268 case return_value_policy::automatic:
269 return eigen_encapsulate<props>(src);
270 case return_value_policy::move:
271 return eigen_encapsulate<props>(new CType(std::move(*src)));
272 case return_value_policy::copy:
273 return eigen_array_cast<props>(*src);
274 case return_value_policy::reference:
275 case return_value_policy::automatic_reference:
276 return eigen_ref_array<props>(*src);
277 case return_value_policy::reference_internal:
278 return eigen_ref_array<props>(*src, parent);
279 default:
280 throw cast_error("unhandled return_value_policy: should not happen!");
281 };
282 }
283
284public:
285
286 // Normal returned non-reference, non-const value:
287 static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
288 return cast_impl(&src, return_value_policy::move, parent);
289 }
290 // If you return a non-reference const, we mark the numpy array readonly:
291 static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
292 return cast_impl(&src, return_value_policy::move, parent);
293 }
294 // lvalue reference return; default (automatic) becomes copy
295 static handle cast(Type &src, return_value_policy policy, handle parent) {
296 if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
297 policy = return_value_policy::copy;
298 return cast_impl(&src, policy, parent);
299 }
300 // const lvalue reference return; default (automatic) becomes copy
301 static handle cast(const Type &src, return_value_policy policy, handle parent) {
302 if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
303 policy = return_value_policy::copy;
304 return cast(&src, policy, parent);
305 }
306 // non-const pointer return
307 static handle cast(Type *src, return_value_policy policy, handle parent) {
308 return cast_impl(src, policy, parent);
309 }
310 // const pointer return
311 static handle cast(const Type *src, return_value_policy policy, handle parent) {
312 return cast_impl(src, policy, parent);
313 }
314
315 static PYBIND11_DESCR name() { return type_descr(props::descriptor()); }
316
317 operator Type*() { return &value; }
318 operator Type&() { return value; }
319 template <typename T> using cast_op_type = cast_op_type<T>;
320
321private:
322 Type value;
323};
324
325// Eigen Ref/Map classes have slightly different policy requirements, meaning we don't want to force
326// `move` when a Ref/Map rvalue is returned; we treat Ref<> sort of like a pointer (we care about
327// the underlying data, not the outer shell).
328template <typename Return>
329struct return_value_policy_override<Return, enable_if_t<is_eigen_dense_map<Return>::value>> {
330 static return_value_policy policy(return_value_policy p) { return p; }
331};
332
333// Base class for casting reference/map/block/etc. objects back to python.
334template <typename MapType> struct eigen_map_caster {
335private:
336 using props = EigenProps<MapType>;
337
338public:
339
340 // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
341 // to stay around), but we'll allow it under the assumption that you know what you're doing (and
342 // have an appropriate keep_alive in place). We return a numpy array pointing directly at the
343 // ref's data (The numpy array ends up read-only if the ref was to a const matrix type.) Note
344 // that this means you need to ensure you don't destroy the object in some other way (e.g. with
345 // an appropriate keep_alive, or with a reference to a statically allocated matrix).
346 static handle cast(const MapType &src, return_value_policy policy, handle parent) {
347 switch (policy) {
348 case return_value_policy::copy:
349 return eigen_array_cast<props>(src);
350 case return_value_policy::reference_internal:
351 return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);
352 case return_value_policy::reference:
353 case return_value_policy::automatic:
354 case return_value_policy::automatic_reference:
355 return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);
356 default:
357 // move, take_ownership don't make any sense for a ref/map:
358 pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
Wenzel Jakoba970a572016-05-20 12:00:56 +0200359 }
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200360 }
361
Jason Rhinelander17d02832017-01-16 20:35:14 -0500362 static PYBIND11_DESCR name() { return props::descriptor(); }
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200363
Jason Rhinelander17d02832017-01-16 20:35:14 -0500364 // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
365 // types but not bound arguments). We still provide them (with an explicitly delete) so that
366 // you end up here if you try anyway.
367 bool load(handle, bool) = delete;
368 operator MapType() = delete;
369 template <typename> using cast_op_type = MapType;
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200370};
371
Jason Rhinelander17d02832017-01-16 20:35:14 -0500372// We can return any map-like object (but can only load Refs, specialized next):
373template <typename Type> struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>>
374 : eigen_map_caster<Type> {};
375
376// Loader for Ref<...> arguments. See the documentation for info on how to make this work without
377// copying (it requires some extra effort in many cases).
378template <typename PlainObjectType, typename StrideType>
379struct type_caster<
380 Eigen::Ref<PlainObjectType, 0, StrideType>,
381 enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>
382> : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
383private:
384 using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;
385 using props = EigenProps<Type>;
386 using Scalar = typename props::Scalar;
387 using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;
388 using Array = array_t<Scalar, array::forcecast |
389 ((props::row_major ? props::inner_stride : props::outer_stride) == 1 ? array::c_style :
390 (props::row_major ? props::outer_stride : props::inner_stride) == 1 ? array::f_style : 0)>;
391 static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
392 // Delay construction (these have no default constructor)
393 std::unique_ptr<MapType> map;
394 std::unique_ptr<Type> ref;
395 // Our array. When possible, this is just a numpy array pointing to the source data, but
396 // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an incompatible
397 // layout, or is an array of a type that needs to be converted). Using a numpy temporary
398 // (rather than an Eigen temporary) saves an extra copy when we need both type conversion and
399 // storage order conversion. (Note that we refuse to use this temporary copy when loading an
400 // argument for a Ref<M> with M non-const, i.e. a read-write reference).
401 Array copy_or_ref;
Jason Rhinelander5fd50742016-08-03 16:50:22 -0400402public:
Jason Rhinelander17d02832017-01-16 20:35:14 -0500403 bool load(handle src, bool convert) {
404 // First check whether what we have is already an array of the right type. If not, we can't
405 // avoid a copy (because the copy is also going to do type conversion).
406 bool need_copy = !isinstance<Array>(src);
Jason Rhinelander5fd50742016-08-03 16:50:22 -0400407
Jason Rhinelander17d02832017-01-16 20:35:14 -0500408 EigenConformable<props::row_major> fits;
409 if (!need_copy) {
410 // We don't need a converting copy, but we also need to check whether the strides are
411 // compatible with the Ref's stride requirements
412 Array aref = reinterpret_borrow<Array>(src);
Jason Rhinelander5fd50742016-08-03 16:50:22 -0400413
Jason Rhinelander17d02832017-01-16 20:35:14 -0500414 if (aref && (!need_writeable || aref.writeable())) {
415 fits = props::conformable(aref);
416 if (!fits) return false; // Incompatible dimensions
417 if (!fits.template stride_compatible<props>())
418 need_copy = true;
419 else
420 copy_or_ref = std::move(aref);
421 }
422 else {
423 need_copy = true;
424 }
425 }
426
427 if (need_copy) {
428 // We need to copy: If we need a mutable reference, or we're not supposed to convert
429 // (either because we're in the no-convert overload pass, or because we're explicitly
430 // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
431 if (!convert || need_writeable) return false;
432
433 Array copy = Array::ensure(src);
434 if (!copy) return false;
435 fits = props::conformable(copy);
436 if (!fits || !fits.template stride_compatible<props>())
437 return false;
Jason Rhinelanderdc5ce592017-03-13 12:49:10 -0300438 copy_or_ref = std::move(copy);
Jason Rhinelander17d02832017-01-16 20:35:14 -0500439 }
440
441 ref.reset();
442 map.reset(new MapType(data(copy_or_ref), fits.rows, fits.cols, make_stride(fits.stride.outer(), fits.stride.inner())));
443 ref.reset(new Type(*map));
444
445 return true;
446 }
447
448 operator Type*() { return ref.get(); }
449 operator Type&() { return *ref; }
Jason Rhinelander5fd50742016-08-03 16:50:22 -0400450 template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>;
Jason Rhinelander17d02832017-01-16 20:35:14 -0500451
452private:
453 template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>
454 Scalar *data(Array &a) { return a.mutable_data(); }
455
456 template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>
457 const Scalar *data(Array &a) { return a.data(); }
458
459 // Attempt to figure out a constructor of `Stride` that will work.
460 // If both strides are fixed, use a default constructor:
461 template <typename S> using stride_ctor_default = bool_constant<
462 S::InnerStrideAtCompileTime != Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic &&
463 std::is_default_constructible<S>::value>;
464 // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
465 // Eigen::Stride, and use it:
466 template <typename S> using stride_ctor_dual = bool_constant<
467 !stride_ctor_default<S>::value && std::is_constructible<S, EigenIndex, EigenIndex>::value>;
468 // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
469 // it (passing whichever stride is dynamic).
470 template <typename S> using stride_ctor_outer = bool_constant<
471 !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value &&
472 S::OuterStrideAtCompileTime == Eigen::Dynamic && S::InnerStrideAtCompileTime != Eigen::Dynamic &&
473 std::is_constructible<S, EigenIndex>::value>;
474 template <typename S> using stride_ctor_inner = bool_constant<
475 !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value &&
476 S::InnerStrideAtCompileTime == Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic &&
477 std::is_constructible<S, EigenIndex>::value>;
478
479 template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>
480 static S make_stride(EigenIndex, EigenIndex) { return S(); }
481 template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>
482 static S make_stride(EigenIndex outer, EigenIndex inner) { return S(outer, inner); }
483 template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>
484 static S make_stride(EigenIndex outer, EigenIndex) { return S(outer); }
485 template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>
486 static S make_stride(EigenIndex, EigenIndex inner) { return S(inner); }
487
Jason Rhinelander5fd50742016-08-03 16:50:22 -0400488};
489
Jason Rhinelander17d02832017-01-16 20:35:14 -0500490// type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
491// EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
492// load() is not supported, but we can cast them into the python domain by first copying to a
493// regular Eigen::Matrix, then casting that.
Jason Rhinelander9ffb3dd2016-08-04 15:24:41 -0400494template <typename Type>
Jason Rhinelander17d02832017-01-16 20:35:14 -0500495struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
Jason Rhinelander9ffb3dd2016-08-04 15:24:41 -0400496protected:
Jason Rhinelander17d02832017-01-16 20:35:14 -0500497 using Matrix = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
498 using props = EigenProps<Matrix>;
Jason Rhinelander9ffb3dd2016-08-04 15:24:41 -0400499public:
Jason Rhinelander17d02832017-01-16 20:35:14 -0500500 static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
501 handle h = eigen_encapsulate<props>(new Matrix(src));
502 return h;
503 }
504 static handle cast(const Type *src, return_value_policy policy, handle parent) { return cast(*src, policy, parent); }
Jason Rhinelander9ffb3dd2016-08-04 15:24:41 -0400505
Jason Rhinelander17d02832017-01-16 20:35:14 -0500506 static PYBIND11_DESCR name() { return props::descriptor(); }
Jason Rhinelander9ffb3dd2016-08-04 15:24:41 -0400507
Jason Rhinelander17d02832017-01-16 20:35:14 -0500508 // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
509 // types but not bound arguments). We still provide them (with an explicitly delete) so that
510 // you end up here if you try anyway.
511 bool load(handle, bool) = delete;
512 operator Type() = delete;
513 template <typename> using cast_op_type = Type;
Jason Rhinelander9ffb3dd2016-08-04 15:24:41 -0400514};
515
Jason Rhinelander5fd50742016-08-03 16:50:22 -0400516template<typename Type>
Wenzel Jakobc1fc27e2016-09-13 00:36:43 +0900517struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200518 typedef typename Type::Scalar Scalar;
519 typedef typename std::remove_reference<decltype(*std::declval<Type>().outerIndexPtr())>::type StorageIndex;
520 typedef typename Type::Index Index;
Jason Rhinelanderd9d224f2017-01-12 19:50:33 -0500521 static constexpr bool rowMajor = Type::IsRowMajor;
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200522
523 bool load(handle src, bool) {
Wenzel Jakob178c8a82016-05-10 15:59:01 +0100524 if (!src)
525 return false;
526
Dean Moldovanc7ac16b2016-10-28 03:08:15 +0200527 auto obj = reinterpret_borrow<object>(src);
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200528 object sparse_module = module::import("scipy.sparse");
529 object matrix_type = sparse_module.attr(
530 rowMajor ? "csr_matrix" : "csc_matrix");
531
532 if (obj.get_type() != matrix_type.ptr()) {
533 try {
Wenzel Jakob6c03beb2016-05-08 14:34:09 +0200534 obj = matrix_type(obj);
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200535 } catch (const error_already_set &) {
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200536 return false;
537 }
538 }
539
Ivan Smirnov91b3d682016-08-29 02:41:05 +0100540 auto values = array_t<Scalar>((object) obj.attr("data"));
541 auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
542 auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200543 auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
544 auto nnz = obj.attr("nnz").cast<Index>();
545
Dean Moldovanb4498ef2016-10-23 14:50:08 +0200546 if (!values || !innerIndices || !outerIndices)
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200547 return false;
548
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200549 value = Eigen::MappedSparseMatrix<Scalar, Type::Flags, StorageIndex>(
Ivan Smirnov91b3d682016-08-29 02:41:05 +0100550 shape[0].cast<Index>(), shape[1].cast<Index>(), nnz,
551 outerIndices.mutable_data(), innerIndices.mutable_data(), values.mutable_data());
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200552
553 return true;
554 }
555
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200556 static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
557 const_cast<Type&>(src).makeCompressed();
558
559 object matrix_type = module::import("scipy.sparse").attr(
560 rowMajor ? "csr_matrix" : "csc_matrix");
561
Ivan Smirnov6956b652016-08-15 01:24:59 +0100562 array data((size_t) src.nonZeros(), src.valuePtr());
563 array outerIndices((size_t) (rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
564 array innerIndices((size_t) src.nonZeros(), src.innerIndexPtr());
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200565
Wenzel Jakob6c03beb2016-05-08 14:34:09 +0200566 return matrix_type(
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200567 std::make_tuple(data, innerIndices, outerIndices),
568 std::make_pair(src.rows(), src.cols())
569 ).release();
570 }
571
Jason Rhinelanderd9d224f2017-01-12 19:50:33 -0500572 PYBIND11_TYPE_CASTER(Type, _<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[", "scipy.sparse.csc_matrix[")
Jason Rhinelander8469f752016-07-06 00:40:54 -0400573 + npy_format_descriptor<Scalar>::name() + _("]"));
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200574};
575
576NAMESPACE_END(detail)
577NAMESPACE_END(pybind11)
578
Jason Rhinelandercb637702016-12-13 19:09:08 -0500579#if defined(__GNUG__) || defined(__clang__)
580# pragma GCC diagnostic pop
581#elif defined(_MSC_VER)
582# pragma warning(pop)
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200583#endif