numpy.h
Go to the documentation of this file.
1 /*
2  pybind11/numpy.h: Basic NumPy support, vectorize() wrapper
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.h"
13 #include "detail/common.h"
14 #include "complex.h"
15 #include "gil_safe_call_once.h"
16 #include "pytypes.h"
17 
18 #include <algorithm>
19 #include <array>
20 #include <cstdint>
21 #include <cstdlib>
22 #include <cstring>
23 #include <functional>
24 #include <numeric>
25 #include <sstream>
26 #include <string>
27 #include <type_traits>
28 #include <typeindex>
29 #include <utility>
30 #include <vector>
31 
32 #if defined(PYBIND11_NUMPY_1_ONLY) && !defined(PYBIND11_INTERNAL_NUMPY_1_ONLY_DETECTED)
33 # error PYBIND11_NUMPY_1_ONLY must be defined before any pybind11 header is included.
34 #endif
35 
36 /* This will be true on all flat address space platforms and allows us to reduce the
37  whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size
38  and dimension types (e.g. shape, strides, indexing), instead of inflicting this
39  upon the library user.
40  Note that NumPy 2 now uses ssize_t for `npy_intp` to simplify this. */
41 static_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
42 static_assert(std::is_signed<Py_intptr_t>::value, "Py_intptr_t must be signed");
43 // We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares)
44 
46 
48 
49 class dtype; // Forward declaration
50 class array; // Forward declaration
51 
53 
54 template <>
56  static constexpr auto name = const_name("numpy.dtype");
57 };
58 
59 template <>
61  static constexpr auto name = const_name("numpy.ndarray");
62 };
63 
64 template <typename type, typename SFINAE = void>
66 
67 /* NumPy 1 proxy (always includes legacy fields) */
69  PyObject_HEAD
70  PyObject *typeobj;
71  char kind;
72  char type;
73  char byteorder;
74  char flags;
75  int type_num;
76  int elsize;
77  int alignment;
78  char *subarray;
79  PyObject *fields;
80  PyObject *names;
81 };
82 
83 #ifndef PYBIND11_NUMPY_1_ONLY
85  PyObject_HEAD
86  PyObject *typeobj;
87  char kind;
88  char type;
89  char byteorder;
91  int type_num;
92  /* Additional fields are NumPy version specific. */
93 };
94 #else
95 /* NumPy 1.x only, we can expose all fields */
97 #endif
98 
99 /* NumPy 2 proxy, including legacy fields */
101  PyObject_HEAD
102  PyObject *typeobj;
103  char kind;
104  char type;
105  char byteorder;
107  int type_num;
111  PyObject *metadata;
112  Py_hash_t hash;
113  void *reserved_null[2];
114  /* The following fields only exist if 0 <= type_num < 2056 */
115  char *subarray;
116  PyObject *fields;
117  PyObject *names;
118 };
119 
121  PyObject_HEAD
122  char *data;
123  int nd;
126  PyObject *base;
127  PyObject *descr;
128  int flags;
129 };
130 
132  PyObject_VAR_HEAD char *obval;
134  int flags;
135  PyObject *base;
136 };
137 
139  PyObject *dtype_ptr;
140  std::string format_str;
141 };
142 
144  std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;
145 
146  numpy_type_info *get_type_info(const std::type_info &tinfo, bool throw_if_missing = true) {
147  auto it = registered_dtypes.find(std::type_index(tinfo));
148  if (it != registered_dtypes.end()) {
149  return &(it->second);
150  }
151  if (throw_if_missing) {
152  pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name());
153  }
154  return nullptr;
155  }
156 
157  template <typename T>
158  numpy_type_info *get_type_info(bool throw_if_missing = true) {
159  return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);
160  }
161 };
162 
164  ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals");
165 }
166 
168  static numpy_internals *ptr = nullptr;
169  if (!ptr) {
171  }
172  return *ptr;
173 }
174 
176  module_ numpy = module_::import("numpy");
177  str version_string = numpy.attr("__version__");
178 
179  module_ numpy_lib = module_::import("numpy.lib");
180  object numpy_version = numpy_lib.attr("NumpyVersion")(version_string);
181  int major_version = numpy_version.attr("major").cast<int>();
182 
183 #ifdef PYBIND11_NUMPY_1_ONLY
184  if (major_version >= 2) {
185  throw std::runtime_error(
186  "This extension was built with PYBIND11_NUMPY_1_ONLY defined, "
187  "but NumPy 2 is used in this process. For NumPy2 compatibility, "
188  "this extension needs to be rebuilt without the PYBIND11_NUMPY_1_ONLY define.");
189  }
190 #endif
191  /* `numpy.core` was renamed to `numpy._core` in NumPy 2.0 as it officially
192  became a private module. */
193  std::string numpy_core_path = major_version >= 2 ? "numpy._core" : "numpy.core";
194  return module_::import((numpy_core_path + "." + submodule_name).c_str());
195 }
196 
197 template <typename T>
198 struct same_size {
199  template <typename U>
200  using as = bool_constant<sizeof(T) == sizeof(U)>;
201 };
202 
203 template <typename Concrete>
204 constexpr int platform_lookup() {
205  return -1;
206 }
207 
208 // Lookup a type according to its size, and return a value corresponding to the NumPy typenum.
209 template <typename Concrete, typename T, typename... Ts, typename... Ints>
210 constexpr int platform_lookup(int I, Ints... Is) {
211  return sizeof(Concrete) == sizeof(T) ? I : platform_lookup<Concrete, Ts...>(Is...);
212 }
213 
214 struct npy_api {
215  enum constants {
244  // Platform-dependent normalization
249  // `npy_common.h` defines the integer aliases. In order, it checks:
250  // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR
251  // and assigns the alias to the first matching size, so we should check in this order.
253  = platform_lookup<std::int32_t, long, int, short>(NPY_LONG_, NPY_INT_, NPY_SHORT_),
254  NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(
257  = platform_lookup<std::int64_t, long, long long, int>(NPY_LONG_, NPY_LONGLONG_, NPY_INT_),
259  = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(
261  };
262 
264 
265  struct PyArray_Dims {
266  Py_intptr_t *ptr;
267  int len;
268  };
269 
270  static npy_api &get() {
272  return storage.call_once_and_store_result(lookup).get_stored();
273  }
274 
275  bool PyArray_Check_(PyObject *obj) const {
276  return PyObject_TypeCheck(obj, PyArray_Type_) != 0;
277  }
278  bool PyArrayDescr_Check_(PyObject *obj) const {
279  return PyObject_TypeCheck(obj, PyArrayDescr_Type_) != 0;
280  }
281 
283  PyObject *(*PyArray_DescrFromType_)(int);
284  PyObject *(*PyArray_NewFromDescr_)(PyTypeObject *,
285  PyObject *,
286  int,
287  Py_intptr_t const *,
288  Py_intptr_t const *,
289  void *,
290  int,
291  PyObject *);
292  // Unused. Not removed because that affects ABI of the class.
293  PyObject *(*PyArray_DescrNewFromType_)(int);
294  int (*PyArray_CopyInto_)(PyObject *, PyObject *);
295  PyObject *(*PyArray_NewCopy_)(PyObject *, int);
296  PyTypeObject *PyArray_Type_;
297  PyTypeObject *PyVoidArrType_Type_;
298  PyTypeObject *PyArrayDescr_Type_;
299  PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
300  PyObject *(*PyArray_FromAny_)(PyObject *, PyObject *, int, int, int, PyObject *);
301  int (*PyArray_DescrConverter_)(PyObject *, PyObject **);
302  bool (*PyArray_EquivTypes_)(PyObject *, PyObject *);
303 #ifdef PYBIND11_NUMPY_1_ONLY
304  int (*PyArray_GetArrayParamsFromObject_)(PyObject *,
305  PyObject *,
306  unsigned char,
307  PyObject **,
308  int *,
309  Py_intptr_t *,
310  PyObject **,
311  PyObject *);
312 #endif
313  PyObject *(*PyArray_Squeeze_)(PyObject *);
314  // Unused. Not removed because that affects ABI of the class.
315  int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);
316  PyObject *(*PyArray_Resize_)(PyObject *, PyArray_Dims *, int, int);
317  PyObject *(*PyArray_Newshape_)(PyObject *, PyArray_Dims *, int);
318  PyObject *(*PyArray_View_)(PyObject *, PyObject *, PyObject *);
319 
320 private:
321  enum functions {
330  // CopyInto was slot 82 and 50 was effectively an alias. NumPy 2 removed 82.
340 #ifdef PYBIND11_NUMPY_1_ONLY
341  API_PyArray_GetArrayParamsFromObject = 278,
342 #endif
344  };
345 
346  static npy_api lookup() {
348  auto c = m.attr("_ARRAY_API");
349  void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), nullptr);
350  if (api_ptr == nullptr) {
351  raise_from(PyExc_SystemError, "FAILURE obtaining numpy _ARRAY_API pointer.");
352  throw error_already_set();
353  }
354  npy_api api;
355 #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
356  DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);
357  api.PyArray_RUNTIME_VERSION_ = api.PyArray_GetNDArrayCFeatureVersion_();
358  if (api.PyArray_RUNTIME_VERSION_ < 0x7) {
359  pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0");
360  }
361  DECL_NPY_API(PyArray_Type);
362  DECL_NPY_API(PyVoidArrType_Type);
363  DECL_NPY_API(PyArrayDescr_Type);
364  DECL_NPY_API(PyArray_DescrFromType);
365  DECL_NPY_API(PyArray_DescrFromScalar);
366  DECL_NPY_API(PyArray_FromAny);
367  DECL_NPY_API(PyArray_Resize);
368  DECL_NPY_API(PyArray_CopyInto);
369  DECL_NPY_API(PyArray_NewCopy);
370  DECL_NPY_API(PyArray_NewFromDescr);
371  DECL_NPY_API(PyArray_DescrNewFromType);
372  DECL_NPY_API(PyArray_Newshape);
373  DECL_NPY_API(PyArray_Squeeze);
374  DECL_NPY_API(PyArray_View);
375  DECL_NPY_API(PyArray_DescrConverter);
376  DECL_NPY_API(PyArray_EquivTypes);
377 #ifdef PYBIND11_NUMPY_1_ONLY
378  DECL_NPY_API(PyArray_GetArrayParamsFromObject);
379 #endif
380  DECL_NPY_API(PyArray_SetBaseObject);
381 
382 #undef DECL_NPY_API
383  return api;
384  }
385 };
386 
387 inline PyArray_Proxy *array_proxy(void *ptr) { return reinterpret_cast<PyArray_Proxy *>(ptr); }
388 
389 inline const PyArray_Proxy *array_proxy(const void *ptr) {
390  return reinterpret_cast<const PyArray_Proxy *>(ptr);
391 }
392 
394  return reinterpret_cast<PyArrayDescr_Proxy *>(ptr);
395 }
396 
397 inline const PyArrayDescr_Proxy *array_descriptor_proxy(const PyObject *ptr) {
398  return reinterpret_cast<const PyArrayDescr_Proxy *>(ptr);
399 }
400 
401 inline const PyArrayDescr1_Proxy *array_descriptor1_proxy(const PyObject *ptr) {
402  return reinterpret_cast<const PyArrayDescr1_Proxy *>(ptr);
403 }
404 
405 inline const PyArrayDescr2_Proxy *array_descriptor2_proxy(const PyObject *ptr) {
406  return reinterpret_cast<const PyArrayDescr2_Proxy *>(ptr);
407 }
408 
409 inline bool check_flags(const void *ptr, int flag) {
410  return (flag == (array_proxy(ptr)->flags & flag));
411 }
412 
413 template <typename T>
414 struct is_std_array : std::false_type {};
415 template <typename T, size_t N>
416 struct is_std_array<std::array<T, N>> : std::true_type {};
417 template <typename T>
418 struct is_complex : std::false_type {};
419 template <typename T>
420 struct is_complex<std::complex<T>> : std::true_type {};
421 
422 template <typename T>
424  using type = T;
425  static constexpr bool is_array = false;
426  static constexpr bool is_empty = false;
427  static constexpr auto extents = const_name("");
428  static void append_extents(list & /* shape */) {}
429 };
430 // Computes underlying type and a comma-separated list of extents for array
431 // types (any mix of std::array and built-in arrays). An array of char is
432 // treated as scalar because it gets special handling.
433 template <typename T>
435 template <typename T, size_t N>
436 struct array_info<std::array<T, N>> {
437  using type = typename array_info<T>::type;
438  static constexpr bool is_array = true;
439  static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;
440  static constexpr size_t extent = N;
441 
442  // appends the extents to shape
443  static void append_extents(list &shape) {
444  shape.append(N);
446  }
447 
448  static constexpr auto extents = const_name<array_info<T>::is_array>(
449  ::pybind11::detail::concat(const_name<N>(), array_info<T>::extents), const_name<N>());
450 };
451 // For numpy we have special handling for arrays of characters, so we don't include
452 // the size in the array extents.
453 template <size_t N>
454 struct array_info<char[N]> : array_info_scalar<char[N]> {};
455 template <size_t N>
456 struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> {};
457 template <typename T, size_t N>
458 struct array_info<T[N]> : array_info<std::array<T, N>> {};
459 template <typename T>
461 
462 template <typename T>
463 using is_pod_struct
464  = all_of<std::is_standard_layout<T>, // since we're accessing directly in memory
465  // we need a standard layout type
466 #if defined(__GLIBCXX__) \
467  && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623 \
468  || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)
469  // libstdc++ < 5 (including versions 4.8.5, 4.9.3 and 4.9.4 which were released after
470  // 5) don't implement is_trivially_copyable, so approximate it
471  std::is_trivially_destructible<T>,
473 #else
474  std::is_trivially_copyable<T>,
475 #endif
477  std::is_reference,
478  std::is_array,
479  is_std_array,
480  std::is_arithmetic,
481  is_complex,
482  std::is_enum>>;
483 
484 // Replacement for std::is_pod (deprecated in C++20)
485 template <typename T>
486 using is_pod = all_of<std::is_standard_layout<T>, std::is_trivial<T>>;
487 
488 template <ssize_t Dim = 0, typename Strides>
489 ssize_t byte_offset_unsafe(const Strides &) {
490  return 0;
491 }
492 template <ssize_t Dim = 0, typename Strides, typename... Ix>
493 ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {
494  return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);
495 }
496 
502 template <typename T, ssize_t Dims>
504 protected:
505  static constexpr bool Dynamic = Dims < 0;
506  const unsigned char *data_;
507  // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
508  // make large performance gains on big, nested loops, but requires compile-time dimensions
510  const ssize_t dims_;
511 
512  friend class pybind11::array;
513  // Constructor for compile-time dimensions:
514  template <bool Dyn = Dynamic>
516  const ssize_t *shape,
517  const ssize_t *strides,
519  : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
520  for (size_t i = 0; i < (size_t) dims_; i++) {
521  shape_[i] = shape[i];
522  strides_[i] = strides[i];
523  }
524  }
525  // Constructor for runtime dimensions:
526  template <bool Dyn = Dynamic>
528  const ssize_t *shape,
529  const ssize_t *strides,
531  : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides},
532  dims_{dims} {}
533 
534 public:
540  template <typename... Ix>
541  const T &operator()(Ix... index) const {
542  static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
543  "Invalid number of indices for unchecked array reference");
544  return *reinterpret_cast<const T *>(data_
545  + byte_offset_unsafe(strides_, ssize_t(index)...));
546  }
551  template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
552  const T &operator[](ssize_t index) const {
553  return operator()(index);
554  }
555 
557  template <typename... Ix>
558  const T *data(Ix... ix) const {
559  return &operator()(ssize_t(ix)...);
560  }
561 
563  constexpr static ssize_t itemsize() { return sizeof(T); }
564 
566  ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; }
567 
569  ssize_t ndim() const { return dims_; }
570 
573  template <bool Dyn = Dynamic>
575  return std::accumulate(
576  shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
577  }
578  template <bool Dyn = Dynamic>
580  return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
581  }
582 
586  ssize_t nbytes() const { return size() * itemsize(); }
587 };
588 
589 template <typename T, ssize_t Dims>
591  friend class pybind11::array;
593  using ConstBase::ConstBase;
594  using ConstBase::Dynamic;
595 
596 public:
597  // Bring in const-qualified versions from base class
598  using ConstBase::operator();
599  using ConstBase::operator[];
600 
602  template <typename... Ix>
603  T &operator()(Ix... index) {
604  static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
605  "Invalid number of indices for unchecked array reference");
606  return const_cast<T &>(ConstBase::operator()(index...));
607  }
613  template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
614  T &operator[](ssize_t index) {
615  return operator()(index);
616  }
617 
619  template <typename... Ix>
620  T *mutable_data(Ix... ix) {
621  return &operator()(ssize_t(ix)...);
622  }
623 };
624 
625 template <typename T, ssize_t Dim>
627  static_assert(Dim == 0 && Dim > 0 /* always fail */,
628  "unchecked array proxy object is not castable");
629 };
630 template <typename T, ssize_t Dim>
632  : type_caster<unchecked_reference<T, Dim>> {};
633 
635 
636 class dtype : public object {
637 public:
638  PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_)
639 
640  explicit dtype(const buffer_info &info) {
641  dtype descr(_dtype_from_pep3118()(pybind11::str(info.format)));
642  // If info.itemsize == 0, use the value calculated from the format string
643  m_ptr = descr.strip_padding(info.itemsize != 0 ? info.itemsize : descr.itemsize())
644  .release()
645  .ptr();
646  }
647 
648  explicit dtype(const pybind11::str &format) : dtype(from_args(format)) {}
649 
650  explicit dtype(const std::string &format) : dtype(pybind11::str(format)) {}
651 
652  explicit dtype(const char *format) : dtype(pybind11::str(format)) {}
653 
654  dtype(list names, list formats, list offsets, ssize_t itemsize) {
655  dict args;
656  args["names"] = std::move(names);
657  args["formats"] = std::move(formats);
658  args["offsets"] = std::move(offsets);
659  args["itemsize"] = pybind11::int_(itemsize);
660  m_ptr = from_args(args).release().ptr();
661  }
662 
665  explicit dtype(int typenum)
666  : object(detail::npy_api::get().PyArray_DescrFromType_(typenum), stolen_t{}) {
667  if (m_ptr == nullptr) {
668  throw error_already_set();
669  }
670  }
671 
673  static dtype from_args(const object &args) {
674  PyObject *ptr = nullptr;
675  if ((detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) == 0) || !ptr) {
676  throw error_already_set();
677  }
678  return reinterpret_steal<dtype>(ptr);
679  }
680 
682  template <typename T>
683  static dtype of() {
685  }
686 
688 #ifdef PYBIND11_NUMPY_1_ONLY
689  ssize_t itemsize() const { return detail::array_descriptor_proxy(m_ptr)->elsize; }
690 #else
691  ssize_t itemsize() const {
692  if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {
694  }
696  }
697 #endif
698 
700 #ifdef PYBIND11_NUMPY_1_ONLY
701  bool has_fields() const { return detail::array_descriptor_proxy(m_ptr)->names != nullptr; }
702 #else
703  bool has_fields() const {
704  if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {
705  return detail::array_descriptor1_proxy(m_ptr)->names != nullptr;
706  }
707  const auto *proxy = detail::array_descriptor2_proxy(m_ptr);
708  if (proxy->type_num < 0 || proxy->type_num >= 2056) {
709  return false;
710  }
711  return proxy->names != nullptr;
712  }
713 #endif
714 
717  char kind() const { return detail::array_descriptor_proxy(m_ptr)->kind; }
718 
721  char char_() const {
722  // Note: The signature, `dtype::char_` follows the naming of NumPy's
723  // public Python API (i.e., ``dtype.char``), rather than its internal
724  // C API (``PyArray_Descr::type``).
725  return detail::array_descriptor_proxy(m_ptr)->type;
726  }
727 
729  int num() const {
730  // Note: The signature, `dtype::num` follows the naming of NumPy's public
731  // Python API (i.e., ``dtype.num``), rather than its internal
732  // C API (``PyArray_Descr::type_num``).
734  }
735 
737  char byteorder() const { return detail::array_descriptor_proxy(m_ptr)->byteorder; }
738 
740 #ifdef PYBIND11_NUMPY_1_ONLY
741  int alignment() const { return detail::array_descriptor_proxy(m_ptr)->alignment; }
742 #else
743  ssize_t alignment() const {
744  if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {
746  }
748  }
749 #endif
750 
752 #ifdef PYBIND11_NUMPY_1_ONLY
753  char flags() const { return detail::array_descriptor_proxy(m_ptr)->flags; }
754 #else
756  if (detail::npy_api::get().PyArray_RUNTIME_VERSION_ < 0x12) {
757  return (unsigned char) detail::array_descriptor1_proxy(m_ptr)->flags;
758  }
759  return detail::array_descriptor2_proxy(m_ptr)->flags;
760  }
761 #endif
762 
763 private:
764  static object &_dtype_from_pep3118() {
766  return storage
768  return detail::import_numpy_core_submodule("_internal")
769  .attr("_dtype_from_pep3118");
770  })
771  .get_stored();
772  }
773 
775  // Recursively strip all void fields with empty names that are generated for
776  // padding fields (as of NumPy v1.11).
777  if (!has_fields()) {
778  return *this;
779  }
780 
781  struct field_descr {
783  object format;
784  pybind11::int_ offset;
785  field_descr(pybind11::str &&name, object &&format, pybind11::int_ &&offset)
786  : name{std::move(name)}, format{std::move(format)}, offset{std::move(offset)} {};
787  };
788  auto field_dict = attr("fields").cast<dict>();
789  std::vector<field_descr> field_descriptors;
790  field_descriptors.reserve(field_dict.size());
791 
792  for (auto field : field_dict.attr("items")()) {
793  auto spec = field.cast<tuple>();
794  auto name = spec[0].cast<pybind11::str>();
795  auto spec_fo = spec[1].cast<tuple>();
796  auto format = spec_fo[0].cast<dtype>();
797  auto offset = spec_fo[1].cast<pybind11::int_>();
798  if ((len(name) == 0u) && format.kind() == 'V') {
799  continue;
800  }
801  field_descriptors.emplace_back(
802  std::move(name), format.strip_padding(format.itemsize()), std::move(offset));
803  }
804 
805  std::sort(field_descriptors.begin(),
806  field_descriptors.end(),
807  [](const field_descr &a, const field_descr &b) {
808  return a.offset.cast<int>() < b.offset.cast<int>();
809  });
810 
811  list names, formats, offsets;
812  for (auto &descr : field_descriptors) {
813  names.append(std::move(descr.name));
814  formats.append(std::move(descr.format));
815  offsets.append(std::move(descr.offset));
816  }
817  return dtype(std::move(names), std::move(formats), std::move(offsets), itemsize);
818  }
819 };
820 
821 class array : public buffer {
822 public:
824 
825  enum {
826  c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,
827  f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,
828  forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_
829  };
830 
831  array() : array(0, static_cast<const double *>(nullptr)) {}
832 
833  using ShapeContainer = detail::any_container<ssize_t>;
834  using StridesContainer = detail::any_container<ssize_t>;
835 
836  // Constructs an array taking shape/strides from arbitrary container types
840  const void *ptr = nullptr,
841  handle base = handle()) {
842 
843  if (strides->empty()) {
844  *strides = detail::c_strides(*shape, dt.itemsize());
845  }
846 
847  auto ndim = shape->size();
848  if (ndim != strides->size()) {
849  pybind11_fail("NumPy: shape ndim doesn't match strides ndim");
850  }
851  auto descr = dt;
852 
853  int flags = 0;
854  if (base && ptr) {
855  if (isinstance<array>(base)) {
856  /* Copy flags from base (except ownership bit) */
857  flags = reinterpret_borrow<array>(base).flags()
859  } else {
860  /* Writable by default, easy to downgrade later on if needed */
861  flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
862  }
863  }
864 
865  auto &api = detail::npy_api::get();
866  auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(
867  api.PyArray_Type_,
868  descr.release().ptr(),
869  (int) ndim,
870  // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
871  reinterpret_cast<Py_intptr_t *>(shape->data()),
872  reinterpret_cast<Py_intptr_t *>(strides->data()),
873  const_cast<void *>(ptr),
874  flags,
875  nullptr));
876  if (!tmp) {
877  throw error_already_set();
878  }
879  if (ptr) {
880  if (base) {
881  api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());
882  } else {
883  tmp = reinterpret_steal<object>(
884  api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
885  }
886  }
887  m_ptr = tmp.release().ptr();
888  }
889 
892  const void *ptr = nullptr,
893  handle base = handle())
894  : array(dt, std::move(shape), {}, ptr, base) {}
895 
896  template <typename T,
897  typename
899  array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())
900  : array(dt, {{count}}, ptr, base) {}
901 
902  template <typename T>
904  : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) {}
905 
906  template <typename T>
908  : array(std::move(shape), {}, ptr, base) {}
909 
910  template <typename T>
911  explicit array(ssize_t count, const T *ptr, handle base = handle())
912  : array({count}, {}, ptr, base) {}
913 
914  explicit array(const buffer_info &info, handle base = handle())
916 
919  return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);
920  }
921 
923  ssize_t size() const {
924  return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
925  }
926 
928  ssize_t itemsize() const { return dtype().itemsize(); }
929 
931  ssize_t nbytes() const { return size() * itemsize(); }
932 
934  ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; }
935 
937  object base() const { return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base); }
938 
940  const ssize_t *shape() const { return detail::array_proxy(m_ptr)->dimensions; }
941 
943  ssize_t shape(ssize_t dim) const {
944  if (dim >= ndim()) {
945  fail_dim_check(dim, "invalid axis");
946  }
947  return shape()[dim];
948  }
949 
951  const ssize_t *strides() const { return detail::array_proxy(m_ptr)->strides; }
952 
954  ssize_t strides(ssize_t dim) const {
955  if (dim >= ndim()) {
956  fail_dim_check(dim, "invalid axis");
957  }
958  return strides()[dim];
959  }
960 
962  int flags() const { return detail::array_proxy(m_ptr)->flags; }
963 
965  bool writeable() const {
966  return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);
967  }
968 
970  bool owndata() const {
971  return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);
972  }
973 
976  template <typename... Ix>
977  const void *data(Ix... index) const {
978  return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
979  }
980 
984  template <typename... Ix>
985  void *mutable_data(Ix... index) {
986  check_writeable();
987  return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
988  }
989 
992  template <typename... Ix>
993  ssize_t offset_at(Ix... index) const {
994  if ((ssize_t) sizeof...(index) > ndim()) {
995  fail_dim_check(sizeof...(index), "too many indices for an array");
996  }
997  return byte_offset(ssize_t(index)...);
998  }
999 
1000  ssize_t offset_at() const { return 0; }
1001 
1004  template <typename... Ix>
1005  ssize_t index_at(Ix... index) const {
1006  return offset_at(index...) / itemsize();
1007  }
1008 
1015  template <typename T, ssize_t Dims = -1>
1016  detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
1017  if (Dims >= 0 && ndim() != Dims) {
1018  throw std::domain_error("array has incorrect number of dimensions: "
1019  + std::to_string(ndim()) + "; expected "
1020  + std::to_string(Dims));
1021  }
1022  return detail::unchecked_mutable_reference<T, Dims>(
1023  mutable_data(), shape(), strides(), ndim());
1024  }
1025 
1033  template <typename T, ssize_t Dims = -1>
1034  detail::unchecked_reference<T, Dims> unchecked() const & {
1035  if (Dims >= 0 && ndim() != Dims) {
1036  throw std::domain_error("array has incorrect number of dimensions: "
1037  + std::to_string(ndim()) + "; expected "
1038  + std::to_string(Dims));
1039  }
1040  return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
1041  }
1042 
1045  auto &api = detail::npy_api::get();
1046  return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
1047  }
1048 
1052  void resize(ShapeContainer new_shape, bool refcheck = true) {
1053  detail::npy_api::PyArray_Dims d
1054  = {// Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
1055  reinterpret_cast<Py_intptr_t *>(new_shape->data()),
1056  int(new_shape->size())};
1057  // try to resize, set ordering param to -1 cause it's not used anyway
1058  auto new_array = reinterpret_steal<object>(
1059  detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1));
1060  if (!new_array) {
1061  throw error_already_set();
1062  }
1063  if (isinstance<array>(new_array)) {
1064  *this = std::move(new_array);
1065  }
1066  }
1067 
1070  detail::npy_api::PyArray_Dims d
1071  = {reinterpret_cast<Py_intptr_t *>(new_shape->data()), int(new_shape->size())};
1072  auto new_array
1073  = reinterpret_steal<array>(detail::npy_api::get().PyArray_Newshape_(m_ptr, &d, 0));
1074  if (!new_array) {
1075  throw error_already_set();
1076  }
1077  return new_array;
1078  }
1079 
1085  array view(const std::string &dtype) {
1086  auto &api = detail::npy_api::get();
1087  auto new_view = reinterpret_steal<array>(api.PyArray_View_(
1089  if (!new_view) {
1090  throw error_already_set();
1091  }
1092  return new_view;
1093  }
1094 
1097  static array ensure(handle h, int ExtraFlags = 0) {
1098  auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
1099  if (!result) {
1100  PyErr_Clear();
1101  }
1102  return result;
1103  }
1104 
1105 protected:
1106  template <typename, typename>
1107  friend struct detail::npy_format_descriptor;
1108 
1109  void fail_dim_check(ssize_t dim, const std::string &msg) const {
1110  throw index_error(msg + ": " + std::to_string(dim) + " (ndim = " + std::to_string(ndim())
1111  + ')');
1112  }
1113 
1114  template <typename... Ix>
1115  ssize_t byte_offset(Ix... index) const {
1116  check_dimensions(index...);
1117  return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
1118  }
1119 
1120  void check_writeable() const {
1121  if (!writeable()) {
1122  throw std::domain_error("array is not writeable");
1123  }
1124  }
1125 
1126  template <typename... Ix>
1127  void check_dimensions(Ix... index) const {
1128  check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
1129  }
1130 
1131  void check_dimensions_impl(ssize_t, const ssize_t *) const {}
1132 
1133  template <typename... Ix>
1134  void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const {
1135  if (i >= *shape) {
1136  throw index_error(std::string("index ") + std::to_string(i)
1137  + " is out of bounds for axis " + std::to_string(axis)
1138  + " with size " + std::to_string(*shape));
1139  }
1140  check_dimensions_impl(axis + 1, shape + 1, index...);
1141  }
1142 
1144  static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {
1145  if (ptr == nullptr) {
1146  set_error(PyExc_ValueError, "cannot create a pybind11::array from a nullptr");
1147  return nullptr;
1148  }
1149  return detail::npy_api::get().PyArray_FromAny_(
1150  ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
1151  }
1152 };
1153 
1154 template <typename T, int ExtraFlags = array::forcecast>
1155 class array_t : public array {
1156 private:
1157  struct private_ctor {};
1158  // Delegating constructor needed when both moving and accessing in the same constructor
1162  const T *ptr,
1163  handle base)
1164  : array(std::move(shape), std::move(strides), ptr, base) {}
1165 
1166 public:
1167  static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
1168 
1169  using value_type = T;
1170 
1171  array_t() : array(0, static_cast<const T *>(nullptr)) {}
1174 
1175  PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
1177  if (!m_ptr) {
1178  PyErr_Clear();
1179  }
1180  if (!is_borrowed) {
1181  Py_XDECREF(h.ptr());
1182  }
1183  }
1184 
1185  // NOLINTNEXTLINE(google-explicit-constructor)
1186  array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
1187  if (!m_ptr) {
1188  throw error_already_set();
1189  }
1190  }
1191 
1192  explicit array_t(const buffer_info &info, handle base = handle()) : array(info, base) {}
1193 
1196  const T *ptr = nullptr,
1197  handle base = handle())
1198  : array(std::move(shape), std::move(strides), ptr, base) {}
1199 
1200  explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
1201  : array_t(private_ctor{},
1202  std::move(shape),
1203  (ExtraFlags & f_style) != 0 ? detail::f_strides(*shape, itemsize())
1205  ptr,
1206  base) {}
1207 
1208  explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle())
1209  : array({count}, {}, ptr, base) {}
1210 
1211  constexpr ssize_t itemsize() const { return sizeof(T); }
1212 
1213  template <typename... Ix>
1214  ssize_t index_at(Ix... index) const {
1215  return offset_at(index...) / itemsize();
1216  }
1217 
1218  template <typename... Ix>
1219  const T *data(Ix... index) const {
1220  return static_cast<const T *>(array::data(index...));
1221  }
1222 
1223  template <typename... Ix>
1224  T *mutable_data(Ix... index) {
1225  return static_cast<T *>(array::mutable_data(index...));
1226  }
1227 
1228  // Reference to element at a given index
1229  template <typename... Ix>
1230  const T &at(Ix... index) const {
1231  if ((ssize_t) sizeof...(index) != ndim()) {
1232  fail_dim_check(sizeof...(index), "index dimension mismatch");
1233  }
1234  return *(static_cast<const T *>(array::data())
1235  + byte_offset(ssize_t(index)...) / itemsize());
1236  }
1237 
1238  // Mutable reference to element at a given index
1239  template <typename... Ix>
1240  T &mutable_at(Ix... index) {
1241  if ((ssize_t) sizeof...(index) != ndim()) {
1242  fail_dim_check(sizeof...(index), "index dimension mismatch");
1243  }
1244  return *(static_cast<T *>(array::mutable_data())
1245  + byte_offset(ssize_t(index)...) / itemsize());
1246  }
1247 
1254  template <ssize_t Dims = -1>
1255  detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
1256  return array::mutable_unchecked<T, Dims>();
1257  }
1258 
1266  template <ssize_t Dims = -1>
1267  detail::unchecked_reference<T, Dims> unchecked() const & {
1268  return array::unchecked<T, Dims>();
1269  }
1270 
1274  auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
1275  if (!result) {
1276  PyErr_Clear();
1277  }
1278  return result;
1279  }
1280 
1281  static bool check_(handle h) {
1282  const auto &api = detail::npy_api::get();
1283  return api.PyArray_Check_(h.ptr())
1284  && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr,
1285  dtype::of<T>().ptr())
1286  && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style));
1287  }
1288 
1289 protected:
1291  static PyObject *raw_array_t(PyObject *ptr) {
1292  if (ptr == nullptr) {
1293  set_error(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
1294  return nullptr;
1295  }
1296  return detail::npy_api::get().PyArray_FromAny_(ptr,
1297  dtype::of<T>().release().ptr(),
1298  0,
1299  0,
1300  detail::npy_api::NPY_ARRAY_ENSUREARRAY_
1301  | ExtraFlags,
1302  nullptr);
1303  }
1304 };
1305 
1306 template <typename T>
1307 struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1308  static std::string format() {
1310  }
1311 };
1312 
1313 template <size_t N>
1314 struct format_descriptor<char[N]> {
1315  static std::string format() { return std::to_string(N) + 's'; }
1316 };
1317 template <size_t N>
1318 struct format_descriptor<std::array<char, N>> {
1319  static std::string format() { return std::to_string(N) + 's'; }
1320 };
1321 
1322 template <typename T>
1323 struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {
1324  static std::string format() {
1325  return format_descriptor<
1327  }
1328 };
1329 
1330 template <typename T>
1331 struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
1332  static std::string format() {
1333  using namespace detail;
1334  static constexpr auto extents = const_name("(") + array_info<T>::extents + const_name(")");
1335  return extents.text + format_descriptor<remove_all_extents_t<T>>::format();
1336  }
1337 };
1338 
1340 template <typename T, int ExtraFlags>
1341 struct pyobject_caster<array_t<T, ExtraFlags>> {
1343 
1344  bool load(handle src, bool convert) {
1345  if (!convert && !type::check_(src)) {
1346  return false;
1347  }
1348  value = type::ensure(src);
1349  return static_cast<bool>(value);
1350  }
1351 
1352  static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1353  return src.inc_ref();
1354  }
1356 };
1357 
1358 template <typename T>
1359 struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1360  static bool compare(const buffer_info &b) {
1361  return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
1362  }
1363 };
1364 
1365 template <typename T, typename = void>
1367 
1368 template <typename T>
1371  const_name("bool"),
1372  const_name<std::is_signed<T>::value>("numpy.int", "numpy.uint")
1373  + const_name<sizeof(T) * 8>());
1374 };
1375 
1376 template <typename T>
1377 struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {
1382  > (const_name("numpy.float") + const_name<sizeof(T) * 8>(),
1383  const_name("numpy.longdouble"));
1384 };
1385 
1386 template <typename T>
1392  > (const_name("numpy.complex")
1393  + const_name<sizeof(typename T::value_type) * 16>(),
1394  const_name("numpy.longcomplex"));
1395 };
1396 
1397 template <typename T>
1399  T,
1400  enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>
1402 private:
1403  // NB: the order here must match the one in common.h
1404  constexpr static const int values[15] = {npy_api::NPY_BOOL_,
1419 
1420 public:
1421  static constexpr int value = values[detail::is_fmt_numeric<T>::index];
1422 
1423  static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }
1424 };
1425 
1426 template <typename T>
1428  static constexpr auto name = const_name("object");
1429 
1430  static constexpr int value = npy_api::NPY_OBJECT_;
1431 
1432  static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }
1433 };
1434 
1435 #define PYBIND11_DECL_CHAR_FMT \
1436  static constexpr auto name = const_name("S") + const_name<N>(); \
1437  static pybind11::dtype dtype() { \
1438  return pybind11::dtype(std::string("S") + std::to_string(N)); \
1439  }
1440 template <size_t N>
1441 struct npy_format_descriptor<char[N]> {
1443 };
1444 template <size_t N>
1445 struct npy_format_descriptor<std::array<char, N>> {
1447 };
1448 #undef PYBIND11_DECL_CHAR_FMT
1449 
1450 template <typename T>
1452 private:
1454 
1455 public:
1456  static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
1457 
1458  static constexpr auto name
1461  list shape;
1463  return pybind11::dtype::from_args(
1464  pybind11::make_tuple(base_descr::dtype(), std::move(shape)));
1465  }
1466 };
1467 
1468 template <typename T>
1470 private:
1472 
1473 public:
1474  static constexpr auto name = base_descr::name;
1475  static pybind11::dtype dtype() { return base_descr::dtype(); }
1476 };
1477 
1479  const char *name;
1482  std::string format;
1484 };
1485 
1487  const std::type_info &tinfo,
1488  ssize_t itemsize,
1489  bool (*direct_converter)(PyObject *, void *&)) {
1490 
1492  if (numpy_internals.get_type_info(tinfo, false)) {
1493  pybind11_fail("NumPy: dtype is already registered");
1494  }
1495 
1496  // Use ordered fields because order matters as of NumPy 1.14:
1497  // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays
1498  std::vector<field_descriptor> ordered_fields(std::move(fields));
1499  std::sort(
1500  ordered_fields.begin(),
1501  ordered_fields.end(),
1502  [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
1503 
1504  list names, formats, offsets;
1505  for (auto &field : ordered_fields) {
1506  if (!field.descr) {
1507  pybind11_fail(std::string("NumPy: unsupported field dtype: `") + field.name + "` @ "
1508  + tinfo.name());
1509  }
1510  names.append(pybind11::str(field.name));
1511  formats.append(field.descr);
1512  offsets.append(pybind11::int_(field.offset));
1513  }
1514  auto *dtype_ptr
1515  = pybind11::dtype(std::move(names), std::move(formats), std::move(offsets), itemsize)
1516  .release()
1517  .ptr();
1518 
1519  // There is an existing bug in NumPy (as of v1.11): trailing bytes are
1520  // not encoded explicitly into the format string. This will supposedly
1521  // get fixed in v1.12; for further details, see these:
1522  // - https://github.com/numpy/numpy/issues/7797
1523  // - https://github.com/numpy/numpy/pull/7798
1524  // Because of this, we won't use numpy's logic to generate buffer format
1525  // strings and will just do it ourselves.
1526  ssize_t offset = 0;
1527  std::ostringstream oss;
1528  // mark the structure as unaligned with '^', because numpy and C++ don't
1529  // always agree about alignment (particularly for complex), and we're
1530  // explicitly listing all our padding. This depends on none of the fields
1531  // overriding the endianness. Putting the ^ in front of individual fields
1532  // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
1533  oss << "^T{";
1534  for (auto &field : ordered_fields) {
1535  if (field.offset > offset) {
1536  oss << (field.offset - offset) << 'x';
1537  }
1538  oss << field.format << ':' << field.name << ':';
1539  offset = field.offset + field.size;
1540  }
1541  if (itemsize > offset) {
1542  oss << (itemsize - offset) << 'x';
1543  }
1544  oss << '}';
1545  auto format_str = oss.str();
1546 
1547  // Smoke test: verify that NumPy properly parses our buffer format string
1548  auto &api = npy_api::get();
1549  auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));
1550  if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) {
1551  pybind11_fail("NumPy: invalid buffer descriptor!");
1552  }
1553 
1554  auto tindex = std::type_index(tinfo);
1555  numpy_internals.registered_dtypes[tindex] = {dtype_ptr, std::move(format_str)};
1556  with_internals([tindex, &direct_converter](internals &internals) {
1557  internals.direct_conversions[tindex].push_back(direct_converter);
1558  });
1559 }
1560 
1561 template <typename T, typename SFINAE>
1562 struct npy_format_descriptor {
1563  static_assert(is_pod_struct<T>::value,
1564  "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1565 
1566  static constexpr auto name = make_caster<T>::name;
1567 
1568  static pybind11::dtype dtype() { return reinterpret_borrow<pybind11::dtype>(dtype_ptr()); }
1569 
1570  static std::string format() {
1571  static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
1572  return format_str;
1573  }
1574 
1576  register_structured_dtype(std::move(fields),
1577  typeid(typename std::remove_cv<T>::type),
1578  sizeof(T),
1579  &direct_converter);
1580  }
1581 
1582 private:
1583  static PyObject *dtype_ptr() {
1584  static PyObject *ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
1585  return ptr;
1586  }
1587 
1588  static bool direct_converter(PyObject *obj, void *&value) {
1589  auto &api = npy_api::get();
1590  if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) {
1591  return false;
1592  }
1593  if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
1594  if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
1595  value = ((PyVoidScalarObject_Proxy *) obj)->obval;
1596  return true;
1597  }
1598  }
1599  return false;
1600  }
1601 };
1602 
1603 #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1604 # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)
1605 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)
1606 #else
1607 
1608 # define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
1609  ::pybind11::detail::field_descriptor { \
1610  Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
1611  ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
1612  ::pybind11::detail::npy_format_descriptor< \
1613  decltype(std::declval<T>().Field)>::dtype() \
1614  }
1615 
1616 // Extract name, offset and format descriptor for a struct field
1617 # define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
1618 
1619 // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
1620 // (C) William Swanson, Paul Fultz
1621 # define PYBIND11_EVAL0(...) __VA_ARGS__
1622 # define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__)))
1623 # define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__)))
1624 # define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__)))
1625 # define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__)))
1626 # define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__)))
1627 # define PYBIND11_MAP_END(...)
1628 # define PYBIND11_MAP_OUT
1629 # define PYBIND11_MAP_COMMA ,
1630 # define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1631 # define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1632 # define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0)
1633 # define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next)
1634 # if defined(_MSC_VER) \
1635  && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
1636 # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1637  PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1638 # else
1639 # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1640  PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1641 # endif
1642 # define PYBIND11_MAP_LIST_NEXT(test, next) \
1643  PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1644 # define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1645  f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__)
1646 # define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1647  f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__)
1648 // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
1649 # define PYBIND11_MAP_LIST(f, t, ...) \
1650  PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0))
1651 
1652 # define PYBIND11_NUMPY_DTYPE(Type, ...) \
1653  ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1654  ::std::vector<::pybind11::detail::field_descriptor>{ \
1655  PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1656 
1657 # if defined(_MSC_VER) && !defined(__clang__)
1658 # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1659  PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1660 # else
1661 # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1662  PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1663 # endif
1664 # define PYBIND11_MAP2_LIST_NEXT(test, next) \
1665  PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1666 # define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1667  f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__)
1668 # define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1669  f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__)
1670 // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
1671 # define PYBIND11_MAP2_LIST(f, t, ...) \
1672  PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0))
1673 
1674 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1675  ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1676  ::std::vector<::pybind11::detail::field_descriptor>{ \
1677  PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1678 
1679 #endif // __CLION_IDE__
1680 
1682 public:
1683  using container_type = std::vector<ssize_t>;
1684  using value_type = container_type::value_type;
1685  using size_type = container_type::size_type;
1686 
1687  common_iterator() : m_strides() {}
1688 
1689  common_iterator(void *ptr, const container_type &strides, const container_type &shape)
1690  : p_ptr(reinterpret_cast<char *>(ptr)), m_strides(strides.size()) {
1691  m_strides.back() = static_cast<value_type>(strides.back());
1692  for (size_type i = m_strides.size() - 1; i != 0; --i) {
1693  size_type j = i - 1;
1694  auto s = static_cast<value_type>(shape[i]);
1695  m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
1696  }
1697  }
1698 
1699  void increment(size_type dim) { p_ptr += m_strides[dim]; }
1700 
1701  void *data() const { return p_ptr; }
1702 
1703 private:
1704  char *p_ptr{nullptr};
1706 };
1707 
1708 template <size_t N>
1710 public:
1711  using container_type = std::vector<ssize_t>;
1712 
1713  multi_array_iterator(const std::array<buffer_info, N> &buffers, const container_type &shape)
1714  : m_shape(shape.size()), m_index(shape.size(), 0), m_common_iterator() {
1715 
1716  // Manual copy to avoid conversion warning if using std::copy
1717  for (size_t i = 0; i < shape.size(); ++i) {
1718  m_shape[i] = shape[i];
1719  }
1720 
1721  container_type strides(shape.size());
1722  for (size_t i = 0; i < N; ++i) {
1723  init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
1724  }
1725  }
1726 
1728  for (size_t j = m_index.size(); j != 0; --j) {
1729  size_t i = j - 1;
1730  if (++m_index[i] != m_shape[i]) {
1731  increment_common_iterator(i);
1732  break;
1733  }
1734  m_index[i] = 0;
1735  }
1736  return *this;
1737  }
1738 
1739  template <size_t K, class T = void>
1740  T *data() const {
1741  return reinterpret_cast<T *>(m_common_iterator[K].data());
1742  }
1743 
1744 private:
1746 
1748  const container_type &shape,
1751  auto buffer_shape_iter = buffer.shape.rbegin();
1752  auto buffer_strides_iter = buffer.strides.rbegin();
1753  auto shape_iter = shape.rbegin();
1754  auto strides_iter = strides.rbegin();
1755 
1756  while (buffer_shape_iter != buffer.shape.rend()) {
1757  if (*shape_iter == *buffer_shape_iter) {
1758  *strides_iter = *buffer_strides_iter;
1759  } else {
1760  *strides_iter = 0;
1761  }
1762 
1763  ++buffer_shape_iter;
1764  ++buffer_strides_iter;
1765  ++shape_iter;
1766  ++strides_iter;
1767  }
1768 
1769  std::fill(strides_iter, strides.rend(), 0);
1770  iterator = common_iter(buffer.ptr, strides, shape);
1771  }
1772 
1773  void increment_common_iterator(size_t dim) {
1774  for (auto &iter : m_common_iterator) {
1775  iter.increment(dim);
1776  }
1777  }
1778 
1781  std::array<common_iter, N> m_common_iterator;
1782 };
1783 
1785 
1786 // Populates the shape and number of dimensions for the set of buffers. Returns a
1787 // broadcast_trivial enum value indicating whether the broadcast is "trivial"--that is, has each
1788 // buffer being either a singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous
1789 // (`f_trivial`) storage buffer; returns `non_trivial` otherwise.
1790 template <size_t N>
1792 broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
1793  ndim = std::accumulate(
1794  buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
1795  return std::max(res, buf.ndim);
1796  });
1797 
1798  shape.clear();
1799  shape.resize((size_t) ndim, 1);
1800 
1801  // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1
1802  // or the full size).
1803  for (size_t i = 0; i < N; ++i) {
1804  auto res_iter = shape.rbegin();
1805  auto end = buffers[i].shape.rend();
1806  for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end;
1807  ++shape_iter, ++res_iter) {
1808  const auto &dim_size_in = *shape_iter;
1809  auto &dim_size_out = *res_iter;
1810 
1811  // Each input dimension can either be 1 or `n`, but `n` values must match across
1812  // buffers
1813  if (dim_size_out == 1) {
1814  dim_size_out = dim_size_in;
1815  } else if (dim_size_in != 1 && dim_size_in != dim_size_out) {
1816  pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
1817  }
1818  }
1819  }
1820 
1821  bool trivial_broadcast_c = true;
1822  bool trivial_broadcast_f = true;
1823  for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
1824  if (buffers[i].size == 1) {
1825  continue;
1826  }
1827 
1828  // Require the same number of dimensions:
1829  if (buffers[i].ndim != ndim) {
1831  }
1832 
1833  // Require all dimensions be full-size:
1834  if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) {
1836  }
1837 
1838  // Check for C contiguity (but only if previous inputs were also C contiguous)
1839  if (trivial_broadcast_c) {
1840  ssize_t expect_stride = buffers[i].itemsize;
1841  auto end = buffers[i].shape.crend();
1842  for (auto shape_iter = buffers[i].shape.crbegin(),
1843  stride_iter = buffers[i].strides.crbegin();
1844  trivial_broadcast_c && shape_iter != end;
1845  ++shape_iter, ++stride_iter) {
1846  if (expect_stride == *stride_iter) {
1847  expect_stride *= *shape_iter;
1848  } else {
1849  trivial_broadcast_c = false;
1850  }
1851  }
1852  }
1853 
1854  // Check for Fortran contiguity (if previous inputs were also F contiguous)
1855  if (trivial_broadcast_f) {
1856  ssize_t expect_stride = buffers[i].itemsize;
1857  auto end = buffers[i].shape.cend();
1858  for (auto shape_iter = buffers[i].shape.cbegin(),
1859  stride_iter = buffers[i].strides.cbegin();
1860  trivial_broadcast_f && shape_iter != end;
1861  ++shape_iter, ++stride_iter) {
1862  if (expect_stride == *stride_iter) {
1863  expect_stride *= *shape_iter;
1864  } else {
1865  trivial_broadcast_f = false;
1866  }
1867  }
1868  }
1869  }
1870 
1871  return trivial_broadcast_c ? broadcast_trivial::c_trivial
1872  : trivial_broadcast_f ? broadcast_trivial::f_trivial
1874 }
1875 
1876 template <typename T>
1878  static_assert(!std::is_rvalue_reference<T>::value,
1879  "Functions with rvalue reference arguments cannot be vectorized");
1880  // The wrapped function gets called with this type:
1882  // Is this a vectorized argument?
1883  static constexpr bool vectorize
1886  std::is_pointer,
1887  std::is_array,
1888  is_std_array,
1889  std::is_enum>::value
1892  // Accept this type: an array for vectorized types, otherwise the type as-is:
1894 };
1895 
1896 // py::vectorize when a return type is present
1897 template <typename Func, typename Return, typename... Args>
1900 
1901  static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) {
1902  if (trivial == broadcast_trivial::f_trivial) {
1903  return array_t<Return, array::f_style>(shape);
1904  }
1905  return array_t<Return>(shape);
1906  }
1907 
1908  static Return *mutable_data(Type &array) { return array.mutable_data(); }
1909 
1910  static Return call(Func &f, Args &...args) { return f(args...); }
1911 
1912  static void call(Return *out, size_t i, Func &f, Args &...args) { out[i] = f(args...); }
1913 };
1914 
1915 // py::vectorize when a return type is not present
1916 template <typename Func, typename... Args>
1917 struct vectorize_returned_array<Func, void, Args...> {
1918  using Type = none;
1919 
1920  static Type create(broadcast_trivial, const std::vector<ssize_t> &) { return none(); }
1921 
1922  static void *mutable_data(Type &) { return nullptr; }
1923 
1924  static detail::void_type call(Func &f, Args &...args) {
1925  f(args...);
1926  return {};
1927  }
1928 
1929  static void call(void *, size_t, Func &f, Args &...args) { f(args...); }
1930 };
1931 
1932 template <typename Func, typename Return, typename... Args>
1934 
1935 // NVCC for some reason breaks if NVectorized is private
1936 #ifdef __CUDACC__
1937 public:
1938 #else
1939 private:
1940 #endif
1941 
1942  static constexpr size_t N = sizeof...(Args);
1943  static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
1944  static_assert(
1945  NVectorized >= 1,
1946  "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
1947 
1948 public:
1949  template <typename T,
1950  // SFINAE to prevent shadowing the copy constructor.
1951  typename = detail::enable_if_t<
1953  explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) {}
1954 
1956  return run(args...,
1960  }
1961 
1962 private:
1964 
1965  // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling
1966  // with "/permissive-" flag when arg_call_types is manually inlined.
1967  using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;
1968  template <size_t Index>
1970 
1971  using returned_array = vectorize_returned_array<Func, Return, Args...>;
1972 
1973  // Runs a vectorized function given arguments tuple and three index sequences:
1974  // - Index is the full set of 0 ... (N-1) argument indices;
1975  // - VIndex is the subset of argument indices with vectorized parameters, letting us access
1976  // vectorized arguments (anything not in this sequence is passed through)
1977  // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
1978  // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
1979  // index BIndex in the array).
1980  template <size_t... Index, size_t... VIndex, size_t... BIndex>
1981  object run(typename vectorize_arg<Args>::type &...args,
1984  index_sequence<BIndex...> bi_seq) {
1985 
1986  // Pointers to values the function was called with; the vectorized ones set here will start
1987  // out as array_t<T> pointers, but they will be changed them to T pointers before we make
1988  // call the wrapped function. Non-vectorized pointers are left as-is.
1989  std::array<void *, N> params{{&args...}};
1990 
1991  // The array of `buffer_info`s of vectorized arguments:
1992  std::array<buffer_info, NVectorized> buffers{
1993  {reinterpret_cast<array *>(params[VIndex])->request()...}};
1994 
1995  /* Determine dimensions parameters of output array */
1996  ssize_t nd = 0;
1997  std::vector<ssize_t> shape(0);
1998  auto trivial = broadcast(buffers, nd, shape);
1999  auto ndim = (size_t) nd;
2000 
2001  size_t size
2002  = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
2003 
2004  // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
2005  // not wrapped in an array).
2006  if (size == 1 && ndim == 0) {
2007  PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
2008  return cast(
2009  returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...));
2010  }
2011 
2012  auto result = returned_array::create(trivial, shape);
2013 
2014  PYBIND11_WARNING_PUSH
2015 #ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
2016  PYBIND11_WARNING_DISABLE_CLANG("-Wreturn-std-move")
2017 #endif
2018 
2019  if (size == 0) {
2020  return result;
2021  }
2022 
2023  /* Call the function */
2024  auto *mutable_data = returned_array::mutable_data(result);
2025  if (trivial == broadcast_trivial::non_trivial) {
2026  apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq);
2027  } else {
2028  apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq);
2029  }
2030 
2031  return result;
2033  }
2034 
2035  template <size_t... Index, size_t... VIndex, size_t... BIndex>
2036  void apply_trivial(std::array<buffer_info, NVectorized> &buffers,
2037  std::array<void *, N> &params,
2038  Return *out,
2039  size_t size,
2043 
2044  // Initialize an array of mutable byte references and sizes with references set to the
2045  // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
2046  // (except for singletons, which get an increment of 0).
2047  std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{
2048  {std::pair<unsigned char *&, const size_t>(
2049  reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
2050  buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>))...}};
2051 
2052  for (size_t i = 0; i < size; ++i) {
2053  returned_array::call(
2054  out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...);
2055  for (auto &x : vecparams) {
2056  x.first += x.second;
2057  }
2058  }
2059  }
2060 
2061  template <size_t... Index, size_t... VIndex, size_t... BIndex>
2062  void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
2063  std::array<void *, N> &params,
2064  Return *out,
2065  size_t size,
2066  const std::vector<ssize_t> &output_shape,
2070 
2071  multi_array_iterator<NVectorized> input_iter(buffers, output_shape);
2072 
2073  for (size_t i = 0; i < size; ++i, ++input_iter) {
2074  PYBIND11_EXPAND_SIDE_EFFECTS((params[VIndex] = input_iter.template data<BIndex>()));
2075  returned_array::call(
2076  out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
2077  }
2078  }
2079 };
2080 
2081 template <typename Func, typename Return, typename... Args>
2082 vectorize_helper<Func, Return, Args...> vectorize_extractor(const Func &f, Return (*)(Args...)) {
2083  return detail::vectorize_helper<Func, Return, Args...>(f);
2084 }
2085 
2086 template <typename T, int Flags>
2087 struct handle_type_name<array_t<T, Flags>> {
2088  static constexpr auto name
2090 };
2091 
2093 
2094 // Vanilla pointer vectorizer:
2095 template <typename Return, typename... Args>
2096 detail::vectorize_helper<Return (*)(Args...), Return, Args...> vectorize(Return (*f)(Args...)) {
2097  return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
2098 }
2099 
2100 // lambda vectorizer:
2102 auto vectorize(Func &&f)
2103  -> decltype(detail::vectorize_extractor(std::forward<Func>(f),
2104  (detail::function_signature_t<Func> *) nullptr)) {
2105  return detail::vectorize_extractor(std::forward<Func>(f),
2106  (detail::function_signature_t<Func> *) nullptr);
2107 }
2108 
2109 // Vectorize a class method (non-const):
2110 template <typename Return,
2111  typename Class,
2112  typename... Args,
2113  typename Helper = detail::vectorize_helper<
2114  decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())),
2115  Return,
2116  Class *,
2117  Args...>>
2118 Helper vectorize(Return (Class::*f)(Args...)) {
2119  return Helper(std::mem_fn(f));
2120 }
2121 
2122 // Vectorize a class method (const):
2123 template <typename Return,
2124  typename Class,
2125  typename... Args,
2126  typename Helper = detail::vectorize_helper<
2127  decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())),
2128  Return,
2129  const Class *,
2130  Args...>>
2131 Helper vectorize(Return (Class::*f)(Args...) const) {
2132  return Helper(std::mem_fn(f));
2133 }
2134 
common_iterator::m_strides
container_type m_strides
Definition: numpy.h:1705
array_t::itemsize
constexpr ssize_t itemsize() const
Definition: numpy.h:1211
select_indices
typename select_indices_impl< index_sequence<>, 0, Bs... >::type select_indices
Definition: wrap/pybind11/include/pybind11/detail/common.h:707
Dims
std::vector< Eigen::Index > Dims
Definition: testGaussianConditional.cpp:46
gtsam.examples.DogLegOptimizerExample.int
int
Definition: DogLegOptimizerExample.py:111
module_::import
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Definition: pybind11.h:1278
npy_format_descriptor::dtype_ptr
static PyObject * dtype_ptr()
Definition: numpy.h:1583
create
ADT create(const Signature &signature)
Definition: testAlgebraicDecisionTree.cpp:136
npy_api::NPY_ARRAY_WRITEABLE_
@ NPY_ARRAY_WRITEABLE_
Definition: numpy.h:222
npy_api::API_PyArray_DescrFromType
@ API_PyArray_DescrFromType
Definition: numpy.h:326
dtype::byteorder
char byteorder() const
Single character for byteorder.
Definition: numpy.h:737
npy_api::NPY_DOUBLE_
@ NPY_DOUBLE_
Definition: numpy.h:235
format_descriptor
Definition: wrap/pybind11/include/pybind11/detail/common.h:1036
vectorize_helper
Definition: numpy.h:1933
dtype::alignment
ssize_t alignment() const
Alignment of the data type.
Definition: numpy.h:743
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
array_t::ensure
static array_t ensure(handle h)
Definition: numpy.h:1273
npy_api::PyArray_RUNTIME_VERSION_
unsigned int PyArray_RUNTIME_VERSION_
Definition: numpy.h:263
PYBIND11_CONSTINIT
#define PYBIND11_CONSTINIT
Definition: wrap/pybind11/include/pybind11/detail/common.h:125
vectorize_helper::f
remove_reference_t< Func > f
Definition: numpy.h:1963
array::strides
ssize_t strides(ssize_t dim) const
Stride along a given axis.
Definition: numpy.h:954
npy_format_descriptor
Definition: numpy.h:65
PyArrayDescr2_Proxy::metadata
PyObject * metadata
Definition: numpy.h:111
name
Annotation for function names.
Definition: attr.h:51
vectorize_helper::vectorize_helper
vectorize_helper(T &&f)
Definition: numpy.h:1953
PYBIND11_EXPAND_SIDE_EFFECTS
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
Definition: wrap/pybind11/include/pybind11/detail/common.h:991
array::fail_dim_check
void fail_dim_check(ssize_t dim, const std::string &msg) const
Definition: numpy.h:1109
unchecked_reference::shape_
conditional_t< Dynamic, const ssize_t *, std::array< ssize_t,(size_t) Dims > > shape_
Definition: numpy.h:509
is_std_array
Definition: numpy.h:414
internals
Definition: internals.h:162
base
Annotation indicating that a class derives from another given type.
Definition: attr.h:64
npy_api::NPY_INT16_
@ NPY_INT16_
Definition: numpy.h:247
multi_array_iterator::m_index
container_type m_index
Definition: numpy.h:1780
array::unchecked
detail::unchecked_reference< T, Dims > unchecked() const &
Definition: numpy.h:1034
broadcast_trivial::c_trivial
@ c_trivial
npy_api::NPY_CDOUBLE_
@ NPY_CDOUBLE_
Definition: numpy.h:238
npy_api::NPY_UINT32_
@ NPY_UINT32_
Definition: numpy.h:254
npy_api::NPY_INT8_
@ NPY_INT8_
Definition: numpy.h:245
npy_api::API_PyArray_Squeeze
@ API_PyArray_Squeeze
Definition: numpy.h:336
format
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
Definition: openglsupport.cpp:226
npy_api::PyArray_Check_
bool PyArray_Check_(PyObject *obj) const
Definition: numpy.h:275
array
int array[24]
Definition: Map_general_stride.cpp:1
array::view
array view(const std::string &dtype)
Definition: numpy.h:1085
Eigen::internal::strides
EIGEN_ALWAYS_INLINE DSizes< IndexType, NumDims > strides(const DSizes< IndexType, NumDims > &dimensions)
Definition: TensorBlock.h:26
index_sequence
Index sequences.
Definition: wrap/pybind11/include/pybind11/detail/common.h:685
npy_api::NPY_BOOL_
@ NPY_BOOL_
Definition: numpy.h:223
vectorize_arg
Definition: numpy.h:1877
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
array::check_dimensions
void check_dimensions(Ix... index) const
Definition: numpy.h:1127
array::array
array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base=handle())
Definition: numpy.h:903
error_already_set
Definition: pytypes.h:739
object::stolen_t
Definition: pytypes.h:438
npy_api::API_PyArray_DescrConverter
@ API_PyArray_DescrConverter
Definition: numpy.h:338
array::mutable_data
void * mutable_data(Ix... index)
Definition: numpy.h:985
numpy_type_info::format_str
std::string format_str
Definition: numpy.h:140
array::f_style
@ f_style
Definition: numpy.h:827
s
RealScalar s
Definition: level1_cplx_impl.h:126
const_name
constexpr descr< N - 1 > const_name(char const (&text)[N])
Definition: descr.h:60
d
static const double d[K][N]
Definition: igam.h:11
PyArrayDescr2_Proxy::byteorder
char byteorder
Definition: numpy.h:105
PyArrayDescr2_Proxy::hash
Py_hash_t hash
Definition: numpy.h:112
broadcast_trivial
broadcast_trivial
Definition: numpy.h:1784
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
npy_api::API_PyArray_NewFromDescr
@ API_PyArray_NewFromDescr
Definition: numpy.h:333
array::shape
ssize_t shape(ssize_t dim) const
Dimension along a given axis.
Definition: numpy.h:943
array< double >::ShapeContainer
detail::any_container< ssize_t > ShapeContainer
Definition: numpy.h:833
list
Definition: pytypes.h:2166
npy_api
Definition: numpy.h:214
PyVoidScalarObject_Proxy::base
PyObject * base
Definition: numpy.h:135
npy_api::NPY_STRING_
@ NPY_STRING_
Definition: numpy.h:241
field_descriptor::offset
ssize_t offset
Definition: numpy.h:1480
npy_api::NPY_INT_
@ NPY_INT_
Definition: numpy.h:228
array_t::mutable_data
T * mutable_data(Ix... index)
Definition: numpy.h:1224
PyArrayDescr1_Proxy::kind
char kind
Definition: numpy.h:71
vectorize_helper::run
object run(typename vectorize_arg< Args >::type &...args, index_sequence< Index... > i_seq, index_sequence< VIndex... > vi_seq, index_sequence< BIndex... > bi_seq)
Definition: numpy.h:1981
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
array::array
array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides, const void *ptr=nullptr, handle base=handle())
Definition: numpy.h:837
b
Scalar * b
Definition: benchVecAdd.cpp:17
f_strides
std::vector< ssize_t > f_strides(const std::vector< ssize_t > &shape, ssize_t itemsize)
Definition: buffer_info.h:31
constexpr_sum
constexpr size_t constexpr_sum()
Compile-time integer sum.
Definition: wrap/pybind11/include/pybind11/detail/common.h:828
PYBIND11_OBJECT_CVT
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:1407
unchecked_reference
Definition: numpy.h:503
numpy_internals
Definition: numpy.h:143
npy_api::PyArray_Type_
PyTypeObject * PyArray_Type_
Definition: numpy.h:296
array_t::array_t
array_t(handle h, stolen_t)
Definition: numpy.h:1173
array_t::data
const T * data(Ix... index) const
Definition: numpy.h:1219
array_descriptor1_proxy
const PyArrayDescr1_Proxy * array_descriptor1_proxy(const PyObject *ptr)
Definition: numpy.h:401
npy_api::API_PyArray_Newshape
@ API_PyArray_Newshape
Definition: numpy.h:335
common_iterator::value_type
container_type::value_type value_type
Definition: numpy.h:1684
PyArrayDescr2_Proxy::typeobj
PyObject_HEAD PyObject * typeobj
Definition: numpy.h:102
format_descriptor< T, detail::enable_if_t< detail::array_info< T >::is_array > >::format
static std::string format()
Definition: numpy.h:1332
x
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy x
Definition: gnuplot_common_settings.hh:12
array::ndim
ssize_t ndim() const
Number of dimensions.
Definition: numpy.h:934
handle::inc_ref
const handle & inc_ref() const &
Definition: pytypes.h:258
array::itemsize
ssize_t itemsize() const
Byte size of a single element.
Definition: numpy.h:928
npy_api::NPY_BYTE_
@ NPY_BYTE_
Definition: numpy.h:224
array_t::array_t
array_t()
Definition: numpy.h:1171
vectorize_returned_array< Func, void, Args... >::mutable_data
static void * mutable_data(Type &)
Definition: numpy.h:1922
npy_api::NPY_LONG_
@ NPY_LONG_
Definition: numpy.h:230
npy_api::PyArrayDescr_Check_
bool PyArrayDescr_Check_(PyObject *obj) const
Definition: numpy.h:278
pyobject_caster< array_t< T, ExtraFlags > >::cast
static handle cast(const handle &src, return_value_policy, handle)
Definition: numpy.h:1352
dt
const double dt
Definition: testVelocityConstraint.cpp:15
PyArrayDescr1_Proxy::byteorder
char byteorder
Definition: numpy.h:73
PYBIND11_WARNING_POP
PYBIND11_WARNING_PUSH PYBIND11_WARNING_POP
Definition: tensor.h:30
dtype::strip_padding
dtype strip_padding(ssize_t itemsize)
Definition: numpy.h:774
npy_api::API_PyArray_Resize
@ API_PyArray_Resize
Definition: numpy.h:329
array_info< std::array< T, N > >::append_extents
static void append_extents(list &shape)
Definition: numpy.h:443
vectorize_returned_array::mutable_data
static Return * mutable_data(Type &array)
Definition: numpy.h:1908
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
dtype::has_fields
bool has_fields() const
Returns true for structured data types.
Definition: numpy.h:703
PYBIND11_NOINLINE
#define PYBIND11_NOINLINE
Definition: wrap/pybind11/include/pybind11/detail/common.h:194
unchecked_reference::data_
const unsigned char * data_
Definition: numpy.h:506
broadcast_trivial::non_trivial
@ non_trivial
npy_api::PyArray_GetNDArrayCFeatureVersion_
unsigned int(* PyArray_GetNDArrayCFeatureVersion_)()
Definition: numpy.h:282
type
Definition: pytypes.h:1525
npy_api::NPY_INT64_
@ NPY_INT64_
Definition: numpy.h:256
array::array
array()
Definition: numpy.h:831
npy_api::NPY_ARRAY_F_CONTIGUOUS_
@ NPY_ARRAY_F_CONTIGUOUS_
Definition: numpy.h:217
T
Eigen::Triplet< double > T
Definition: Tutorial_sparse_example.cpp:6
handle::m_ptr
PyObject * m_ptr
Definition: pytypes.h:306
npy_api::PyArray_DescrConverter_
int(* PyArray_DescrConverter_)(PyObject *, PyObject **)
Definition: numpy.h:301
different_sigmas::values
HybridValues values
Definition: testHybridBayesNet.cpp:245
compare_buffer_info< T, detail::enable_if_t< detail::is_pod_struct< T >::value > >::compare
static bool compare(const buffer_info &b)
Definition: numpy.h:1360
PyArrayDescr1_Proxy::flags
char flags
Definition: numpy.h:74
dtype::dtype
dtype(const pybind11::str &format)
Definition: numpy.h:648
broadcast
broadcast_trivial broadcast(const std::array< buffer_info, N > &buffers, ssize_t &ndim, std::vector< ssize_t > &shape)
Definition: numpy.h:1792
detail
Definition: testSerializationNonlinear.cpp:70
PyArray_Proxy::nd
int nd
Definition: numpy.h:123
npy_format_descriptor::direct_converter
static bool direct_converter(PyObject *obj, void *&value)
Definition: numpy.h:1588
buffer
Definition: pytypes.h:2270
array_info_scalar
Definition: numpy.h:423
npy_api::NPY_ULONGLONG_
@ NPY_ULONGLONG_
Definition: numpy.h:233
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
PyVoidScalarObject_Proxy::flags
int flags
Definition: numpy.h:134
npy_api::NPY_ARRAY_ENSUREARRAY_
@ NPY_ARRAY_ENSUREARRAY_
Definition: numpy.h:220
iterator
Definition: pytypes.h:1460
res
cout<< "Here is the matrix m:"<< endl<< m<< endl;Matrix< ptrdiff_t, 3, 1 > res
Definition: PartialRedux_count.cpp:3
npy_api::NPY_ARRAY_C_CONTIGUOUS_
@ NPY_ARRAY_C_CONTIGUOUS_
Definition: numpy.h:216
byte_offset_unsafe
ssize_t byte_offset_unsafe(const Strides &)
Definition: numpy.h:489
array_t::check_
static bool check_(handle h)
Definition: numpy.h:1281
array_t::array_t
array_t(ssize_t count, const T *ptr=nullptr, handle base=handle())
Definition: numpy.h:1208
h
const double h
Definition: testSimpleHelicopter.cpp:19
PyArray_Proxy::strides
ssize_t * strides
Definition: numpy.h:125
proxy
double proxy(double x)
Definition: testFourier.cpp:159
unchecked_mutable_reference::mutable_data
T * mutable_data(Ix... ix)
Mutable pointer access to the data at the given indices.
Definition: numpy.h:620
vanilla::params
static const SmartProjectionParams params
Definition: smartFactorScenarios.h:69
array_info_scalar::is_array
static constexpr bool is_array
Definition: numpy.h:425
same_size
Definition: numpy.h:198
result
Values result
Definition: OdometryOptimize.cpp:8
is_complex
Definition: numpy.h:418
PyArrayDescr2_Proxy
Definition: numpy.h:100
PyArrayDescr1_Proxy::elsize
int elsize
Definition: numpy.h:76
descr
Definition: descr.h:25
object::PYBIND11_DEPRECATED
PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") object(handle h
array::shape
const ssize_t * shape() const
Dimensions of the array.
Definition: numpy.h:940
unchecked_reference::strides_
conditional_t< Dynamic, const ssize_t *, std::array< ssize_t,(size_t) Dims > > strides_
Definition: numpy.h:509
PyArray_Proxy
Definition: numpy.h:120
npy_api::NPY_ARRAY_ALIGNED_
@ NPY_ARRAY_ALIGNED_
Definition: numpy.h:221
npy_api::NPY_ARRAY_FORCECAST_
@ NPY_ARRAY_FORCECAST_
Definition: numpy.h:219
conditional_t
typename std::conditional< B, T, F >::type conditional_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:656
unchecked_mutable_reference
Definition: numpy.h:590
PyArrayDescr2_Proxy::flags
std::uint64_t flags
Definition: numpy.h:108
name
static char name[]
Definition: rgamma.c:72
PyVoidScalarObject_Proxy::obval
PyObject_VAR_HEAD char * obval
Definition: numpy.h:132
npy_api::PyArray_Dims::ptr
Py_intptr_t * ptr
Definition: numpy.h:266
unchecked_reference::Dynamic
static constexpr bool Dynamic
Definition: numpy.h:505
npy_format_descriptor::format
static std::string format()
Definition: numpy.h:1570
size
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
is_pod
all_of< std::is_standard_layout< T >, std::is_trivial< T > > is_pod
Definition: numpy.h:486
process_shonan_timing_results.args
args
Definition: process_shonan_timing_results.py:163
array::offset_at
ssize_t offset_at() const
Definition: numpy.h:1000
PyArrayDescr1_Proxy::fields
PyObject * fields
Definition: numpy.h:79
field_descriptor::name
const char * name
Definition: numpy.h:1479
vectorize_returned_array
Definition: numpy.h:1898
vectorize_returned_array::call
static void call(Return *out, size_t i, Func &f, Args &...args)
Definition: numpy.h:1912
any_container
Definition: wrap/pybind11/include/pybind11/detail/common.h:1154
array_t
Definition: numpy.h:1155
npy_api::PyArrayDescr_Type_
PyTypeObject * PyArrayDescr_Type_
Definition: numpy.h:298
object
Definition: pytypes.h:364
PyArrayDescr_Proxy::type
char type
Definition: numpy.h:88
PyArrayDescr2_Proxy::_former_flags
char _former_flags
Definition: numpy.h:106
npy_api::API_PyArray_FromAny
@ API_PyArray_FromAny
Definition: numpy.h:328
npy_api::NPY_UINT8_
@ NPY_UINT8_
Definition: numpy.h:246
complex.h
multi_array_iterator::data
T * data() const
Definition: numpy.h:1740
vectorize_arg::type
conditional_t< vectorize, array_t< remove_cv_t< call_type >, array::forcecast >, T > type
Definition: numpy.h:1893
vectorize_returned_array< Func, void, Args... >::call
static void call(void *, size_t, Func &f, Args &...args)
Definition: numpy.h:1929
dict
Definition: pytypes.h:2107
dtype
Definition: numpy.h:636
array::owndata
bool owndata() const
If set, the array owns the data (will be freed when the array is deleted)
Definition: numpy.h:970
array_t::array_t
array_t(const object &o)
Definition: numpy.h:1186
raise_from
void raise_from(PyObject *type, const char *message)
Definition: pytypes.h:797
array_t::array_t
array_t(ShapeContainer shape, const T *ptr=nullptr, handle base=handle())
Definition: numpy.h:1200
npy_api::lookup
static npy_api lookup()
Definition: numpy.h:346
array::array
array(const buffer_info &info, handle base=handle())
Definition: numpy.h:914
array< double >::StridesContainer
detail::any_container< ssize_t > StridesContainer
Definition: numpy.h:834
handle
Definition: pytypes.h:226
npy_api::API_PyArray_EquivTypes
@ API_PyArray_EquivTypes
Definition: numpy.h:339
type_caster
Definition: cast.h:38
vectorize_arg::call_type
remove_reference_t< T > call_type
Definition: numpy.h:1881
dtype::num
int num() const
type number of dtype.
Definition: numpy.h:729
npy_api::NPY_LONGLONG_
@ NPY_LONGLONG_
Definition: numpy.h:232
j
std::ptrdiff_t j
Definition: tut_arithmetic_redux_minmax.cpp:2
make_tuple
tuple make_tuple()
Definition: cast.h:1383
multi_array_iterator::increment_common_iterator
void increment_common_iterator(size_t dim)
Definition: numpy.h:1773
PyArrayDescr_Proxy::type_num
int type_num
Definition: numpy.h:91
I
#define I
Definition: main.h:112
npy_api::PyArray_SetBaseObject_
int(* PyArray_SetBaseObject_)(PyObject *, PyObject *)
Definition: numpy.h:315
get_numpy_internals
numpy_internals & get_numpy_internals()
Definition: numpy.h:167
array_t::private_ctor
Definition: numpy.h:1157
field_descriptor::descr
dtype descr
Definition: numpy.h:1483
npy_format_descriptor< T, enable_if_t< satisfies_any_of< T, std::is_arithmetic, is_complex >::value > >::dtype
static pybind11::dtype dtype()
Definition: numpy.h:1423
object::release
handle release()
Definition: pytypes.h:385
vectorize_helper::arg_call_types
std::tuple< typename vectorize_arg< Args >::call_type... > arg_call_types
Definition: numpy.h:1967
array_info_scalar::extents
static constexpr auto extents
Definition: numpy.h:427
PyArray_Proxy::base
PyObject * base
Definition: numpy.h:126
PyArrayDescr2_Proxy::names
PyObject * names
Definition: numpy.h:117
multi_array_iterator
Definition: numpy.h:1709
multi_array_iterator::container_type
std::vector< ssize_t > container_type
Definition: numpy.h:1711
npy_api::functions
functions
Definition: numpy.h:321
numpy_internals::registered_dtypes
std::unordered_map< std::type_index, numpy_type_info > registered_dtypes
Definition: numpy.h:144
npy_api::API_PyVoidArrType_Type
@ API_PyVoidArrType_Type
Definition: numpy.h:325
array::nbytes
ssize_t nbytes() const
Total number of bytes.
Definition: numpy.h:931
common_iterator
Definition: numpy.h:1681
numpy_internals::get_type_info
numpy_type_info * get_type_info(bool throw_if_missing=true)
Definition: numpy.h:158
npy_api::API_PyArray_NewCopy
@ API_PyArray_NewCopy
Definition: numpy.h:332
npy_api::NPY_UINT_
@ NPY_UINT_
Definition: numpy.h:229
vectorize
detail::vectorize_helper< Return(*)(Args...), Return, Args... > vectorize(Return(*f)(Args...))
Definition: numpy.h:2096
negation
Definition: wrap/pybind11/include/pybind11/detail/common.h:713
PyArray_Proxy::data
PyObject_HEAD char * data
Definition: numpy.h:122
remove_all_extents_t
typename array_info< T >::type remove_all_extents_t
Definition: numpy.h:460
PyArrayDescr2_Proxy::fields
PyObject * fields
Definition: numpy.h:116
info
else if n * info
Definition: 3rdparty/Eigen/lapack/cholesky.cpp:18
npy_api::PyArray_EquivTypes_
bool(* PyArray_EquivTypes_)(PyObject *, PyObject *)
Definition: numpy.h:302
buffer_info::ndim
ssize_t ndim
Definition: buffer_info.h:52
array::array
array(ShapeContainer shape, const T *ptr, handle base=handle())
Definition: numpy.h:907
object::borrowed_t
Definition: pytypes.h:437
gtsam.examples.DogLegOptimizerExample.run
def run(args)
Definition: DogLegOptimizerExample.py:21
npy_api::API_PyArray_DescrFromScalar
@ API_PyArray_DescrFromScalar
Definition: numpy.h:327
common_iterator::common_iterator
common_iterator()
Definition: numpy.h:1687
unchecked_reference::unchecked_reference
unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t< Dyn, ssize_t > dims)
Definition: numpy.h:527
npy_api::NPY_UBYTE_
@ NPY_UBYTE_
Definition: numpy.h:225
PYBIND11_NAMESPACE
Definition: test_custom_type_casters.cpp:24
m
Matrix3f m
Definition: AngleAxis_mimic_euler.cpp:1
array_t::mutable_unchecked
detail::unchecked_mutable_reference< T, Dims > mutable_unchecked() &
Definition: numpy.h:1255
npy_api::NPY_USHORT_
@ NPY_USHORT_
Definition: numpy.h:227
Eigen::Triplet
A small structure to hold a non zero as a triplet (i,j,value).
Definition: SparseUtil.h:162
array_info_scalar::append_extents
static void append_extents(list &)
Definition: numpy.h:428
concat
constexpr descr< 0 > concat()
Definition: descr.h:139
unchecked_mutable_reference::operator()
T & operator()(Ix... index)
Mutable, unchecked access to data at the given indices.
Definition: numpy.h:603
array::c_style
@ c_style
Definition: numpy.h:826
common.h
PyArrayDescr2_Proxy::type
char type
Definition: numpy.h:104
pyobject_caster
Definition: cast.h:1038
vectorize_returned_array::call
static Return call(Func &f, Args &...args)
Definition: numpy.h:1910
npy_api::API_PyArrayDescr_Type
@ API_PyArrayDescr_Type
Definition: numpy.h:324
unchecked_reference::shape
ssize_t shape(ssize_t dim) const
Returns the shape (i.e. size) of dimension dim
Definition: numpy.h:566
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1026
gil_safe_call_once_and_store
Definition: gil_safe_call_once.h:46
vectorize_returned_array::create
static Type create(broadcast_trivial trivial, const std::vector< ssize_t > &shape)
Definition: numpy.h:1901
format_descriptor< std::array< char, N > >::format
static std::string format()
Definition: numpy.h:1319
gil_safe_call_once_and_store::get_stored
T & get_stored()
Definition: gil_safe_call_once.h:68
is_pod_struct
all_of< std::is_standard_layout< T >, std::is_trivially_copyable< T >, satisfies_none_of< T, std::is_reference, std::is_array, is_std_array, std::is_arithmetic, is_complex, std::is_enum > > is_pod_struct
Definition: numpy.h:482
common_iterator::common_iterator
common_iterator(void *ptr, const container_type &strides, const container_type &shape)
Definition: numpy.h:1689
size_t
std::size_t size_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:490
unchecked_reference::nbytes
ssize_t nbytes() const
Definition: numpy.h:586
npy_api::NPY_UINT16_
@ NPY_UINT16_
Definition: numpy.h:248
PyVoidScalarObject_Proxy
Definition: numpy.h:131
dtype::dtype
dtype(const std::string &format)
Definition: numpy.h:650
set_error
void set_error(const handle &type, const char *message)
Definition: pytypes.h:346
out
std::ofstream out("Result.txt")
array_t::at
const T & at(Ix... index) const
Definition: numpy.h:1230
npy_api::PyArray_Dims
Definition: numpy.h:265
multi_array_iterator::operator++
multi_array_iterator & operator++()
Definition: numpy.h:1727
check_flags
bool check_flags(const void *ptr, int flag)
Definition: numpy.h:409
npy_format_descriptor< T, enable_if_t< array_info< T >::is_array > >::dtype
static pybind11::dtype dtype()
Definition: numpy.h:1460
pytypes.h
format_descriptor< T, detail::enable_if_t< detail::is_pod_struct< T >::value > >::format
static std::string format()
Definition: numpy.h:1308
unchecked_reference::ndim
ssize_t ndim() const
Returns the number of dimensions of the array.
Definition: numpy.h:569
offset
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set set pointsize set encoding default set nopolar set noparametric set set set set surface set nocontour set clabel set mapping cartesian set nohidden3d set cntrparam order set cntrparam linear set cntrparam levels auto set cntrparam points set size set set xzeroaxis lt lw set x2zeroaxis lt lw set yzeroaxis lt lw set y2zeroaxis lt lw set tics in set ticslevel set tics set mxtics default set mytics default set mx2tics default set my2tics default set xtics border mirror norotate autofreq set ytics border mirror norotate autofreq set ztics border nomirror norotate autofreq set nox2tics set noy2tics set timestamp bottom norotate offset
Definition: gnuplot_common_settings.hh:64
dtype::char_
char char_() const
Definition: numpy.h:721
str
Definition: pytypes.h:1558
npy_api::PyArray_CopyInto_
int(* PyArray_CopyInto_)(PyObject *, PyObject *)
Definition: numpy.h:294
common_iterator::size_type
container_type::size_type size_type
Definition: numpy.h:1685
npy_format_descriptor::register_dtype
static void register_dtype(any_container< field_descriptor > fields)
Definition: numpy.h:1575
PyArrayDescr_Proxy::byteorder
char byteorder
Definition: numpy.h:89
is_same_ignoring_cvref
std::is_same< detail::remove_cvref_t< T >, U > is_same_ignoring_cvref
Example usage: is_same_ignoring_cvref<T, PyObject *>::value.
Definition: wrap/pybind11/include/pybind11/detail/common.h:677
tree::f
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Definition: testExpression.cpp:218
numpy_type_info
Definition: numpy.h:138
multi_array_iterator::m_shape
container_type m_shape
Definition: numpy.h:1779
array::size
ssize_t size() const
Total number of elements.
Definition: numpy.h:923
npy_api::API_PyArray_CopyInto
@ API_PyArray_CopyInto
Definition: numpy.h:331
PYBIND11_TYPE_CASTER
#define PYBIND11_TYPE_CASTER(type, py_name)
Definition: cast.h:87
array::mutable_unchecked
detail::unchecked_mutable_reference< T, Dims > mutable_unchecked() &
Definition: numpy.h:1016
field_descriptor::size
ssize_t size
Definition: numpy.h:1481
process_shonan_timing_results.names
dictionary names
Definition: process_shonan_timing_results.py:175
array::check_dimensions_impl
void check_dimensions_impl(ssize_t, const ssize_t *) const
Definition: numpy.h:1131
dtype::of
static dtype of()
Return dtype associated with a C++ type.
Definition: numpy.h:683
array::check_writeable
void check_writeable() const
Definition: numpy.h:1120
array::array
array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr=nullptr, handle base=handle())
Definition: numpy.h:890
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
npy_api::API_PyArray_GetNDArrayCFeatureVersion
@ API_PyArray_GetNDArrayCFeatureVersion
Definition: numpy.h:322
dtype::flags
std::uint64_t flags() const
Flags for the array descriptor.
Definition: numpy.h:755
npy_api::NPY_ULONG_
@ NPY_ULONG_
Definition: numpy.h:231
npy_api::NPY_CFLOAT_
@ NPY_CFLOAT_
Definition: numpy.h:237
unchecked_mutable_reference::operator[]
T & operator[](ssize_t index)
Definition: numpy.h:614
unchecked_reference::itemsize
constexpr static ssize_t itemsize()
Returns the item size, i.e. sizeof(T)
Definition: numpy.h:563
pybind11.h
PyArrayDescr2_Proxy::reserved_null
void * reserved_null[2]
Definition: numpy.h:113
array::array
array(const pybind11::dtype &dt, T count, const void *ptr=nullptr, handle base=handle())
Definition: numpy.h:899
numpy_internals::get_type_info
numpy_type_info * get_type_info(const std::type_info &tinfo, bool throw_if_missing=true)
Definition: numpy.h:146
npy_format_descriptor::dtype
static pybind11::dtype dtype()
Definition: numpy.h:1568
multi_array_iterator::m_common_iterator
std::array< common_iter, N > m_common_iterator
Definition: numpy.h:1781
PyArrayDescr2_Proxy::alignment
ssize_t alignment
Definition: numpy.h:110
npy_api::NPY_OBJECT_
@ NPY_OBJECT_
Definition: numpy.h:240
a
ArrayXXi a
Definition: Array_initializer_list_23_cxx11.cpp:1
PYBIND11_OBJECT_DEFAULT
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
Definition: pytypes.h:1445
platform_lookup
constexpr int platform_lookup()
Definition: numpy.h:204
array
Definition: numpy.h:821
field_descriptor
Definition: numpy.h:1478
array::squeeze
array squeeze()
Return a new view with all of the dimensions of length 1 removed.
Definition: numpy.h:1044
arr
py::array arr
Definition: test_numpy_array.cpp:77
npy_api::NPY_SHORT_
@ NPY_SHORT_
Definition: numpy.h:226
internals::direct_conversions
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:178
npy_api::NPY_FLOAT_
@ NPY_FLOAT_
Definition: numpy.h:234
PyArrayDescr1_Proxy::type_num
int type_num
Definition: numpy.h:75
make_index_sequence
typename make_index_sequence_impl< N >::type make_index_sequence
Definition: wrap/pybind11/include/pybind11/detail/common.h:693
handle_type_name
Definition: cast.h:894
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:250
array::data
const void * data(Ix... index) const
Definition: numpy.h:977
multi_array_iterator::multi_array_iterator
multi_array_iterator(const std::array< buffer_info, N > &buffers, const container_type &shape)
Definition: numpy.h:1713
Eigen::array::back
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T & back()
Definition: EmulateArray.h:39
array::raw_array
static PyObject * raw_array(PyObject *ptr, int ExtraFlags=0)
Create array from any object – always returns a new reference.
Definition: numpy.h:1144
forward
Definition: testScenarioRunner.cpp:79
PyArrayDescr2_Proxy::elsize
ssize_t elsize
Definition: numpy.h:109
module_
Wrapper for Python extension modules.
Definition: pybind11.h:1220
PyArrayDescr2_Proxy::subarray
char * subarray
Definition: numpy.h:115
with_internals
auto with_internals(const F &cb) -> decltype(cb(get_internals()))
Definition: internals.h:623
K
#define K
Definition: igam.h:8
npy_api::API_PyArray_SetBaseObject
@ API_PyArray_SetBaseObject
Definition: numpy.h:343
dtype::dtype
dtype(int typenum)
Definition: numpy.h:665
format_descriptor< T, detail::enable_if_t< std::is_enum< T >::value > >::format
static std::string format()
Definition: numpy.h:1324
PYBIND11_WARNING_DISABLE_MSVC
PYBIND11_WARNING_PUSH PYBIND11_WARNING_DISABLE_MSVC(5054) PYBIND11_WARNING_POP static_assert(EIGEN_VERSION_AT_LEAST(3
array::dtype
pybind11::dtype dtype() const
Array descriptor (dtype)
Definition: numpy.h:918
npy_api::NPY_LONGDOUBLE_
@ NPY_LONGDOUBLE_
Definition: numpy.h:236
handle::handle
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
PyArray_Proxy::dimensions
ssize_t * dimensions
Definition: numpy.h:124
array_t::unchecked
detail::unchecked_reference< T, Dims > unchecked() const &
Definition: numpy.h:1267
array_t::raw_array_t
static PyObject * raw_array_t(PyObject *ptr)
Create array from any object – always returns a new reference.
Definition: numpy.h:1291
array::byte_offset
ssize_t byte_offset(Ix... index) const
Definition: numpy.h:1115
array::reshape
array reshape(ShapeContainer new_shape)
Optional order parameter omitted, to be added as needed.
Definition: numpy.h:1069
iter
iterator iter(handle obj)
Definition: pytypes.h:2475
dtype::_dtype_from_pep3118
static object & _dtype_from_pep3118()
Definition: numpy.h:764
DECL_NPY_API
#define DECL_NPY_API(Func)
vectorize_helper::apply_broadcast
void apply_broadcast(std::array< buffer_info, NVectorized > &buffers, std::array< void *, N > &params, Return *out, size_t size, const std::vector< ssize_t > &output_shape, index_sequence< Index... >, index_sequence< VIndex... >, index_sequence< BIndex... >)
Definition: numpy.h:2062
array::ensure
static array ensure(handle h, int ExtraFlags=0)
Definition: numpy.h:1097
gil_safe_call_once.h
std
Definition: BFloat16.h:88
vectorize_helper::param_n_t
typename std::tuple_element< Index, arg_call_types >::type param_n_t
Definition: numpy.h:1969
args
Definition: pytypes.h:2210
gil_safe_call_once_and_store::call_once_and_store_result
gil_safe_call_once_and_store & call_once_and_store_result(Callable &&fn)
Definition: gil_safe_call_once.h:50
test_eigen_tensor.dtype
dtype
Definition: test_eigen_tensor.py:26
array_t::array_t
array_t(ShapeContainer shape, StridesContainer strides, const T *ptr=nullptr, handle base=handle())
Definition: numpy.h:1194
vectorize_returned_array< Func, void, Args... >::create
static Type create(broadcast_trivial, const std::vector< ssize_t > &)
Definition: numpy.h:1920
buffer_info
Information record describing a Python buffer object.
Definition: buffer_info.h:46
array_t::array_t
array_t(const buffer_info &info, handle base=handle())
Definition: numpy.h:1192
npy_api::get
static npy_api & get()
Definition: numpy.h:270
PyArrayDescr1_Proxy::type
char type
Definition: numpy.h:72
npy_api::NPY_UINT64_
@ NPY_UINT64_
Definition: numpy.h:258
npy_api::PyVoidArrType_Type_
PyTypeObject * PyVoidArrType_Type_
Definition: numpy.h:297
c_str
const char * c_str(Args &&...args)
Definition: internals.h:684
unchecked_reference::size
enable_if_t<!Dyn, ssize_t > size() const
Definition: numpy.h:574
array_t::array_t
array_t(handle h, borrowed_t)
Definition: numpy.h:1172
array::resize
void resize(ShapeContainer new_shape, bool refcheck=true)
Definition: numpy.h:1052
PyArrayDescr_Proxy::_former_flags
char _former_flags
Definition: numpy.h:90
dtype::kind
char kind() const
Definition: numpy.h:717
import_numpy_core_submodule
PYBIND11_NOINLINE module_ import_numpy_core_submodule(const char *submodule_name)
Definition: numpy.h:175
tuple
Definition: pytypes.h:2077
PyArrayDescr2_Proxy::kind
char kind
Definition: numpy.h:103
make_changelog.api
api
Definition: make_changelog.py:26
offsets
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set offsets
Definition: gnuplot_common_settings.hh:27
array_info
Definition: numpy.h:434
multi_array_iterator::init_common_iterator
void init_common_iterator(const buffer_info &buffer, const container_type &shape, common_iter &iterator, container_type &strides)
Definition: numpy.h:1747
field_descriptor::format
std::string format
Definition: numpy.h:1482
list::append
void append(T &&val)
Definition: pytypes.h:2187
array_t::mutable_at
T & mutable_at(Ix... index)
Definition: numpy.h:1240
unchecked_reference::data
const T * data(Ix... ix) const
Pointer access to the data at the given indices.
Definition: numpy.h:558
unchecked_reference::size
enable_if_t< Dyn, ssize_t > size() const
Definition: numpy.h:579
array_t::index_at
ssize_t index_at(Ix... index) const
Definition: numpy.h:1214
vectorize_returned_array< Func, void, Args... >::call
static detail::void_type call(Func &f, Args &...args)
Definition: numpy.h:1924
numpy_type_info::dtype_ptr
PyObject * dtype_ptr
Definition: numpy.h:139
U
@ U
Definition: testDecisionTree.cpp:342
pybind11
Definition: wrap/pybind11/pybind11/__init__.py:1
PyArrayDescr2_Proxy::type_num
int type_num
Definition: numpy.h:107
PyArray_Proxy::flags
int flags
Definition: numpy.h:128
format_descriptor< char[N]>::format
static std::string format()
Definition: numpy.h:1315
array::base
object base() const
Base object.
Definition: numpy.h:937
npy_api::NPY_ARRAY_OWNDATA_
@ NPY_ARRAY_OWNDATA_
Definition: numpy.h:218
vectorize_extractor
vectorize_helper< Func, Return, Args... > vectorize_extractor(const Func &f, Return(*)(Args...))
Definition: numpy.h:2082
PYBIND11_DECL_CHAR_FMT
#define PYBIND11_DECL_CHAR_FMT
Definition: numpy.h:1435
PyVoidScalarObject_Proxy::descr
PyArrayDescr_Proxy * descr
Definition: numpy.h:133
unchecked_reference::dims_
const ssize_t dims_
Definition: numpy.h:510
uint64_t
unsigned __int64 uint64_t
Definition: ms_stdint.h:95
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2446
PyArrayDescr1_Proxy
Definition: numpy.h:68
N
#define N
Definition: igam.h:9
register_structured_dtype
PYBIND11_NOINLINE void register_structured_dtype(any_container< field_descriptor > fields, const std::type_info &tinfo, ssize_t itemsize, bool(*direct_converter)(PyObject *, void *&))
Definition: numpy.h:1486
array_descriptor2_proxy
const PyArrayDescr2_Proxy * array_descriptor2_proxy(const PyObject *ptr)
Definition: numpy.h:405
unchecked_reference::operator[]
const T & operator[](ssize_t index) const
Definition: numpy.h:552
object::cast
T cast() const &
Definition: cast.h:1293
PyArrayDescr1_Proxy::alignment
int alignment
Definition: numpy.h:77
array_descriptor_proxy
PyArrayDescr_Proxy * array_descriptor_proxy(PyObject *ptr)
Definition: numpy.h:393
PyArray_Proxy::descr
PyObject * descr
Definition: numpy.h:127
compare_buffer_info
Definition: buffer_info.h:41
Eigen::placeholders::end
static const EIGEN_DEPRECATED end_t end
Definition: IndexedViewHelper.h:181
none
Definition: pytypes.h:1786
PyArrayDescr1_Proxy::typeobj
PyObject_HEAD PyObject * typeobj
Definition: numpy.h:70
load_numpy_internals
PYBIND11_NOINLINE void load_numpy_internals(numpy_internals *&ptr)
Definition: numpy.h:163
unchecked_reference::unchecked_reference
unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<!Dyn, ssize_t >)
Definition: numpy.h:515
npy_api::NPY_INT32_
@ NPY_INT32_
Definition: numpy.h:252
npy_api::PyArray_Dims::len
int len
Definition: numpy.h:267
c_strides
std::vector< ssize_t > c_strides(const std::vector< ssize_t > &shape, ssize_t itemsize)
Definition: buffer_info.h:19
array_t::array_t
array_t(private_ctor, ShapeContainer &&shape, StridesContainer &&strides, const T *ptr, handle base)
Definition: numpy.h:1159
array_info_scalar::is_empty
static constexpr bool is_empty
Definition: numpy.h:426
npy_format_descriptor_name
Definition: numpy.h:1366
common_iterator::container_type
std::vector< ssize_t > container_type
Definition: numpy.h:1683
max
#define max(a, b)
Definition: datatypes.h:20
npy_api::constants
constants
Definition: numpy.h:215
common_iterator::increment
void increment(size_type dim)
Definition: numpy.h:1699
vectorize_helper::operator()
object operator()(typename vectorize_arg< Args >::type... args)
Definition: numpy.h:1955
gtsam::convert
static BinaryMeasurement< Rot3 > convert(const BetweenFactor< Pose3 >::shared_ptr &f)
Definition: ShonanAveraging.cpp:994
gtsam.examples.ShonanAveragingCLI.str
str
Definition: ShonanAveragingCLI.py:115
npy_api::API_PyArray_DescrNewFromType
@ API_PyArray_DescrNewFromType
Definition: numpy.h:334
get
Container::iterator get(Container &c, Position position)
Definition: stdlist_overload.cpp:29
npy_api::API_PyArray_View
@ API_PyArray_View
Definition: numpy.h:337
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
npy_api::API_PyArray_Type
@ API_PyArray_Type
Definition: numpy.h:323
same_size::as
bool_constant< sizeof(T)==sizeof(U)> as
Definition: numpy.h:200
gtsam::equal
bool equal(const T &obj1, const T &obj2, double tol)
Definition: Testable.h:85
array::flags
int flags() const
Return the NumPy array flags.
Definition: numpy.h:962
PyArrayDescr_Proxy::typeobj
PyObject_HEAD PyObject * typeobj
Definition: numpy.h:86
test_callbacks.value
value
Definition: test_callbacks.py:160
array::writeable
bool writeable() const
If set, the array is writeable (otherwise the buffer is read-only)
Definition: numpy.h:965
PyArrayDescr1_Proxy::subarray
char * subarray
Definition: numpy.h:78
object::is_borrowed
bool is_borrowed
Definition: pytypes.h:370
i
int i
Definition: BiCGSTAB_step_by_step.cpp:9
dtype::itemsize
ssize_t itemsize() const
Size of the data type in bytes.
Definition: numpy.h:691
dtype::from_args
static dtype from_args(const object &args)
This is essentially the same as calling numpy.dtype(args) in Python.
Definition: numpy.h:673
Eigen::internal::cast
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
Definition: Eigen/src/Core/MathFunctions.h:460
pyobject_caster< array_t< T, ExtraFlags > >::load
bool load(handle src, bool convert)
Definition: numpy.h:1344
common_iterator::data
void * data() const
Definition: numpy.h:1701
array_proxy
PyArray_Proxy * array_proxy(void *ptr)
Definition: numpy.h:387
array::offset_at
ssize_t offset_at(Ix... index) const
Definition: numpy.h:993
array::strides
const ssize_t * strides() const
Strides of the array.
Definition: numpy.h:951
unchecked_reference::operator()
const T & operator()(Ix... index) const
Definition: numpy.h:541
broadcast_trivial::f_trivial
@ f_trivial
remove_reference_t
typename std::remove_reference< T >::type remove_reference_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:660
npy_api::NPY_CLONGDOUBLE_
@ NPY_CLONGDOUBLE_
Definition: numpy.h:239
npy_api::NPY_UNICODE_
@ NPY_UNICODE_
Definition: numpy.h:242
dtype::dtype
dtype(const char *format)
Definition: numpy.h:652
array::index_at
ssize_t index_at(Ix... index) const
Definition: numpy.h:1005
array::check_dimensions_impl
void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const
Definition: numpy.h:1134
complex
Definition: datatypes.h:12
array::array
array(ssize_t count, const T *ptr, handle base=handle())
Definition: numpy.h:911
dtype::dtype
dtype(list names, list formats, list offsets, ssize_t itemsize)
Definition: numpy.h:654
PYBIND11_WARNING_DISABLE_CLANG
#define PYBIND11_WARNING_DISABLE_CLANG(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:61
Eigen::Index
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
The Index type as used for the API.
Definition: Meta.h:74
PyArrayDescr_Proxy::kind
char kind
Definition: numpy.h:87
PyArrayDescr1_Proxy::names
PyObject * names
Definition: numpy.h:80
pybind11.msg
msg
Definition: wrap/pybind11/pybind11/__init__.py:6
npy_format_descriptor< T, enable_if_t< is_same_ignoring_cvref< T, PyObject * >::value > >::dtype
static pybind11::dtype dtype()
Definition: numpy.h:1432
npy_format_descriptor< T, enable_if_t< std::is_enum< T >::value > >::dtype
static pybind11::dtype dtype()
Definition: numpy.h:1475
vectorize_helper::apply_trivial
void apply_trivial(std::array< buffer_info, NVectorized > &buffers, std::array< void *, N > &params, Return *out, size_t size, index_sequence< Index... >, index_sequence< VIndex... >, index_sequence< BIndex... >)
Definition: numpy.h:2036
PyArrayDescr_Proxy
Definition: numpy.h:84
npy_api::NPY_VOID_
@ NPY_VOID_
Definition: numpy.h:243


gtsam
Author(s):
autogenerated on Thu Dec 19 2024 04:02:03