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


gtsam
Author(s):
autogenerated on Wed Mar 19 2025 03:02:22