wrap/pybind11/include/pybind11/eigen.h
Go to the documentation of this file.
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 /* HINT: To suppress warnings originating from the Eigen headers, use -isystem.
13  See also:
14  https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir
15  https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler
16 */
17 
18 #include "numpy.h"
19 
20 // The C4127 suppression was introduced for Eigen 3.4.0. In theory we could
21 // make it version specific, or even remove it later, but considering that
22 // 1. C4127 is generally far more distracting than useful for modern template code, and
23 // 2. we definitely want to ignore any MSVC warnings originating from Eigen code,
24 // it is probably best to keep this around indefinitely.
25 #if defined(_MSC_VER)
26 # pragma warning(push)
27 # pragma warning(disable : 4127) // C4127: conditional expression is constant
28 # pragma warning(disable : 5054) // https://github.com/pybind/pybind11/pull/3741
29 // C5054: operator '&': deprecated between enumerations of different types
30 #endif
31 
32 #include <Eigen/Core>
33 #include <Eigen/SparseCore>
34 
35 #if defined(_MSC_VER)
36 # pragma warning(pop)
37 #endif
38 
39 // Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
40 // move constructors that break things. We could detect this an explicitly copy, but an extra copy
41 // of matrices seems highly undesirable.
42 static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
43  "Eigen support in pybind11 requires Eigen >= 3.2.7");
44 
46 
47 // Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
48 using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
49 template <typename MatrixType>
51 template <typename MatrixType>
52 using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
53 
55 
56 #if EIGEN_VERSION_AT_LEAST(3, 3, 0)
57 using EigenIndex = Eigen::Index;
58 template <typename Scalar, int Flags, typename StorageIndex>
60 #else
62 template <typename Scalar, int Flags, typename StorageIndex>
64 #endif
65 
66 // Matches Eigen::Map, Eigen::Ref, blocks, etc:
67 template <typename T>
69  std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
70 template <typename T>
71 using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
72 template <typename T>
75 template <typename T>
77 // Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
78 // basically covers anything that can be assigned to a dense matrix but that don't have a typical
79 // matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
80 // SelfAdjointView fall into this category.
81 template <typename T>
82 using is_eigen_other
85 
86 // Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
87 template <bool EigenRowMajor>
89  bool conformable = false;
90  EigenIndex rows = 0, cols = 0;
91  EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
92  bool negativestrides = false; // If true, do not use stride!
93 
94  // NOLINTNEXTLINE(google-explicit-constructor)
95  EigenConformable(bool fits = false) : conformable{fits} {}
96  // Matrix type:
98  : conformable{true}, rows{r}, cols{c},
99  // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
100  // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
101  stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
102  : (cstride > 0 ? cstride : 0) /* outer stride */,
103  EigenRowMajor ? (cstride > 0 ? cstride : 0)
104  : (rstride > 0 ? rstride : 0) /* inner stride */},
105  negativestrides{rstride < 0 || cstride < 0} {}
106  // Vector type:
108  : EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
109 
110  template <typename props>
111  bool stride_compatible() const {
112  // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
113  // matching strides, or a dimension size of 1 (in which case the stride value is
114  // irrelevant). Alternatively, if any dimension size is 0, the strides are not relevant
115  // (and numpy ≥ 1.23 sets the strides to 0 in that case, so we need to check explicitly).
116  if (negativestrides) {
117  return false;
118  }
119  if (rows == 0 || cols == 0) {
120  return true;
121  }
122  return (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
123  || (EigenRowMajor ? cols : rows) == 1)
124  && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
125  || (EigenRowMajor ? rows : cols) == 1);
126  }
127  // NOLINTNEXTLINE(google-explicit-constructor)
128  operator bool() const { return conformable; }
129 };
130 
131 template <typename Type>
133  using type = Type;
134 };
135 template <typename PlainObjectType, int MapOptions, typename StrideType>
136 struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {
137  using type = StrideType;
138 };
139 template <typename PlainObjectType, int Options, typename StrideType>
140 struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {
141  using type = StrideType;
142 };
143 
144 // Helper struct for extracting information from an Eigen type
145 template <typename Type_>
146 struct EigenProps {
147  using Type = Type_;
148  using Scalar = typename Type::Scalar;
150  static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
151  size = Type::SizeAtCompileTime;
152  static constexpr bool row_major = Type::IsRowMajor,
153  vector
154  = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
155  fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
156  fixed = size != Eigen::Dynamic, // Fully-fixed size
157  dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
158 
159  template <EigenIndex i, EigenIndex ifzero>
160  using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
161  static constexpr EigenIndex inner_stride
163  outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
164  vector ? size
165  : row_major ? cols
166  : rows > ::value;
167  static constexpr bool dynamic_stride
168  = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
169  static constexpr bool requires_row_major
170  = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
171  static constexpr bool requires_col_major
172  = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
173 
174  // Takes an input array and determines whether we can make it fit into the Eigen type. If
175  // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
176  // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
178  const auto dims = a.ndim();
179  if (dims < 1 || dims > 2) {
180  return false;
181  }
182 
183  if (dims == 2) { // Matrix type: require exact match (or dynamic)
184 
185  EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
186  np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
187  np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
188  if ((PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && np_rows != rows)
189  || (PYBIND11_SILENCE_MSVC_C4127(fixed_cols) && np_cols != cols)) {
190  return false;
191  }
192 
193  return {np_rows, np_cols, np_rstride, np_cstride};
194  }
195 
196  // Otherwise we're storing an n-vector. Only one of the strides will be used, but
197  // whichever is used, we want the (single) numpy stride value.
198  const EigenIndex n = a.shape(0),
199  stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
200 
201  if (vector) { // Eigen type is a compile-time vector
202  if (PYBIND11_SILENCE_MSVC_C4127(fixed) && size != n) {
203  return false; // Vector size mismatch
204  }
205  return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
206  }
207  if (fixed) {
208  // The type has a fixed size, but is not a vector: abort
209  return false;
210  }
211  if (fixed_cols) {
212  // Since this isn't a vector, cols must be != 1. We allow this only if it exactly
213  // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
214  if (cols != n) {
215  return false;
216  }
217  return {1, n, stride};
218  } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
219  if (PYBIND11_SILENCE_MSVC_C4127(fixed_rows) && rows != n) {
220  return false;
221  }
222  return {n, 1, stride};
223  }
224 
225  static constexpr bool show_writeable
227  static constexpr bool show_order = is_eigen_dense_map<Type>::value;
228  static constexpr bool show_c_contiguous = show_order && requires_row_major;
229  static constexpr bool show_f_contiguous
230  = !show_c_contiguous && show_order && requires_col_major;
231 
232  static constexpr auto descriptor
234  + const_name<fixed_rows>(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
235  + const_name<fixed_cols>(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
236  +
237  // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to
238  // be satisfied: writeable=True (for a mutable reference), and, depending on the map's
239  // stride options, possibly f_contiguous or c_contiguous. We include them in the
240  // descriptor output to provide some hint as to why a TypeError is occurring (otherwise
241  // it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
242  // an error message that you *gave* a numpy.ndarray of the right type and dimensions.
243  const_name<show_writeable>(", flags.writeable", "")
244  + const_name<show_c_contiguous>(", flags.c_contiguous", "")
245  + const_name<show_f_contiguous>(", flags.f_contiguous", "") + const_name("]");
246 };
247 
248 // Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
249 // otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
250 template <typename props>
251 handle
252 eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
253  constexpr ssize_t elem_size = sizeof(typename props::Scalar);
254  array a;
255  if (props::vector) {
256  a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
257  } else {
258  a = array({src.rows(), src.cols()},
259  {elem_size * src.rowStride(), elem_size * src.colStride()},
260  src.data(),
261  base);
262  }
263 
264  if (!writeable) {
265  array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
266  }
267 
268  return a.release();
269 }
270 
271 // Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
272 // reference the Eigen object's data with `base` as the python-registered base class (if omitted,
273 // the base will be set to None, and lifetime management is up to the caller). The numpy array is
274 // non-writeable if the given type is const.
275 template <typename props, typename Type>
276 handle eigen_ref_array(Type &src, handle parent = none()) {
277  // none here is to get past array's should-we-copy detection, which currently always
278  // copies when there is no base. Setting the base to None should be harmless.
279  return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
280 }
281 
282 // Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
283 // numpy array that references the encapsulated data with a python-side reference to the capsule to
284 // tie its destruction to that of any dependent python objects. Const-ness is determined by
285 // whether or not the Type of the pointer given is const.
288  capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
289  return eigen_ref_array<props>(*src, base);
290 }
291 
292 // Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
293 // types.
294 template <typename Type>
296  using Scalar = typename Type::Scalar;
298 
299  bool load(handle src, bool convert) {
300  // If we're in no-convert mode, only load if given an array of the correct type
301  if (!convert && !isinstance<array_t<Scalar>>(src)) {
302  return false;
303  }
304 
305  // Coerce into an array, but don't do type conversion yet; the copy below handles it.
306  auto buf = array::ensure(src);
307 
308  if (!buf) {
309  return false;
310  }
311 
312  auto dims = buf.ndim();
313  if (dims < 1 || dims > 2) {
314  return false;
315  }
316 
317  auto fits = props::conformable(buf);
318  if (!fits) {
319  return false;
320  }
321 
322  // Allocate the new type, then build a numpy reference into it
323  value = Type(fits.rows, fits.cols);
324  auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));
325  if (dims == 1) {
326  ref = ref.squeeze();
327  } else if (ref.ndim() == 1) {
328  buf = buf.squeeze();
329  }
330 
331  int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
332 
333  if (result < 0) { // Copy failed!
334  PyErr_Clear();
335  return false;
336  }
337 
338  return true;
339  }
340 
341 private:
342  // Cast implementation
343  template <typename CType>
344  static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
345  switch (policy) {
348  return eigen_encapsulate<props>(src);
350  return eigen_encapsulate<props>(new CType(std::move(*src)));
352  return eigen_array_cast<props>(*src);
355  return eigen_ref_array<props>(*src);
357  return eigen_ref_array<props>(*src, parent);
358  default:
359  throw cast_error("unhandled return_value_policy: should not happen!");
360  };
361  }
362 
363 public:
364  // Normal returned non-reference, non-const value:
365  static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
366  return cast_impl(&src, return_value_policy::move, parent);
367  }
368  // If you return a non-reference const, we mark the numpy array readonly:
369  static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
370  return cast_impl(&src, return_value_policy::move, parent);
371  }
372  // lvalue reference return; default (automatic) becomes copy
373  static handle cast(Type &src, return_value_policy policy, handle parent) {
374  if (policy == return_value_policy::automatic
376  policy = return_value_policy::copy;
377  }
378  return cast_impl(&src, policy, parent);
379  }
380  // const lvalue reference return; default (automatic) becomes copy
381  static handle cast(const Type &src, return_value_policy policy, handle parent) {
382  if (policy == return_value_policy::automatic
384  policy = return_value_policy::copy;
385  }
386  return cast(&src, policy, parent);
387  }
388  // non-const pointer return
389  static handle cast(Type *src, return_value_policy policy, handle parent) {
390  return cast_impl(src, policy, parent);
391  }
392  // const pointer return
393  static handle cast(const Type *src, return_value_policy policy, handle parent) {
394  return cast_impl(src, policy, parent);
395  }
396 
397  static constexpr auto name = props::descriptor;
398 
399  // NOLINTNEXTLINE(google-explicit-constructor)
400  operator Type *() { return &value; }
401  // NOLINTNEXTLINE(google-explicit-constructor)
402  operator Type &() { return value; }
403  // NOLINTNEXTLINE(google-explicit-constructor)
404  operator Type &&() && { return std::move(value); }
405  template <typename T>
407 
408 private:
410 };
411 
412 // Base class for casting reference/map/block/etc. objects back to python.
413 template <typename MapType>
415 private:
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);
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>
450 };
451 
452 // We can return any map-like object (but can only load Refs, specialized next):
453 template <typename 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:
466  using Scalar = typename props::Scalar;
468  using Array
469  = array_t<Scalar,
471  | ((props::row_major ? props::inner_stride : props::outer_stride) == 1
473  : (props::row_major ? props::outer_stride : props::inner_stride) == 1
475  : 0)>;
476  static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
477  // Delay construction (these have no default constructor)
478  std::unique_ptr<MapType> map;
479  std::unique_ptr<Type> ref;
480  // Our array. When possible, this is just a numpy array pointing to the source data, but
481  // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
482  // incompatible layout, or is an array of a type that needs to be converted). Using a numpy
483  // temporary (rather than an Eigen temporary) saves an extra copy when we need both type
484  // conversion and storage order conversion. (Note that we refuse to use this temporary copy
485  // when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).
487 
488 public:
489  bool load(handle src, bool convert) {
490  // First check whether what we have is already an array of the right type. If not, we
491  // can't avoid a copy (because the copy is also going to do type conversion).
492  bool need_copy = !isinstance<Array>(src);
493 
495  if (!need_copy) {
496  // We don't need a converting copy, but we also need to check whether the strides are
497  // compatible with the Ref's stride requirements
498  auto aref = reinterpret_borrow<Array>(src);
499 
500  if (aref && (!need_writeable || aref.writeable())) {
501  fits = props::conformable(aref);
502  if (!fits) {
503  return false; // Incompatible dimensions
504  }
505  if (!fits.template stride_compatible<props>()) {
506  need_copy = true;
507  } else {
508  copy_or_ref = std::move(aref);
509  }
510  } else {
511  need_copy = true;
512  }
513  }
514 
515  if (need_copy) {
516  // We need to copy: If we need a mutable reference, or we're not supposed to convert
517  // (either because we're in the no-convert overload pass, or because we're explicitly
518  // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
519  if (!convert || need_writeable) {
520  return false;
521  }
522 
523  Array copy = Array::ensure(src);
524  if (!copy) {
525  return false;
526  }
527  fits = props::conformable(copy);
528  if (!fits || !fits.template stride_compatible<props>()) {
529  return false;
530  }
531  copy_or_ref = std::move(copy);
533  }
534 
535  ref.reset();
536  map.reset(new MapType(data(copy_or_ref),
537  fits.rows,
538  fits.cols,
539  make_stride(fits.stride.outer(), fits.stride.inner())));
540  ref.reset(new Type(*map));
541 
542  return true;
543  }
544 
545  // NOLINTNEXTLINE(google-explicit-constructor)
546  operator Type *() { return ref.get(); }
547  // NOLINTNEXTLINE(google-explicit-constructor)
548  operator Type &() { return *ref; }
549  template <typename _T>
550  using cast_op_type = pybind11::detail::cast_op_type<_T>;
551 
552 private:
554  Scalar *data(Array &a) {
555  return a.mutable_data();
556  }
557 
559  const Scalar *data(Array &a) {
560  return a.data();
561  }
562 
563  // Attempt to figure out a constructor of `Stride` that will work.
564  // If both strides are fixed, use a default constructor:
565  template <typename S>
566  using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic
567  && S::OuterStrideAtCompileTime != Eigen::Dynamic
569  // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
570  // Eigen::Stride, and use it:
571  template <typename S>
572  using stride_ctor_dual
575  // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
576  // it (passing whichever stride is dynamic).
577  template <typename S>
578  using stride_ctor_outer
580  && S::OuterStrideAtCompileTime == Eigen::Dynamic
581  && S::InnerStrideAtCompileTime != Eigen::Dynamic
583  template <typename S>
584  using stride_ctor_inner
586  && S::InnerStrideAtCompileTime == Eigen::Dynamic
587  && S::OuterStrideAtCompileTime != Eigen::Dynamic
589 
592  return S();
593  }
595  static S make_stride(EigenIndex outer, EigenIndex inner) {
596  return S(outer, inner);
597  }
600  return S(outer);
601  }
604  return S(inner);
605  }
606 };
607 
608 // type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
609 // EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
610 // load() is not supported, but we can cast them into the python domain by first copying to a
611 // regular Eigen::Matrix, then casting that.
612 template <typename Type>
614 protected:
615  using Matrix
618 
619 public:
620  static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
621  handle h = eigen_encapsulate<props>(new Matrix(src));
622  return h;
623  }
624  static handle cast(const Type *src, return_value_policy policy, handle parent) {
625  return cast(*src, policy, parent);
626  }
627 
628  static constexpr auto name = props::descriptor;
629 
630  // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
631  // types but not bound arguments). We still provide them (with an explicitly delete) so that
632  // you end up here if you try anyway.
633  bool load(handle, bool) = delete;
634  operator Type() = delete;
635  template <typename>
637 };
638 
639 template <typename Type>
641  using Scalar = typename Type::Scalar;
643  using Index = typename Type::Index;
644  static constexpr bool rowMajor = Type::IsRowMajor;
645 
646  bool load(handle src, bool) {
647  if (!src) {
648  return false;
649  }
650 
651  auto obj = reinterpret_borrow<object>(src);
652  object sparse_module = module_::import("scipy.sparse");
653  object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
654 
655  if (!type::handle_of(obj).is(matrix_type)) {
656  try {
657  obj = matrix_type(obj);
658  } catch (const error_already_set &) {
659  return false;
660  }
661  }
662 
663  auto values = array_t<Scalar>((object) obj.attr("data"));
664  auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
665  auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
666  auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
667  auto nnz = obj.attr("nnz").cast<Index>();
668 
669  if (!values || !innerIndices || !outerIndices) {
670  return false;
671  }
672 
673  value = EigenMapSparseMatrix<Scalar,
674  Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),
675  StorageIndex>(shape[0].cast<Index>(),
676  shape[1].cast<Index>(),
677  std::move(nnz),
678  outerIndices.mutable_data(),
679  innerIndices.mutable_data(),
680  values.mutable_data());
681 
682  return true;
683  }
684 
685  static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
686  const_cast<Type &>(src).makeCompressed();
687 
688  object matrix_type
689  = module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
690 
691  array data(src.nonZeros(), src.valuePtr());
692  array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
693  array innerIndices(src.nonZeros(), src.innerIndexPtr());
694 
695  return matrix_type(pybind11::make_tuple(
696  std::move(data), std::move(innerIndices), std::move(outerIndices)),
697  pybind11::make_tuple(src.rows(), src.cols()))
698  .release();
699  }
700 
702  const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
703  "scipy.sparse.csc_matrix[")
705 };
706 
int array[24]
#define EIGEN_DEFAULT_DENSE_INDEX_TYPE
ssize_t ndim() const
Number of dimensions.
Definition: numpy.h:795
SCALAR Scalar
Definition: bench_gemm.cpp:46
static handle cast(const Type &src, return_value_policy policy, handle parent)
static handle handle_of()
Definition: cast.h:1645
typename eigen_extract_stride< Type >::type StrideType
T cast() const &
A makeCompressed()
const ssize_t * strides() const
Strides of the array.
Definition: numpy.h:812
tuple make_tuple()
Definition: cast.h:1209
A matrix or vector expression mapping an existing array of data.
Definition: Map.h:94
const ssize_t * shape() const
Dimensions of the array.
Definition: numpy.h:801
Definition: numpy.h:680
#define PYBIND11_SILENCE_MSVC_C4127(...)
int n
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
all_of< is_template_base_of< Eigen::EigenBase, T >, negation< any_of< is_eigen_dense_map< T >, is_eigen_dense_plain< T >, is_eigen_sparse< T > >> > is_eigen_other
bool_constant< S::InnerStrideAtCompileTime !=Eigen::Dynamic &&S::OuterStrideAtCompileTime !=Eigen::Dynamic &&std::is_default_constructible< S >::value > stride_ctor_default
decltype(is_template_base_of_impl< Base >::check((intrinsic_t< T > *) nullptr)) is_template_base_of
leaf::MyValues values
Namespace containing all symbols from the Eigen library.
Definition: jet.h:637
MatrixXf MatrixType
EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index outer() const
Definition: Stride.h:82
EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
bool isinstance(handle obj)
Definition: pytypes.h:700
DiscreteKey S(1, 2)
static handle cast(const Type *src, return_value_policy policy, handle parent)
Definition: pytypes.h:1614
handle eigen_ref_array(Type &src, handle parent=none())
EIGEN_DEVICE_FUNC EIGEN_CONSTEXPR Index inner() const
Definition: Stride.h:85
static handle cast(const MapType &src, return_value_policy policy, handle parent)
PyExc_RuntimeError [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
handle eigen_encapsulate(Type *src)
bool_constant<!any_of< stride_ctor_default< S >, stride_ctor_dual< S > >::value &&S::OuterStrideAtCompileTime==Eigen::Dynamic &&S::InnerStrideAtCompileTime !=Eigen::Dynamic &&std::is_constructible< S, EigenIndex >::value > stride_ctor_outer
static handle cast(Type *src, return_value_policy policy, handle parent)
Values result
#define EIGEN_VERSION_AT_LEAST(x, y, z)
Definition: Macros.h:22
std::integral_constant< EigenIndex, i==0 ? ifzero :i > if_zero
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
The Index type as used for the API.
Definition: Meta.h:74
static handle cast(const Type &&src, return_value_policy, handle parent)
std::integral_constant< bool, B > bool_constant
Backports of std::bool_constant and std::negation to accommodate older compilers. ...
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
int data[]
static handle cast(Type &src, return_value_policy policy, handle parent)
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
typename std::remove_reference< T >::type remove_reference_t
std::is_base_of< Eigen::MapBase< T, Eigen::WriteAccessors >, T > is_eigen_mutable_map
all_of< is_template_base_of< Eigen::DenseBase, T >, std::is_base_of< Eigen::MapBase< T, Eigen::ReadOnlyAccessors >, T > > is_eigen_dense_map
static handle cast(const Type &src, return_value_policy, handle)
Reference counting helper.
Definition: object.h:67
static handle cast(const Type &src, return_value_policy, handle)
A matrix or vector expression mapping an existing expression.
Definition: Ref.h:281
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
const T * data(Ix... index) const
Definition: numpy.h:1080
T * mutable_data(Ix... index)
Definition: numpy.h:1085
const double h
static array ensure(handle h, int ExtraFlags=0)
Definition: numpy.h:958
EIGEN_DEFAULT_DENSE_INDEX_TYPE EigenIndex
handle release()
Definition: pytypes.h:330
Map< MatrixType > MapType
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Definition: pybind11.h:1194
all_of< negation< is_eigen_dense_map< T > >, is_template_base_of< Eigen::PlainObjectBase, T > > is_eigen_dense_plain
handle eigen_array_cast(typename props::Type const &src, handle base=handle(), bool writeable=true)
remove_reference_t< decltype(*std::declval< Type >().outerIndexPtr())> StorageIndex
is_template_base_of< Eigen::SparseMatrixBase, T > is_eigen_sparse
EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
bool_constant<!any_of< stride_ctor_default< S >, stride_ctor_dual< S > >::value &&S::InnerStrideAtCompileTime==Eigen::Dynamic &&S::OuterStrideAtCompileTime !=Eigen::Dynamic &&std::is_constructible< S, EigenIndex >::value > stride_ctor_inner
Annotation for function names.
Definition: attr.h:48
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > Matrix
Annotation indicating that a class derives from another given type.
Definition: attr.h:61
const int Dynamic
Definition: Constants.h:22
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:238
Container::iterator get(Container &c, Position position)
static handle cast_impl(CType *src, return_value_policy policy, handle parent)
The matrix class, also used for vectors and row-vectors.
static EigenConformable< row_major > conformable(const array &a)
constexpr descr< N - 1 > const_name(char const (&text)[N])
Definition: descr.h:60
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
typename Type::Scalar Scalar
static PYBIND11_NOINLINE void add_patient(handle h)
#define PYBIND11_TYPE_CASTER(type, py_name)
Definition: cast.h:82
#define PYBIND11_NAMESPACE_END(name)
static BinaryMeasurement< Rot3 > convert(const BetweenFactor< Pose3 >::shared_ptr &f)
static handle cast(const Type *src, return_value_policy policy, handle parent)
Definition: pytypes.h:1370
#define PYBIND11_NAMESPACE_BEGIN(name)
PyArray_Proxy * array_proxy(void *ptr)
Definition: numpy.h:297


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:34:11