eigen.h revision 12037:d28054ac6ec9
1/*
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"
13
14#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__)
17#  pragma GCC diagnostic push
18#  pragma GCC diagnostic ignored "-Wconversion"
19#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
20#  if __GNUC__ >= 7
21#    pragma GCC diagnostic ignored "-Wint-in-bool-context"
22#  endif
23#endif
24
25#include <Eigen/Core>
26#include <Eigen/SparseCore>
27
28#if defined(_MSC_VER)
29#  pragma warning(push)
30#  pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
31#endif
32
33// 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
38NAMESPACE_BEGIN(pybind11)
39
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
45NAMESPACE_BEGIN(detail)
46
47#if EIGEN_VERSION_AT_LEAST(3,3,0)
48using EigenIndex = Eigen::Index;
49#else
50using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
51#endif
52
53// 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>;
58// 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.
62template <typename T> using is_eigen_other = all_of<
63    is_template_base_of<Eigen::EigenBase, T>,
64    negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>
65>;
66
67// 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)
83        : EigenConformable(r, c, r == 1 ? c*stride : stride, c == 1 ? r : r*stride) {}
84
85    template <typename props> bool stride_compatible() const {
86        // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
87        // matching strides, or a dimension size of 1 (in which case the stride value is irrelevant)
88        return
89            (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner() ||
90                (EigenRowMajor ? cols : rows) == 1) &&
91            (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer() ||
92                (EigenRowMajor ? rows : cols) == 1);
93    }
94    operator bool() const { return conformable; }
95};
96
97template <typename Type> struct eigen_extract_stride { using type = Type; };
98template <typename PlainObjectType, int MapOptions, typename StrideType>
99struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> { using type = StrideType; };
100template <typename PlainObjectType, int Options, typename StrideType>
101struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> { using type = StrideType; };
102
103// Helper struct for extracting information from an Eigen type
104template <typename Type_> struct EigenProps {
105    using Type = Type_;
106    using Scalar = typename Type::Scalar;
107    using StrideType = typename eigen_extract_stride<Type>::type;
108    static constexpr EigenIndex
109        rows = Type::RowsAtCompileTime,
110        cols = Type::ColsAtCompileTime,
111        size = Type::SizeAtCompileTime;
112    static constexpr bool
113        row_major = Type::IsRowMajor,
114        vector = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
115        fixed_rows = rows != Eigen::Dynamic,
116        fixed_cols = cols != Eigen::Dynamic,
117        fixed = size != Eigen::Dynamic, // Fully-fixed size
118        dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
119
120    template <EigenIndex i, EigenIndex ifzero> using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
121    static constexpr EigenIndex inner_stride = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
122                                outer_stride = if_zero<StrideType::OuterStrideAtCompileTime,
123                                                       vector ? size : row_major ? cols : rows>::value;
124    static constexpr bool dynamic_stride = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
125    static constexpr bool requires_row_major = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
126    static constexpr bool requires_col_major = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
127
128    // Takes an input array and determines whether we can make it fit into the Eigen type.  If
129    // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
130    // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
131    static EigenConformable<row_major> conformable(const array &a) {
132        const auto dims = a.ndim();
133        if (dims < 1 || dims > 2)
134            return false;
135
136        if (dims == 2) { // Matrix type: require exact match (or dynamic)
137
138            EigenIndex
139                np_rows = a.shape(0),
140                np_cols = a.shape(1),
141                np_rstride = a.strides(0) / sizeof(Scalar),
142                np_cstride = a.strides(1) / sizeof(Scalar);
143            if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols))
144                return false;
145
146            return {np_rows, np_cols, np_rstride, np_cstride};
147        }
148
149        // Otherwise we're storing an n-vector.  Only one of the strides will be used, but whichever
150        // is used, we want the (single) numpy stride value.
151        const EigenIndex n = a.shape(0),
152              stride = a.strides(0) / sizeof(Scalar);
153
154        if (vector) { // Eigen type is a compile-time vector
155            if (fixed && size != n)
156                return false; // Vector size mismatch
157            return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
158        }
159        else if (fixed) {
160            // The type has a fixed size, but is not a vector: abort
161            return false;
162        }
163        else if (fixed_cols) {
164            // Since this isn't a vector, cols must be != 1.  We allow this only if it exactly
165            // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
166            if (cols != n) return false;
167            return {1, n, stride};
168        }
169        else {
170            // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
171            if (fixed_rows && rows != n) return false;
172            return {n, 1, stride};
173        }
174    }
175
176    static PYBIND11_DESCR descriptor() {
177        constexpr bool show_writeable = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
178        constexpr bool show_order = is_eigen_dense_map<Type>::value;
179        constexpr bool show_c_contiguous = show_order && requires_row_major;
180        constexpr bool show_f_contiguous = !show_c_contiguous && show_order && requires_col_major;
181
182    return _("numpy.ndarray[") + npy_format_descriptor<Scalar>::name() +
183        _("[")  + _<fixed_rows>(_<(size_t) rows>(), _("m")) +
184        _(", ") + _<fixed_cols>(_<(size_t) cols>(), _("n")) +
185        _("]") +
186        // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to be
187        // satisfied: writeable=True (for a mutable reference), and, depending on the map's stride
188        // options, possibly f_contiguous or c_contiguous.  We include them in the descriptor output
189        // to provide some hint as to why a TypeError is occurring (otherwise it can be confusing to
190        // see that a function accepts a 'numpy.ndarray[float64[3,2]]' and an error message that you
191        // *gave* a numpy.ndarray of the right type and dimensions.
192        _<show_writeable>(", flags.writeable", "") +
193        _<show_c_contiguous>(", flags.c_contiguous", "") +
194        _<show_f_contiguous>(", flags.f_contiguous", "") +
195        _("]");
196    }
197};
198
199// Casts an Eigen type to numpy array.  If given a base, the numpy array references the src data,
200// otherwise it'll make a copy.  writeable lets you turn off the writeable flag for the array.
201template <typename props> handle eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
202    constexpr size_t elem_size = sizeof(typename props::Scalar);
203    std::vector<size_t> shape, strides;
204    if (props::vector) {
205        shape.push_back(src.size());
206        strides.push_back(elem_size * src.innerStride());
207    }
208    else {
209        shape.push_back(src.rows());
210        shape.push_back(src.cols());
211        strides.push_back(elem_size * src.rowStride());
212        strides.push_back(elem_size * src.colStride());
213    }
214    array a(std::move(shape), std::move(strides), src.data(), base);
215    if (!writeable)
216        array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
217
218    return a.release();
219}
220
221// Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
222// reference the Eigen object's data with `base` as the python-registered base class (if omitted,
223// the base will be set to None, and lifetime management is up to the caller).  The numpy array is
224// non-writeable if the given type is const.
225template <typename props, typename Type>
226handle eigen_ref_array(Type &src, handle parent = none()) {
227    // none here is to get past array's should-we-copy detection, which currently always
228    // copies when there is no base.  Setting the base to None should be harmless.
229    return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
230}
231
232// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a numpy
233// array that references the encapsulated data with a python-side reference to the capsule to tie
234// its destruction to that of any dependent python objects.  Const-ness is determined by whether or
235// not the Type of the pointer given is const.
236template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>
237handle eigen_encapsulate(Type *src) {
238    capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
239    return eigen_ref_array<props>(*src, base);
240}
241
242// Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
243// types.
244template<typename Type>
245struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
246    using Scalar = typename Type::Scalar;
247    using props = EigenProps<Type>;
248
249    bool load(handle src, bool) {
250        auto buf = array_t<Scalar>::ensure(src);
251        if (!buf)
252            return false;
253
254        auto dims = buf.ndim();
255        if (dims < 1 || dims > 2)
256            return false;
257
258        auto fits = props::conformable(buf);
259        if (!fits)
260            return false; // Non-comformable vector/matrix types
261
262        value = Eigen::Map<const Type, 0, EigenDStride>(buf.data(), fits.rows, fits.cols, fits.stride);
263
264        return true;
265    }
266
267private:
268
269    // Cast implementation
270    template <typename CType>
271    static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
272        switch (policy) {
273            case return_value_policy::take_ownership:
274            case return_value_policy::automatic:
275                return eigen_encapsulate<props>(src);
276            case return_value_policy::move:
277                return eigen_encapsulate<props>(new CType(std::move(*src)));
278            case return_value_policy::copy:
279                return eigen_array_cast<props>(*src);
280            case return_value_policy::reference:
281            case return_value_policy::automatic_reference:
282                return eigen_ref_array<props>(*src);
283            case return_value_policy::reference_internal:
284                return eigen_ref_array<props>(*src, parent);
285            default:
286                throw cast_error("unhandled return_value_policy: should not happen!");
287        };
288    }
289
290public:
291
292    // Normal returned non-reference, non-const value:
293    static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
294        return cast_impl(&src, return_value_policy::move, parent);
295    }
296    // If you return a non-reference const, we mark the numpy array readonly:
297    static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
298        return cast_impl(&src, return_value_policy::move, parent);
299    }
300    // lvalue reference return; default (automatic) becomes copy
301    static handle cast(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_impl(&src, policy, parent);
305    }
306    // const lvalue reference return; default (automatic) becomes copy
307    static handle cast(const Type &src, return_value_policy policy, handle parent) {
308        if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
309            policy = return_value_policy::copy;
310        return cast(&src, policy, parent);
311    }
312    // non-const pointer return
313    static handle cast(Type *src, return_value_policy policy, handle parent) {
314        return cast_impl(src, policy, parent);
315    }
316    // const pointer return
317    static handle cast(const Type *src, return_value_policy policy, handle parent) {
318        return cast_impl(src, policy, parent);
319    }
320
321    static PYBIND11_DESCR name() { return type_descr(props::descriptor()); }
322
323    operator Type*() { return &value; }
324    operator Type&() { return value; }
325    template <typename T> using cast_op_type = cast_op_type<T>;
326
327private:
328    Type value;
329};
330
331// Eigen Ref/Map classes have slightly different policy requirements, meaning we don't want to force
332// `move` when a Ref/Map rvalue is returned; we treat Ref<> sort of like a pointer (we care about
333// the underlying data, not the outer shell).
334template <typename Return>
335struct return_value_policy_override<Return, enable_if_t<is_eigen_dense_map<Return>::value>> {
336    static return_value_policy policy(return_value_policy p) { return p; }
337};
338
339// Base class for casting reference/map/block/etc. objects back to python.
340template <typename MapType> struct eigen_map_caster {
341private:
342    using props = EigenProps<MapType>;
343
344public:
345
346    // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
347    // to stay around), but we'll allow it under the assumption that you know what you're doing (and
348    // have an appropriate keep_alive in place).  We return a numpy array pointing directly at the
349    // ref's data (The numpy array ends up read-only if the ref was to a const matrix type.) Note
350    // that this means you need to ensure you don't destroy the object in some other way (e.g. with
351    // an appropriate keep_alive, or with a reference to a statically allocated matrix).
352    static handle cast(const MapType &src, return_value_policy policy, handle parent) {
353        switch (policy) {
354            case return_value_policy::copy:
355                return eigen_array_cast<props>(src);
356            case return_value_policy::reference_internal:
357                return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);
358            case return_value_policy::reference:
359            case return_value_policy::automatic:
360            case return_value_policy::automatic_reference:
361                return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);
362            default:
363                // move, take_ownership don't make any sense for a ref/map:
364                pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
365        }
366    }
367
368    static PYBIND11_DESCR name() { return props::descriptor(); }
369
370    // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
371    // types but not bound arguments).  We still provide them (with an explicitly delete) so that
372    // you end up here if you try anyway.
373    bool load(handle, bool) = delete;
374    operator MapType() = delete;
375    template <typename> using cast_op_type = MapType;
376};
377
378// We can return any map-like object (but can only load Refs, specialized next):
379template <typename Type> struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>>
380    : eigen_map_caster<Type> {};
381
382// Loader for Ref<...> arguments.  See the documentation for info on how to make this work without
383// copying (it requires some extra effort in many cases).
384template <typename PlainObjectType, typename StrideType>
385struct type_caster<
386    Eigen::Ref<PlainObjectType, 0, StrideType>,
387    enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>
388> : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
389private:
390    using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;
391    using props = EigenProps<Type>;
392    using Scalar = typename props::Scalar;
393    using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;
394    using Array = array_t<Scalar, array::forcecast |
395                ((props::row_major ? props::inner_stride : props::outer_stride) == 1 ? array::c_style :
396                 (props::row_major ? props::outer_stride : props::inner_stride) == 1 ? array::f_style : 0)>;
397    static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
398    // Delay construction (these have no default constructor)
399    std::unique_ptr<MapType> map;
400    std::unique_ptr<Type> ref;
401    // Our array.  When possible, this is just a numpy array pointing to the source data, but
402    // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an incompatible
403    // layout, or is an array of a type that needs to be converted).  Using a numpy temporary
404    // (rather than an Eigen temporary) saves an extra copy when we need both type conversion and
405    // storage order conversion.  (Note that we refuse to use this temporary copy when loading an
406    // argument for a Ref<M> with M non-const, i.e. a read-write reference).
407    Array copy_or_ref;
408public:
409    bool load(handle src, bool convert) {
410        // First check whether what we have is already an array of the right type.  If not, we can't
411        // avoid a copy (because the copy is also going to do type conversion).
412        bool need_copy = !isinstance<Array>(src);
413
414        EigenConformable<props::row_major> fits;
415        if (!need_copy) {
416            // We don't need a converting copy, but we also need to check whether the strides are
417            // compatible with the Ref's stride requirements
418            Array aref = reinterpret_borrow<Array>(src);
419
420            if (aref && (!need_writeable || aref.writeable())) {
421                fits = props::conformable(aref);
422                if (!fits) return false; // Incompatible dimensions
423                if (!fits.template stride_compatible<props>())
424                    need_copy = true;
425                else
426                    copy_or_ref = std::move(aref);
427            }
428            else {
429                need_copy = true;
430            }
431        }
432
433        if (need_copy) {
434            // We need to copy: If we need a mutable reference, or we're not supposed to convert
435            // (either because we're in the no-convert overload pass, or because we're explicitly
436            // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
437            if (!convert || need_writeable) return false;
438
439            Array copy = Array::ensure(src);
440            if (!copy) return false;
441            fits = props::conformable(copy);
442            if (!fits || !fits.template stride_compatible<props>())
443                return false;
444            copy_or_ref = std::move(copy);
445        }
446
447        ref.reset();
448        map.reset(new MapType(data(copy_or_ref), fits.rows, fits.cols, make_stride(fits.stride.outer(), fits.stride.inner())));
449        ref.reset(new Type(*map));
450
451        return true;
452    }
453
454    operator Type*() { return ref.get(); }
455    operator Type&() { return *ref; }
456    template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>;
457
458private:
459    template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>
460    Scalar *data(Array &a) { return a.mutable_data(); }
461
462    template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>
463    const Scalar *data(Array &a) { return a.data(); }
464
465    // Attempt to figure out a constructor of `Stride` that will work.
466    // If both strides are fixed, use a default constructor:
467    template <typename S> using stride_ctor_default = bool_constant<
468        S::InnerStrideAtCompileTime != Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic &&
469        std::is_default_constructible<S>::value>;
470    // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
471    // Eigen::Stride, and use it:
472    template <typename S> using stride_ctor_dual = bool_constant<
473        !stride_ctor_default<S>::value && std::is_constructible<S, EigenIndex, EigenIndex>::value>;
474    // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
475    // it (passing whichever stride is dynamic).
476    template <typename S> using stride_ctor_outer = bool_constant<
477        !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value &&
478        S::OuterStrideAtCompileTime == Eigen::Dynamic && S::InnerStrideAtCompileTime != Eigen::Dynamic &&
479        std::is_constructible<S, EigenIndex>::value>;
480    template <typename S> using stride_ctor_inner = bool_constant<
481        !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value &&
482        S::InnerStrideAtCompileTime == Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic &&
483        std::is_constructible<S, EigenIndex>::value>;
484
485    template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>
486    static S make_stride(EigenIndex, EigenIndex) { return S(); }
487    template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>
488    static S make_stride(EigenIndex outer, EigenIndex inner) { return S(outer, inner); }
489    template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>
490    static S make_stride(EigenIndex outer, EigenIndex) { return S(outer); }
491    template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>
492    static S make_stride(EigenIndex, EigenIndex inner) { return S(inner); }
493
494};
495
496// type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
497// EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
498// load() is not supported, but we can cast them into the python domain by first copying to a
499// regular Eigen::Matrix, then casting that.
500template <typename Type>
501struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
502protected:
503    using Matrix = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
504    using props = EigenProps<Matrix>;
505public:
506    static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
507        handle h = eigen_encapsulate<props>(new Matrix(src));
508        return h;
509    }
510    static handle cast(const Type *src, return_value_policy policy, handle parent) { return cast(*src, policy, parent); }
511
512    static PYBIND11_DESCR name() { return props::descriptor(); }
513
514    // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
515    // types but not bound arguments).  We still provide them (with an explicitly delete) so that
516    // you end up here if you try anyway.
517    bool load(handle, bool) = delete;
518    operator Type() = delete;
519    template <typename> using cast_op_type = Type;
520};
521
522template<typename Type>
523struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
524    typedef typename Type::Scalar Scalar;
525    typedef typename std::remove_reference<decltype(*std::declval<Type>().outerIndexPtr())>::type StorageIndex;
526    typedef typename Type::Index Index;
527    static constexpr bool rowMajor = Type::IsRowMajor;
528
529    bool load(handle src, bool) {
530        if (!src)
531            return false;
532
533        auto obj = reinterpret_borrow<object>(src);
534        object sparse_module = module::import("scipy.sparse");
535        object matrix_type = sparse_module.attr(
536            rowMajor ? "csr_matrix" : "csc_matrix");
537
538        if (obj.get_type() != matrix_type.ptr()) {
539            try {
540                obj = matrix_type(obj);
541            } catch (const error_already_set &) {
542                return false;
543            }
544        }
545
546        auto values = array_t<Scalar>((object) obj.attr("data"));
547        auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
548        auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
549        auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
550        auto nnz = obj.attr("nnz").cast<Index>();
551
552        if (!values || !innerIndices || !outerIndices)
553            return false;
554
555        value = Eigen::MappedSparseMatrix<Scalar, Type::Flags, StorageIndex>(
556            shape[0].cast<Index>(), shape[1].cast<Index>(), nnz,
557            outerIndices.mutable_data(), innerIndices.mutable_data(), values.mutable_data());
558
559        return true;
560    }
561
562    static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
563        const_cast<Type&>(src).makeCompressed();
564
565        object matrix_type = module::import("scipy.sparse").attr(
566            rowMajor ? "csr_matrix" : "csc_matrix");
567
568        array data((size_t) src.nonZeros(), src.valuePtr());
569        array outerIndices((size_t) (rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
570        array innerIndices((size_t) src.nonZeros(), src.innerIndexPtr());
571
572        return matrix_type(
573            std::make_tuple(data, innerIndices, outerIndices),
574            std::make_pair(src.rows(), src.cols())
575        ).release();
576    }
577
578    PYBIND11_TYPE_CASTER(Type, _<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[", "scipy.sparse.csc_matrix[")
579            + npy_format_descriptor<Scalar>::name() + _("]"));
580};
581
582NAMESPACE_END(detail)
583NAMESPACE_END(pybind11)
584
585#if defined(__GNUG__) || defined(__clang__)
586#  pragma GCC diagnostic pop
587#elif defined(_MSC_VER)
588#  pragma warning(pop)
589#endif
590