matrix.h
Go to the documentation of this file.
1 /*
2  pybind11/eigen/matrix.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 #include "common.h"
14 
15 /* HINT: To suppress warnings originating from the Eigen headers, use -isystem.
16  See also:
17  https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir
18  https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler
19 */
20 PYBIND11_WARNING_PUSH
21 PYBIND11_WARNING_DISABLE_MSVC(5054) // https://github.com/pybind/pybind11/pull/3741
22 // C5054: operator '&': deprecated between enumerations of different types
23 #if defined(__MINGW32__)
24 PYBIND11_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
25 #endif
26 
27 #include <Eigen/Core>
28 #include <Eigen/SparseCore>
29 
31 
32 // Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
33 // move constructors that break things. We could detect this an explicitly copy, but an extra copy
34 // of matrices seems highly undesirable.
35 static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
36  "Eigen matrix support in pybind11 requires Eigen >= 3.2.7");
37 
39 
41 
42 // Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
43 using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
44 template <typename MatrixType>
45 using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
46 template <typename MatrixType>
47 using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
48 
50 
51 #if EIGEN_VERSION_AT_LEAST(3, 3, 0)
52 using EigenIndex = Eigen::Index;
53 template <typename Scalar, int Flags, typename StorageIndex>
55 #else
56 using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
57 template <typename Scalar, int Flags, typename StorageIndex>
59 #endif
60 
61 // Matches Eigen::Map, Eigen::Ref, blocks, etc:
62 template <typename T>
63 using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>,
64  std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
65 template <typename T>
66 using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
67 template <typename T>
68 using is_eigen_dense_plain
70 template <typename T>
72 // Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
73 // basically covers anything that can be assigned to a dense matrix but that don't have a typical
74 // matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
75 // SelfAdjointView fall into this category.
76 template <typename T>
77 using is_eigen_other
79  negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>>;
80 
81 // Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
82 template <bool EigenRowMajor>
83 struct EigenConformable {
84  bool conformable = false;
85  EigenIndex rows = 0, cols = 0;
86  EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
87  bool negativestrides = false; // If true, do not use stride!
88 
89  // NOLINTNEXTLINE(google-explicit-constructor)
90  EigenConformable(bool fits = false) : conformable{fits} {}
91  // Matrix type:
92  EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
93  : conformable{true}, rows{r}, cols{c},
94  // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
95  // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
96  stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
97  : (cstride > 0 ? cstride : 0) /* outer stride */,
98  EigenRowMajor ? (cstride > 0 ? cstride : 0)
99  : (rstride > 0 ? rstride : 0) /* inner stride */},
100  negativestrides{rstride < 0 || cstride < 0} {}
101  // Vector type:
102  EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
103  : EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
104 
105  template <typename props>
106  bool stride_compatible() const {
107  // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
108  // matching strides, or a dimension size of 1 (in which case the stride value is
109  // irrelevant). Alternatively, if any dimension size is 0, the strides are not relevant
110  // (and numpy ≥ 1.23 sets the strides to 0 in that case, so we need to check explicitly).
111  if (negativestrides) {
112  return false;
113  }
114  if (rows == 0 || cols == 0) {
115  return true;
116  }
117  return (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
118  || (EigenRowMajor ? cols : rows) == 1)
119  && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
120  || (EigenRowMajor ? rows : cols) == 1);
121  }
122  // NOLINTNEXTLINE(google-explicit-constructor)
123  operator bool() const { return conformable; }
124 };
125 
126 template <typename Type>
127 struct eigen_extract_stride {
128  using type = Type;
129 };
130 template <typename PlainObjectType, int MapOptions, typename StrideType>
131 struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {
132  using type = StrideType;
133 };
134 template <typename PlainObjectType, int Options, typename StrideType>
135 struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {
136  using type = StrideType;
137 };
138 
139 // Helper struct for extracting information from an Eigen type
140 template <typename Type_>
141 struct EigenProps {
142  using Type = Type_;
143  using Scalar = typename Type::Scalar;
144  using StrideType = typename eigen_extract_stride<Type>::type;
145  static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
146  size = Type::SizeAtCompileTime;
147  static constexpr bool row_major = Type::IsRowMajor,
148  vector
149  = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
150  fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
151  fixed = size != Eigen::Dynamic, // Fully-fixed size
152  dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
153 
154  template <EigenIndex i, EigenIndex ifzero>
155  using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
156  static constexpr EigenIndex inner_stride
158  outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
159  vector ? size
160  : row_major ? cols
161  : rows > ::value;
162  static constexpr bool dynamic_stride
163  = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
164  static constexpr bool requires_row_major
165  = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
166  static constexpr bool requires_col_major
167  = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
168 
169  // Takes an input array and determines whether we can make it fit into the Eigen type. If
170  // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
171  // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
172  static EigenConformable<row_major> conformable(const array &a) {
173  const auto dims = a.ndim();
174  if (dims < 1 || dims > 2) {
175  return false;
176  }
177 
178  if (dims == 2) { // Matrix type: require exact match (or dynamic)
179 
180  EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
181  np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
182  np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
183  if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols)) {
184  return false;
185  }
186 
187  return {np_rows, np_cols, np_rstride, np_cstride};
188  }
189 
190  // Otherwise we're storing an n-vector. Only one of the strides will be used, but
191  // whichever is used, we want the (single) numpy stride value.
192  const EigenIndex n = a.shape(0),
193  stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
194 
195  if (vector) { // Eigen type is a compile-time vector
196  if (fixed && size != n) {
197  return false; // Vector size mismatch
198  }
199  return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
200  }
201  if (fixed) {
202  // The type has a fixed size, but is not a vector: abort
203  return false;
204  }
205  if (fixed_cols) {
206  // Since this isn't a vector, cols must be != 1. We allow this only if it exactly
207  // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
208  if (cols != n) {
209  return false;
210  }
211  return {1, n, stride};
212  } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
213  if (fixed_rows && rows != n) {
214  return false;
215  }
216  return {n, 1, stride};
217  }
218 
219  static constexpr bool show_writeable
221  static constexpr bool show_order = is_eigen_dense_map<Type>::value;
222  static constexpr bool show_c_contiguous = show_order && requires_row_major;
223  static constexpr bool show_f_contiguous
224  = !show_c_contiguous && show_order && requires_col_major;
225 
226  static constexpr auto descriptor
227  = const_name("numpy.ndarray[") + npy_format_descriptor<Scalar>::name + const_name("[")
228  + const_name<fixed_rows>(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
229  + const_name<fixed_cols>(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
230  +
231  // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to
232  // be satisfied: writeable=True (for a mutable reference), and, depending on the map's
233  // stride options, possibly f_contiguous or c_contiguous. We include them in the
234  // descriptor output to provide some hint as to why a TypeError is occurring (otherwise
235  // it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
236  // an error message that you *gave* a numpy.ndarray of the right type and dimensions.
237  const_name<show_writeable>(", flags.writeable", "")
238  + const_name<show_c_contiguous>(", flags.c_contiguous", "")
239  + const_name<show_f_contiguous>(", flags.f_contiguous", "") + const_name("]");
240 };
241 
242 // Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
243 // otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
244 template <typename props>
245 handle
246 eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
247  constexpr ssize_t elem_size = sizeof(typename props::Scalar);
248  array a;
249  if (props::vector) {
250  a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
251  } else {
252  a = array({src.rows(), src.cols()},
253  {elem_size * src.rowStride(), elem_size * src.colStride()},
254  src.data(),
255  base);
256  }
257 
258  if (!writeable) {
260  }
261 
262  return a.release();
263 }
264 
265 // Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
266 // reference the Eigen object's data with `base` as the python-registered base class (if omitted,
267 // the base will be set to None, and lifetime management is up to the caller). The numpy array is
268 // non-writeable if the given type is const.
269 template <typename props, typename Type>
270 handle eigen_ref_array(Type &src, handle parent = none()) {
271  // none here is to get past array's should-we-copy detection, which currently always
272  // copies when there is no base. Setting the base to None should be harmless.
273  return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
274 }
275 
276 // Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
277 // numpy array that references the encapsulated data with a python-side reference to the capsule to
278 // tie its destruction to that of any dependent python objects. Const-ness is determined by
279 // whether or not the Type of the pointer given is const.
281 handle eigen_encapsulate(Type *src) {
282  capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
283  return eigen_ref_array<props>(*src, base);
284 }
285 
286 // Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
287 // types.
288 template <typename Type>
289 struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
290  using Scalar = typename Type::Scalar;
291  static_assert(!std::is_pointer<Scalar>::value,
293  using props = EigenProps<Type>;
294 
295  bool load(handle src, bool convert) {
296  // If we're in no-convert mode, only load if given an array of the correct type
297  if (!convert && !isinstance<array_t<Scalar>>(src)) {
298  return false;
299  }
300 
301  // Coerce into an array, but don't do type conversion yet; the copy below handles it.
302  auto buf = array::ensure(src);
303 
304  if (!buf) {
305  return false;
306  }
307 
308  auto dims = buf.ndim();
309  if (dims < 1 || dims > 2) {
310  return false;
311  }
312 
313  auto fits = props::conformable(buf);
314  if (!fits) {
315  return false;
316  }
317 
318  // Allocate the new type, then build a numpy reference into it
319  value = Type(fits.rows, fits.cols);
320  auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));
321  if (dims == 1) {
322  ref = ref.squeeze();
323  } else if (ref.ndim() == 1) {
324  buf = buf.squeeze();
325  }
326 
327  int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
328 
329  if (result < 0) { // Copy failed!
330  PyErr_Clear();
331  return false;
332  }
333 
334  return true;
335  }
336 
337 private:
338  // Cast implementation
339  template <typename CType>
340  static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
341  switch (policy) {
344  return eigen_encapsulate<props>(src);
346  return eigen_encapsulate<props>(new CType(std::move(*src)));
348  return eigen_array_cast<props>(*src);
351  return eigen_ref_array<props>(*src);
353  return eigen_ref_array<props>(*src, parent);
354  default:
355  throw cast_error("unhandled return_value_policy: should not happen!");
356  };
357  }
358 
359 public:
360  // Normal returned non-reference, non-const value:
361  static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
362  return cast_impl(&src, return_value_policy::move, parent);
363  }
364  // If you return a non-reference const, we mark the numpy array readonly:
365  static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
366  return cast_impl(&src, return_value_policy::move, parent);
367  }
368  // lvalue reference return; default (automatic) becomes copy
369  static handle cast(Type &src, return_value_policy policy, handle parent) {
370  if (policy == return_value_policy::automatic
372  policy = return_value_policy::copy;
373  }
374  return cast_impl(&src, policy, parent);
375  }
376  // const lvalue reference return; default (automatic) becomes copy
377  static handle cast(const Type &src, return_value_policy policy, handle parent) {
378  if (policy == return_value_policy::automatic
380  policy = return_value_policy::copy;
381  }
382  return cast(&src, policy, parent);
383  }
384  // non-const pointer return
385  static handle cast(Type *src, return_value_policy policy, handle parent) {
386  return cast_impl(src, policy, parent);
387  }
388  // const pointer return
389  static handle cast(const Type *src, return_value_policy policy, handle parent) {
390  return cast_impl(src, policy, parent);
391  }
392 
393  static constexpr auto name = props::descriptor;
394 
395  // NOLINTNEXTLINE(google-explicit-constructor)
396  operator Type *() { return &value; }
397  // NOLINTNEXTLINE(google-explicit-constructor)
398  operator Type &() { return value; }
399  // NOLINTNEXTLINE(google-explicit-constructor)
400  operator Type &&() && { return std::move(value); }
401  template <typename T>
403 
404 private:
405  Type value;
406 };
407 
408 // Base class for casting reference/map/block/etc. objects back to python.
409 template <typename MapType>
410 struct eigen_map_caster {
413 
414 private:
415  using props = EigenProps<MapType>;
416 
417 public:
418  // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
419  // to stay around), but we'll allow it under the assumption that you know what you're doing
420  // (and have an appropriate keep_alive in place). We return a numpy array pointing directly at
421  // the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)
422  // Note that this means you need to ensure you don't destroy the object in some other way (e.g.
423  // with an appropriate keep_alive, or with a reference to a statically allocated matrix).
424  static handle cast(const MapType &src, return_value_policy policy, handle parent) {
425  switch (policy) {
427  return eigen_array_cast<props>(src);
429  return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);
433  return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);
434  default:
435  // move, take_ownership don't make any sense for a ref/map:
436  pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
437  }
438  }
439 
440  static constexpr auto name = props::descriptor;
441 
442  // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
443  // types but not bound arguments). We still provide them (with an explicitly delete) so that
444  // you end up here if you try anyway.
445  bool load(handle, bool) = delete;
446  operator MapType() = delete;
447  template <typename>
448  using cast_op_type = MapType;
449 };
450 
451 // We can return any map-like object (but can only load Refs, specialized next):
452 template <typename Type>
453 struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {};
454 
455 // Loader for Ref<...> arguments. See the documentation for info on how to make this work without
456 // copying (it requires some extra effort in many cases).
457 template <typename PlainObjectType, typename StrideType>
458 struct type_caster<
459  Eigen::Ref<PlainObjectType, 0, StrideType>,
460  enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>>
461  : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
462 private:
464  using props = EigenProps<Type>;
465  using Scalar = typename props::Scalar;
466  static_assert(!std::is_pointer<Scalar>::value,
469  using Array
470  = array_t<Scalar,
472  | ((props::row_major ? props::inner_stride : props::outer_stride) == 1
474  : (props::row_major ? props::outer_stride : props::inner_stride) == 1
476  : 0)>;
477  static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
478  // Delay construction (these have no default constructor)
479  std::unique_ptr<MapType> map;
480  std::unique_ptr<Type> ref;
481  // Our array. When possible, this is just a numpy array pointing to the source data, but
482  // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
483  // incompatible layout, or is an array of a type that needs to be converted). Using a numpy
484  // temporary (rather than an Eigen temporary) saves an extra copy when we need both type
485  // conversion and storage order conversion. (Note that we refuse to use this temporary copy
486  // when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).
487  Array copy_or_ref;
488 
489 public:
490  bool load(handle src, bool convert) {
491  // First check whether what we have is already an array of the right type. If not, we
492  // can't avoid a copy (because the copy is also going to do type conversion).
493  bool need_copy = !isinstance<Array>(src);
494 
495  EigenConformable<props::row_major> fits;
496  if (!need_copy) {
497  // We don't need a converting copy, but we also need to check whether the strides are
498  // compatible with the Ref's stride requirements
499  auto aref = reinterpret_borrow<Array>(src);
500 
501  if (aref && (!need_writeable || aref.writeable())) {
502  fits = props::conformable(aref);
503  if (!fits) {
504  return false; // Incompatible dimensions
505  }
506  if (!fits.template stride_compatible<props>()) {
507  need_copy = true;
508  } else {
509  copy_or_ref = std::move(aref);
510  }
511  } else {
512  need_copy = true;
513  }
514  }
515 
516  if (need_copy) {
517  // We need to copy: If we need a mutable reference, or we're not supposed to convert
518  // (either because we're in the no-convert overload pass, or because we're explicitly
519  // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
520  if (!convert || need_writeable) {
521  return false;
522  }
523 
524  Array copy = Array::ensure(src);
525  if (!copy) {
526  return false;
527  }
528  fits = props::conformable(copy);
529  if (!fits || !fits.template stride_compatible<props>()) {
530  return false;
531  }
532  copy_or_ref = std::move(copy);
534  }
535 
536  ref.reset();
537  map.reset(new MapType(data(copy_or_ref),
538  fits.rows,
539  fits.cols,
540  make_stride(fits.stride.outer(), fits.stride.inner())));
541  ref.reset(new Type(*map));
542 
543  return true;
544  }
545 
546  // NOLINTNEXTLINE(google-explicit-constructor)
547  operator Type *() { return ref.get(); }
548  // NOLINTNEXTLINE(google-explicit-constructor)
549  operator Type &() { return *ref; }
550  template <typename _T>
551  using cast_op_type = pybind11::detail::cast_op_type<_T>;
552 
553 private:
555  Scalar *data(Array &a) {
556  return a.mutable_data();
557  }
558 
560  const Scalar *data(Array &a) {
561  return a.data();
562  }
563 
564  // Attempt to figure out a constructor of `Stride` that will work.
565  // If both strides are fixed, use a default constructor:
566  template <typename S>
567  using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic
568  && S::OuterStrideAtCompileTime != Eigen::Dynamic
570  // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
571  // Eigen::Stride, and use it:
572  template <typename S>
573  using stride_ctor_dual
576  // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
577  // it (passing whichever stride is dynamic).
578  template <typename S>
579  using stride_ctor_outer
581  && S::OuterStrideAtCompileTime == Eigen::Dynamic
582  && S::InnerStrideAtCompileTime != Eigen::Dynamic
584  template <typename S>
585  using stride_ctor_inner
587  && S::InnerStrideAtCompileTime == Eigen::Dynamic
588  && S::OuterStrideAtCompileTime != Eigen::Dynamic
590 
592  static S make_stride(EigenIndex, EigenIndex) {
593  return S();
594  }
596  static S make_stride(EigenIndex outer, EigenIndex inner) {
597  return S(outer, inner);
598  }
600  static S make_stride(EigenIndex outer, EigenIndex) {
601  return S(outer);
602  }
604  static S make_stride(EigenIndex, EigenIndex inner) {
605  return S(inner);
606  }
607 };
608 
609 // type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
610 // EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
611 // load() is not supported, but we can cast them into the python domain by first copying to a
612 // regular Eigen::Matrix, then casting that.
613 template <typename Type>
614 struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
617 
618 protected:
619  using Matrix
621  using props = EigenProps<Matrix>;
622 
623 public:
624  static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
625  handle h = eigen_encapsulate<props>(new Matrix(src));
626  return h;
627  }
628  static handle cast(const Type *src, return_value_policy policy, handle parent) {
629  return cast(*src, policy, parent);
630  }
631 
632  static constexpr auto name = props::descriptor;
633 
634  // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
635  // types but not bound arguments). We still provide them (with an explicitly delete) so that
636  // you end up here if you try anyway.
637  bool load(handle, bool) = delete;
638  operator Type() = delete;
639  template <typename>
640  using cast_op_type = Type;
641 };
642 
643 template <typename Type>
644 struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
645  using Scalar = typename Type::Scalar;
646  static_assert(!std::is_pointer<Scalar>::value,
648  using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>;
649  using Index = typename Type::Index;
650  static constexpr bool rowMajor = Type::IsRowMajor;
651 
652  bool load(handle src, bool) {
653  if (!src) {
654  return false;
655  }
656 
657  auto obj = reinterpret_borrow<object>(src);
658  object sparse_module = module_::import("scipy.sparse");
659  object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
660 
661  if (!type::handle_of(obj).is(matrix_type)) {
662  try {
663  obj = matrix_type(obj);
664  } catch (const error_already_set &) {
665  return false;
666  }
667  }
668 
669  auto values = array_t<Scalar>((object) obj.attr("data"));
670  auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
671  auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
672  auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
673  auto nnz = obj.attr("nnz").cast<Index>();
674 
675  if (!values || !innerIndices || !outerIndices) {
676  return false;
677  }
678 
679  value = EigenMapSparseMatrix<Scalar,
680  Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),
681  StorageIndex>(shape[0].cast<Index>(),
682  shape[1].cast<Index>(),
683  std::move(nnz),
684  outerIndices.mutable_data(),
685  innerIndices.mutable_data(),
686  values.mutable_data());
687 
688  return true;
689  }
690 
691  static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
692  const_cast<Type &>(src).makeCompressed();
693 
694  object matrix_type
695  = module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
696 
697  array data(src.nonZeros(), src.valuePtr());
698  array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
699  array innerIndices(src.nonZeros(), src.innerIndexPtr());
700 
701  return matrix_type(pybind11::make_tuple(
702  std::move(data), std::move(innerIndices), std::move(outerIndices)),
703  pybind11::make_tuple(src.rows(), src.cols()))
704  .release();
705  }
706 
708  const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
709  "scipy.sparse.csc_matrix[")
711 };
712 
return_value_policy::reference_internal
@ reference_internal
module_::import
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Definition: pybind11.h:1278
npy_api::NPY_ARRAY_WRITEABLE_
@ NPY_ARRAY_WRITEABLE_
Definition: numpy.h:222
common.h
array::forcecast
@ forcecast
Definition: numpy.h:828
return_value_policy::move
@ move
all_of
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
Definition: wrap/pybind11/include/pybind11/detail/common.h:740
npy_format_descriptor
Definition: numpy.h:65
Eigen
Namespace containing all symbols from the Eigen library.
Definition: jet.h:637
name
Annotation for function names.
Definition: attr.h:51
base
Annotation indicating that a class derives from another given type.
Definition: attr.h:64
array
int array[24]
Definition: Map_general_stride.cpp:1
gtsam.examples.DogLegOptimizerExample.type
type
Definition: DogLegOptimizerExample.py:111
ssize_t
Py_ssize_t ssize_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:489
error_already_set
Definition: pytypes.h:739
PYBIND11_WARNING_DISABLE_GCC
#define PYBIND11_WARNING_DISABLE_GCC(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:67
movable_cast_op_type
conditional_t< std::is_pointer< typename std::remove_reference< T >::type >::value, typename std::add_pointer< intrinsic_t< T > >::type, conditional_t< std::is_rvalue_reference< T >::value, typename std::add_rvalue_reference< intrinsic_t< T > >::type, typename std::add_lvalue_reference< intrinsic_t< T > >::type > > movable_cast_op_type
Definition: type_caster_base.h:856
const_name
constexpr descr< N - 1 > const_name(char const (&text)[N])
Definition: descr.h:60
MatrixType
MatrixXf MatrixType
Definition: benchmark-blocking-sizes.cpp:52
return_value_policy
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: wrap/pybind11/include/pybind11/detail/common.h:499
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
type_caster_generic::value
void * value
Definition: type_caster_base.h:828
array::c_style
@ c_style
Definition: numpy.h:826
PYBIND11_WARNING_POP
PYBIND11_WARNING_PUSH PYBIND11_WARNING_POP
Definition: tensor.h:30
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
capsule
Definition: pytypes.h:1951
is_template_base_of
decltype(is_template_base_of_impl< Base >::check((intrinsic_t< T > *) nullptr)) is_template_base_of
Definition: wrap/pybind11/include/pybind11/detail/common.h:927
makeCompressed
A makeCompressed()
type
Definition: pytypes.h:1525
different_sigmas::values
HybridValues values
Definition: testHybridBayesNet.cpp:245
detail
Definition: testSerializationNonlinear.cpp:70
Eigen::RowMajor
@ RowMajor
Definition: Constants.h:321
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
h
const double h
Definition: testSimpleHelicopter.cpp:19
EIGEN_DEFAULT_DENSE_INDEX_TYPE
#define EIGEN_DEFAULT_DENSE_INDEX_TYPE
Definition: tensor_benchmarks.h:5
result
Values result
Definition: OdometryOptimize.cpp:8
array::f_style
@ f_style
Definition: numpy.h:827
rows
int rows
Definition: Tutorial_commainit_02.cpp:1
size
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
n
int n
Definition: BiCGSTAB_simple.cpp:1
array_t
Definition: numpy.h:1155
type_caster_base::cast
static handle cast(const itype &src, return_value_policy policy, handle parent)
Definition: type_caster_base.h:1105
ceres::Matrix
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > Matrix
Definition: gtsam/3rdparty/ceres/eigen.h:42
Type
Definition: typing.h:67
isinstance
bool isinstance(handle obj)
Definition: pytypes.h:842
return_value_policy::automatic
@ automatic
data
int data[]
Definition: Map_placement_new.cpp:1
handle
Definition: pytypes.h:226
type_caster
Definition: cast.h:38
type::handle_of
static handle handle_of()
Definition: cast.h:1828
make_tuple
tuple make_tuple()
Definition: cast.h:1383
return_value_policy::copy
@ copy
object::release
handle release()
Definition: pytypes.h:385
Eigen::Dynamic
const int Dynamic
Definition: Constants.h:22
Eigen::Architecture::Type
Type
Definition: Constants.h:471
return_value_policy::reference
@ reference
negation
Definition: wrap/pybind11/include/pybind11/detail/common.h:713
PYBIND11_NAMESPACE
Definition: test_custom_type_casters.cpp:24
Eigen::Triplet
A small structure to hold a non zero as a triplet (i,j,value).
Definition: SparseUtil.h:162
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1026
Eigen::Map
A matrix or vector expression mapping an existing array of data.
Definition: Map.h:94
cast_op_type
conditional_t< std::is_pointer< remove_reference_t< T > >::value, typename std::add_pointer< intrinsic_t< T > >::type, typename std::add_lvalue_reference< intrinsic_t< T > >::type > cast_op_type
Definition: type_caster_base.h:841
PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED
#define PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED
Definition: wrap/pybind11/include/pybind11/eigen/common.h:7
PYBIND11_TYPE_CASTER
#define PYBIND11_TYPE_CASTER(type, py_name)
Definition: cast.h:87
bool_constant
std::integral_constant< bool, B > bool_constant
Backports of std::bool_constant and std::negation to accommodate older compilers.
Definition: wrap/pybind11/include/pybind11/detail/common.h:711
return_value_policy::take_ownership
@ take_ownership
a
ArrayXXi a
Definition: Array_initializer_list_23_cxx11.cpp:1
array
Definition: numpy.h:821
Eigen::Ref
A matrix or vector expression mapping an existing expression.
Definition: Ref.h:281
PYBIND11_WARNING_DISABLE_MSVC
PYBIND11_WARNING_PUSH PYBIND11_WARNING_DISABLE_MSVC(5054) PYBIND11_WARNING_POP static_assert(EIGEN_VERSION_AT_LEAST(3
array::ensure
static array ensure(handle h, int ExtraFlags=0)
Definition: numpy.h:1097
ref
Reference counting helper.
Definition: object.h:67
PyArray_Proxy::flags
int flags
Definition: numpy.h:128
Eigen::Matrix
The matrix class, also used for vectors and row-vectors.
Definition: 3rdparty/Eigen/Eigen/src/Core/Matrix.h:178
type_caster_generic::load
bool load(handle src, bool convert)
Definition: type_caster_base.h:539
Eigen::ColMajor
@ ColMajor
Definition: Constants.h:319
cols
int cols
Definition: Tutorial_commainit_02.cpp:1
none
Definition: pytypes.h:1786
EIGEN_VERSION_AT_LEAST
#define EIGEN_VERSION_AT_LEAST(x, y, z)
Definition: Macros.h:22
return_value_policy::automatic_reference
@ automatic_reference
gtsam::convert
static BinaryMeasurement< Rot3 > convert(const BetweenFactor< Pose3 >::shared_ptr &f)
Definition: ShonanAveraging.cpp:993
get
Container::iterator get(Container &c, Position position)
Definition: stdlist_overload.cpp:29
enable_if_t
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: wrap/pybind11/include/pybind11/detail/common.h:654
MapType
Map< MatrixType > MapType
Definition: Tutorial_Map_using.cpp:2
test_callbacks.value
value
Definition: test_callbacks.py:160
loader_life_support::add_patient
static PYBIND11_NOINLINE void add_patient(handle h)
Definition: type_caster_base.h:71
Eigen::internal::cast
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
Definition: Eigen/src/Core/MathFunctions.h:460
Eigen::MappedSparseMatrix
Sparse matrix.
Definition: MappedSparseMatrix.h:32
array_proxy
PyArray_Proxy * array_proxy(void *ptr)
Definition: numpy.h:387
remove_reference_t
typename std::remove_reference< T >::type remove_reference_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:660
S
DiscreteKey S(1, 2)
Scalar
SCALAR Scalar
Definition: bench_gemm.cpp:46
Eigen::Index
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
The Index type as used for the API.
Definition: Meta.h:74
test_eigen.ref
ref
Definition: test_eigen.py:9


gtsam
Author(s):
autogenerated on Fri Nov 1 2024 03:33:35