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