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>(),
905  std::move(shape),
906  std::move(strides),
907  reinterpret_cast<const void *>(ptr),
908  base) {}
909 
910  template <typename T>
912  : array(std::move(shape), {}, ptr, base) {}
913 
914  template <typename T>
915  explicit array(ssize_t count, const T *ptr, handle base = handle())
916  : array({count}, {}, ptr, base) {}
917 
918  explicit array(const buffer_info &info, handle base = handle())
920 
923  return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);
924  }
925 
927  ssize_t size() const {
928  return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
929  }
930 
932  ssize_t itemsize() const { return dtype().itemsize(); }
933 
935  ssize_t nbytes() const { return size() * itemsize(); }
936 
938  ssize_t ndim() const { return detail::array_proxy(m_ptr)->nd; }
939 
941  object base() const { return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base); }
942 
944  const ssize_t *shape() const { return detail::array_proxy(m_ptr)->dimensions; }
945 
947  ssize_t shape(ssize_t dim) const {
948  if (dim >= ndim()) {
949  fail_dim_check(dim, "invalid axis");
950  }
951  return shape()[dim];
952  }
953 
955  const ssize_t *strides() const { return detail::array_proxy(m_ptr)->strides; }
956 
958  ssize_t strides(ssize_t dim) const {
959  if (dim >= ndim()) {
960  fail_dim_check(dim, "invalid axis");
961  }
962  return strides()[dim];
963  }
964 
966  int flags() const { return detail::array_proxy(m_ptr)->flags; }
967 
969  bool writeable() const {
970  return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);
971  }
972 
974  bool owndata() const {
975  return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);
976  }
977 
980  template <typename... Ix>
981  const void *data(Ix... index) const {
982  return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
983  }
984 
988  template <typename... Ix>
989  void *mutable_data(Ix... index) {
990  check_writeable();
991  return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
992  }
993 
996  template <typename... Ix>
997  ssize_t offset_at(Ix... index) const {
998  if ((ssize_t) sizeof...(index) > ndim()) {
999  fail_dim_check(sizeof...(index), "too many indices for an array");
1000  }
1001  return byte_offset(ssize_t(index)...);
1002  }
1003 
1004  ssize_t offset_at() const { return 0; }
1005 
1008  template <typename... Ix>
1009  ssize_t index_at(Ix... index) const {
1010  return offset_at(index...) / itemsize();
1011  }
1012 
1019  template <typename T, ssize_t Dims = -1>
1020  detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
1021  if (Dims >= 0 && ndim() != Dims) {
1022  throw std::domain_error("array has incorrect number of dimensions: "
1023  + std::to_string(ndim()) + "; expected "
1024  + std::to_string(Dims));
1025  }
1026  return detail::unchecked_mutable_reference<T, Dims>(
1027  mutable_data(), shape(), strides(), ndim());
1028  }
1029 
1037  template <typename T, ssize_t Dims = -1>
1038  detail::unchecked_reference<T, Dims> unchecked() const & {
1039  if (Dims >= 0 && ndim() != Dims) {
1040  throw std::domain_error("array has incorrect number of dimensions: "
1041  + std::to_string(ndim()) + "; expected "
1042  + std::to_string(Dims));
1043  }
1044  return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
1045  }
1046 
1049  auto &api = detail::npy_api::get();
1050  return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
1051  }
1052 
1056  void resize(ShapeContainer new_shape, bool refcheck = true) {
1057  detail::npy_api::PyArray_Dims d
1058  = {// Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
1059  reinterpret_cast<Py_intptr_t *>(new_shape->data()),
1060  int(new_shape->size())};
1061  // try to resize, set ordering param to -1 cause it's not used anyway
1062  auto new_array = reinterpret_steal<object>(
1063  detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1));
1064  if (!new_array) {
1065  throw error_already_set();
1066  }
1067  if (isinstance<array>(new_array)) {
1068  *this = std::move(new_array);
1069  }
1070  }
1071 
1074  detail::npy_api::PyArray_Dims d
1075  = {reinterpret_cast<Py_intptr_t *>(new_shape->data()), int(new_shape->size())};
1076  auto new_array
1077  = reinterpret_steal<array>(detail::npy_api::get().PyArray_Newshape_(m_ptr, &d, 0));
1078  if (!new_array) {
1079  throw error_already_set();
1080  }
1081  return new_array;
1082  }
1083 
1089  array view(const std::string &dtype) {
1090  auto &api = detail::npy_api::get();
1091  auto new_view = reinterpret_steal<array>(api.PyArray_View_(
1093  if (!new_view) {
1094  throw error_already_set();
1095  }
1096  return new_view;
1097  }
1098 
1101  static array ensure(handle h, int ExtraFlags = 0) {
1102  auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
1103  if (!result) {
1104  PyErr_Clear();
1105  }
1106  return result;
1107  }
1108 
1109 protected:
1110  template <typename, typename>
1111  friend struct detail::npy_format_descriptor;
1112 
1113  void fail_dim_check(ssize_t dim, const std::string &msg) const {
1114  throw index_error(msg + ": " + std::to_string(dim) + " (ndim = " + std::to_string(ndim())
1115  + ')');
1116  }
1117 
1118  template <typename... Ix>
1119  ssize_t byte_offset(Ix... index) const {
1120  check_dimensions(index...);
1121  return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
1122  }
1123 
1124  void check_writeable() const {
1125  if (!writeable()) {
1126  throw std::domain_error("array is not writeable");
1127  }
1128  }
1129 
1130  template <typename... Ix>
1131  void check_dimensions(Ix... index) const {
1132  check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
1133  }
1134 
1135  void check_dimensions_impl(ssize_t, const ssize_t *) const {}
1136 
1137  template <typename... Ix>
1138  void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const {
1139  if (i >= *shape) {
1140  throw index_error(std::string("index ") + std::to_string(i)
1141  + " is out of bounds for axis " + std::to_string(axis)
1142  + " with size " + std::to_string(*shape));
1143  }
1144  check_dimensions_impl(axis + 1, shape + 1, index...);
1145  }
1146 
1148  static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {
1149  if (ptr == nullptr) {
1150  set_error(PyExc_ValueError, "cannot create a pybind11::array from a nullptr");
1151  return nullptr;
1152  }
1153  return detail::npy_api::get().PyArray_FromAny_(
1154  ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
1155  }
1156 };
1157 
1158 template <typename T, int ExtraFlags = array::forcecast>
1159 class array_t : public array {
1160 private:
1161  struct private_ctor {};
1162  // Delegating constructor needed when both moving and accessing in the same constructor
1166  const T *ptr,
1167  handle base)
1168  : array(std::move(shape), std::move(strides), ptr, base) {}
1169 
1170 public:
1171  static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
1172 
1173  using value_type = T;
1174 
1175  array_t() : array(0, static_cast<const T *>(nullptr)) {}
1178 
1179  PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
1181  if (!m_ptr) {
1182  PyErr_Clear();
1183  }
1184  if (!is_borrowed) {
1185  Py_XDECREF(h.ptr());
1186  }
1187  }
1188 
1189  // NOLINTNEXTLINE(google-explicit-constructor)
1190  array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
1191  if (!m_ptr) {
1192  throw error_already_set();
1193  }
1194  }
1195 
1196  explicit array_t(const buffer_info &info, handle base = handle()) : array(info, base) {}
1197 
1200  const T *ptr = nullptr,
1201  handle base = handle())
1202  : array(std::move(shape), std::move(strides), ptr, base) {}
1203 
1204  explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
1205  : array_t(private_ctor{},
1206  std::move(shape),
1207  (ExtraFlags & f_style) != 0 ? detail::f_strides(*shape, itemsize())
1209  ptr,
1210  base) {}
1211 
1212  explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle())
1213  : array({count}, {}, ptr, base) {}
1214 
1215  constexpr ssize_t itemsize() const { return sizeof(T); }
1216 
1217  template <typename... Ix>
1218  ssize_t index_at(Ix... index) const {
1219  return offset_at(index...) / itemsize();
1220  }
1221 
1222  template <typename... Ix>
1223  const T *data(Ix... index) const {
1224  return static_cast<const T *>(array::data(index...));
1225  }
1226 
1227  template <typename... Ix>
1228  T *mutable_data(Ix... index) {
1229  return static_cast<T *>(array::mutable_data(index...));
1230  }
1231 
1232  // Reference to element at a given index
1233  template <typename... Ix>
1234  const T &at(Ix... index) const {
1235  if ((ssize_t) sizeof...(index) != ndim()) {
1236  fail_dim_check(sizeof...(index), "index dimension mismatch");
1237  }
1238  return *(static_cast<const T *>(array::data())
1239  + byte_offset(ssize_t(index)...) / itemsize());
1240  }
1241 
1242  // Mutable reference to element at a given index
1243  template <typename... Ix>
1244  T &mutable_at(Ix... index) {
1245  if ((ssize_t) sizeof...(index) != ndim()) {
1246  fail_dim_check(sizeof...(index), "index dimension mismatch");
1247  }
1248  return *(static_cast<T *>(array::mutable_data())
1249  + byte_offset(ssize_t(index)...) / itemsize());
1250  }
1251 
1258  template <ssize_t Dims = -1>
1259  detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
1260  return array::mutable_unchecked<T, Dims>();
1261  }
1262 
1270  template <ssize_t Dims = -1>
1271  detail::unchecked_reference<T, Dims> unchecked() const & {
1272  return array::unchecked<T, Dims>();
1273  }
1274 
1278  auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
1279  if (!result) {
1280  PyErr_Clear();
1281  }
1282  return result;
1283  }
1284 
1285  static bool check_(handle h) {
1286  const auto &api = detail::npy_api::get();
1287  return api.PyArray_Check_(h.ptr())
1288  && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr,
1289  dtype::of<T>().ptr())
1290  && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style));
1291  }
1292 
1293 protected:
1295  static PyObject *raw_array_t(PyObject *ptr) {
1296  if (ptr == nullptr) {
1297  set_error(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
1298  return nullptr;
1299  }
1300  return detail::npy_api::get().PyArray_FromAny_(ptr,
1301  dtype::of<T>().release().ptr(),
1302  0,
1303  0,
1304  detail::npy_api::NPY_ARRAY_ENSUREARRAY_
1305  | ExtraFlags,
1306  nullptr);
1307  }
1308 };
1309 
1310 template <typename T>
1311 struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1312  static std::string format() {
1314  }
1315 };
1316 
1317 template <size_t N>
1318 struct format_descriptor<char[N]> {
1319  static std::string format() { return std::to_string(N) + 's'; }
1320 };
1321 template <size_t N>
1322 struct format_descriptor<std::array<char, N>> {
1323  static std::string format() { return std::to_string(N) + 's'; }
1324 };
1325 
1326 template <typename T>
1327 struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {
1328  static std::string format() {
1329  return format_descriptor<
1331  }
1332 };
1333 
1334 template <typename T>
1335 struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
1336  static std::string format() {
1337  using namespace detail;
1338  static constexpr auto extents = const_name("(") + array_info<T>::extents + const_name(")");
1339  return extents.text + format_descriptor<remove_all_extents_t<T>>::format();
1340  }
1341 };
1342 
1344 template <typename T, int ExtraFlags>
1345 struct pyobject_caster<array_t<T, ExtraFlags>> {
1347 
1348  bool load(handle src, bool convert) {
1349  if (!convert && !type::check_(src)) {
1350  return false;
1351  }
1352  value = type::ensure(src);
1353  return static_cast<bool>(value);
1354  }
1355 
1356  static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1357  return src.inc_ref();
1358  }
1360 };
1361 
1362 template <typename T>
1363 struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1364  static bool compare(const buffer_info &b) {
1365  return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
1366  }
1367 };
1368 
1369 template <typename T, typename = void>
1371 
1372 template <typename T>
1375  const_name("bool"),
1376  const_name<std::is_signed<T>::value>("numpy.int", "numpy.uint")
1377  + const_name<sizeof(T) * 8>());
1378 };
1379 
1380 template <typename T>
1381 struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {
1386  > (const_name("numpy.float") + const_name<sizeof(T) * 8>(),
1387  const_name("numpy.longdouble"));
1388 };
1389 
1390 template <typename T>
1396  > (const_name("numpy.complex")
1397  + const_name<sizeof(typename T::value_type) * 16>(),
1398  const_name("numpy.longcomplex"));
1399 };
1400 
1401 template <typename T>
1403  T,
1404  enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>
1406 private:
1407  // NB: the order here must match the one in common.h
1408  constexpr static const int values[15] = {npy_api::NPY_BOOL_,
1423 
1424 public:
1425  static constexpr int value = values[detail::is_fmt_numeric<T>::index];
1426 
1427  static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }
1428 };
1429 
1430 template <typename T>
1432  static constexpr auto name = const_name("object");
1433 
1434  static constexpr int value = npy_api::NPY_OBJECT_;
1435 
1436  static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }
1437 };
1438 
1439 #define PYBIND11_DECL_CHAR_FMT \
1440  static constexpr auto name = const_name("S") + const_name<N>(); \
1441  static pybind11::dtype dtype() { \
1442  return pybind11::dtype(std::string("S") + std::to_string(N)); \
1443  }
1444 template <size_t N>
1445 struct npy_format_descriptor<char[N]> {
1447 };
1448 template <size_t N>
1449 struct npy_format_descriptor<std::array<char, N>> {
1451 };
1452 #undef PYBIND11_DECL_CHAR_FMT
1453 
1454 template <typename T>
1456 private:
1458 
1459 public:
1460  static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
1461 
1462  static constexpr auto name
1465  list shape;
1467  return pybind11::dtype::from_args(
1468  pybind11::make_tuple(base_descr::dtype(), std::move(shape)));
1469  }
1470 };
1471 
1472 template <typename T>
1474 private:
1476 
1477 public:
1478  static constexpr auto name = base_descr::name;
1479  static pybind11::dtype dtype() { return base_descr::dtype(); }
1480 };
1481 
1483  const char *name;
1486  std::string format;
1488 };
1489 
1491  const std::type_info &tinfo,
1492  ssize_t itemsize,
1493  bool (*direct_converter)(PyObject *, void *&)) {
1494 
1496  if (numpy_internals.get_type_info(tinfo, false)) {
1497  pybind11_fail("NumPy: dtype is already registered");
1498  }
1499 
1500  // Use ordered fields because order matters as of NumPy 1.14:
1501  // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays
1502  std::vector<field_descriptor> ordered_fields(std::move(fields));
1503  std::sort(
1504  ordered_fields.begin(),
1505  ordered_fields.end(),
1506  [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
1507 
1508  list names, formats, offsets;
1509  for (auto &field : ordered_fields) {
1510  if (!field.descr) {
1511  pybind11_fail(std::string("NumPy: unsupported field dtype: `") + field.name + "` @ "
1512  + tinfo.name());
1513  }
1514  names.append(pybind11::str(field.name));
1515  formats.append(field.descr);
1516  offsets.append(pybind11::int_(field.offset));
1517  }
1518  auto *dtype_ptr
1519  = pybind11::dtype(std::move(names), std::move(formats), std::move(offsets), itemsize)
1520  .release()
1521  .ptr();
1522 
1523  // There is an existing bug in NumPy (as of v1.11): trailing bytes are
1524  // not encoded explicitly into the format string. This will supposedly
1525  // get fixed in v1.12; for further details, see these:
1526  // - https://github.com/numpy/numpy/issues/7797
1527  // - https://github.com/numpy/numpy/pull/7798
1528  // Because of this, we won't use numpy's logic to generate buffer format
1529  // strings and will just do it ourselves.
1530  ssize_t offset = 0;
1531  std::ostringstream oss;
1532  // mark the structure as unaligned with '^', because numpy and C++ don't
1533  // always agree about alignment (particularly for complex), and we're
1534  // explicitly listing all our padding. This depends on none of the fields
1535  // overriding the endianness. Putting the ^ in front of individual fields
1536  // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
1537  oss << "^T{";
1538  for (auto &field : ordered_fields) {
1539  if (field.offset > offset) {
1540  oss << (field.offset - offset) << 'x';
1541  }
1542  oss << field.format << ':' << field.name << ':';
1543  offset = field.offset + field.size;
1544  }
1545  if (itemsize > offset) {
1546  oss << (itemsize - offset) << 'x';
1547  }
1548  oss << '}';
1549  auto format_str = oss.str();
1550 
1551  // Smoke test: verify that NumPy properly parses our buffer format string
1552  auto &api = npy_api::get();
1553  auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));
1554  if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr())) {
1555  pybind11_fail("NumPy: invalid buffer descriptor!");
1556  }
1557 
1558  auto tindex = std::type_index(tinfo);
1559  numpy_internals.registered_dtypes[tindex] = {dtype_ptr, std::move(format_str)};
1560  with_internals([tindex, &direct_converter](internals &internals) {
1561  internals.direct_conversions[tindex].push_back(direct_converter);
1562  });
1563 }
1564 
1565 template <typename T, typename SFINAE>
1566 struct npy_format_descriptor {
1567  static_assert(is_pod_struct<T>::value,
1568  "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1569 
1570  static constexpr auto name = make_caster<T>::name;
1571 
1572  static pybind11::dtype dtype() { return reinterpret_borrow<pybind11::dtype>(dtype_ptr()); }
1573 
1574  static std::string format() {
1575  static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
1576  return format_str;
1577  }
1578 
1580  register_structured_dtype(std::move(fields),
1581  typeid(typename std::remove_cv<T>::type),
1582  sizeof(T),
1583  &direct_converter);
1584  }
1585 
1586 private:
1587  static PyObject *dtype_ptr() {
1588  static PyObject *ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
1589  return ptr;
1590  }
1591 
1592  static bool direct_converter(PyObject *obj, void *&value) {
1593  auto &api = npy_api::get();
1594  if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_)) {
1595  return false;
1596  }
1597  if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
1598  if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
1599  value = ((PyVoidScalarObject_Proxy *) obj)->obval;
1600  return true;
1601  }
1602  }
1603  return false;
1604  }
1605 };
1606 
1607 #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1608 # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)
1609 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)
1610 #else
1611 
1612 # define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
1613  ::pybind11::detail::field_descriptor { \
1614  Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
1615  ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
1616  ::pybind11::detail::npy_format_descriptor< \
1617  decltype(std::declval<T>().Field)>::dtype() \
1618  }
1619 
1620 // Extract name, offset and format descriptor for a struct field
1621 # define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
1622 
1623 // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
1624 // (C) William Swanson, Paul Fultz
1625 # define PYBIND11_EVAL0(...) __VA_ARGS__
1626 # define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__)))
1627 # define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__)))
1628 # define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__)))
1629 # define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__)))
1630 # define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__)))
1631 # define PYBIND11_MAP_END(...)
1632 # define PYBIND11_MAP_OUT
1633 # define PYBIND11_MAP_COMMA ,
1634 # define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1635 # define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1636 # define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0)
1637 # define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next)
1638 # if defined(_MSC_VER) \
1639  && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
1640 # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1641  PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1642 # else
1643 # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1644  PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1645 # endif
1646 # define PYBIND11_MAP_LIST_NEXT(test, next) \
1647  PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1648 # define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1649  f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__)
1650 # define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1651  f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__)
1652 // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
1653 # define PYBIND11_MAP_LIST(f, t, ...) \
1654  PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0))
1655 
1656 # define PYBIND11_NUMPY_DTYPE(Type, ...) \
1657  ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1658  ::std::vector<::pybind11::detail::field_descriptor>{ \
1659  PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1660 
1661 # if defined(_MSC_VER) && !defined(__clang__)
1662 # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1663  PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1664 # else
1665 # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1666  PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1667 # endif
1668 # define PYBIND11_MAP2_LIST_NEXT(test, next) \
1669  PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1670 # define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1671  f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__)
1672 # define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1673  f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__)
1674 // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
1675 # define PYBIND11_MAP2_LIST(f, t, ...) \
1676  PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0))
1677 
1678 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1679  ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1680  ::std::vector<::pybind11::detail::field_descriptor>{ \
1681  PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1682 
1683 #endif // __CLION_IDE__
1684 
1686 public:
1687  using container_type = std::vector<ssize_t>;
1688  using value_type = container_type::value_type;
1689  using size_type = container_type::size_type;
1690 
1691  common_iterator() : m_strides() {}
1692 
1693  common_iterator(void *ptr, const container_type &strides, const container_type &shape)
1694  : p_ptr(reinterpret_cast<char *>(ptr)), m_strides(strides.size()) {
1695  m_strides.back() = static_cast<value_type>(strides.back());
1696  for (size_type i = m_strides.size() - 1; i != 0; --i) {
1697  size_type j = i - 1;
1698  auto s = static_cast<value_type>(shape[i]);
1699  m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
1700  }
1701  }
1702 
1703  void increment(size_type dim) { p_ptr += m_strides[dim]; }
1704 
1705  void *data() const { return p_ptr; }
1706 
1707 private:
1708  char *p_ptr{nullptr};
1710 };
1711 
1712 template <size_t N>
1714 public:
1715  using container_type = std::vector<ssize_t>;
1716 
1717  multi_array_iterator(const std::array<buffer_info, N> &buffers, const container_type &shape)
1718  : m_shape(shape.size()), m_index(shape.size(), 0), m_common_iterator() {
1719 
1720  // Manual copy to avoid conversion warning if using std::copy
1721  for (size_t i = 0; i < shape.size(); ++i) {
1722  m_shape[i] = shape[i];
1723  }
1724 
1725  container_type strides(shape.size());
1726  for (size_t i = 0; i < N; ++i) {
1727  init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
1728  }
1729  }
1730 
1732  for (size_t j = m_index.size(); j != 0; --j) {
1733  size_t i = j - 1;
1734  if (++m_index[i] != m_shape[i]) {
1735  increment_common_iterator(i);
1736  break;
1737  }
1738  m_index[i] = 0;
1739  }
1740  return *this;
1741  }
1742 
1743  template <size_t K, class T = void>
1744  T *data() const {
1745  return reinterpret_cast<T *>(m_common_iterator[K].data());
1746  }
1747 
1748 private:
1750 
1752  const container_type &shape,
1755  auto buffer_shape_iter = buffer.shape.rbegin();
1756  auto buffer_strides_iter = buffer.strides.rbegin();
1757  auto shape_iter = shape.rbegin();
1758  auto strides_iter = strides.rbegin();
1759 
1760  while (buffer_shape_iter != buffer.shape.rend()) {
1761  if (*shape_iter == *buffer_shape_iter) {
1762  *strides_iter = *buffer_strides_iter;
1763  } else {
1764  *strides_iter = 0;
1765  }
1766 
1767  ++buffer_shape_iter;
1768  ++buffer_strides_iter;
1769  ++shape_iter;
1770  ++strides_iter;
1771  }
1772 
1773  std::fill(strides_iter, strides.rend(), 0);
1774  iterator = common_iter(buffer.ptr, strides, shape);
1775  }
1776 
1777  void increment_common_iterator(size_t dim) {
1778  for (auto &iter : m_common_iterator) {
1779  iter.increment(dim);
1780  }
1781  }
1782 
1785  std::array<common_iter, N> m_common_iterator;
1786 };
1787 
1789 
1790 // Populates the shape and number of dimensions for the set of buffers. Returns a
1791 // broadcast_trivial enum value indicating whether the broadcast is "trivial"--that is, has each
1792 // buffer being either a singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous
1793 // (`f_trivial`) storage buffer; returns `non_trivial` otherwise.
1794 template <size_t N>
1796 broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
1797  ndim = std::accumulate(
1798  buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
1799  return std::max(res, buf.ndim);
1800  });
1801 
1802  shape.clear();
1803  shape.resize((size_t) ndim, 1);
1804 
1805  // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1
1806  // or the full size).
1807  for (size_t i = 0; i < N; ++i) {
1808  auto res_iter = shape.rbegin();
1809  auto end = buffers[i].shape.rend();
1810  for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end;
1811  ++shape_iter, ++res_iter) {
1812  const auto &dim_size_in = *shape_iter;
1813  auto &dim_size_out = *res_iter;
1814 
1815  // Each input dimension can either be 1 or `n`, but `n` values must match across
1816  // buffers
1817  if (dim_size_out == 1) {
1818  dim_size_out = dim_size_in;
1819  } else if (dim_size_in != 1 && dim_size_in != dim_size_out) {
1820  pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
1821  }
1822  }
1823  }
1824 
1825  bool trivial_broadcast_c = true;
1826  bool trivial_broadcast_f = true;
1827  for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
1828  if (buffers[i].size == 1) {
1829  continue;
1830  }
1831 
1832  // Require the same number of dimensions:
1833  if (buffers[i].ndim != ndim) {
1835  }
1836 
1837  // Require all dimensions be full-size:
1838  if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin())) {
1840  }
1841 
1842  // Check for C contiguity (but only if previous inputs were also C contiguous)
1843  if (trivial_broadcast_c) {
1844  ssize_t expect_stride = buffers[i].itemsize;
1845  auto end = buffers[i].shape.crend();
1846  for (auto shape_iter = buffers[i].shape.crbegin(),
1847  stride_iter = buffers[i].strides.crbegin();
1848  trivial_broadcast_c && shape_iter != end;
1849  ++shape_iter, ++stride_iter) {
1850  if (expect_stride == *stride_iter) {
1851  expect_stride *= *shape_iter;
1852  } else {
1853  trivial_broadcast_c = false;
1854  }
1855  }
1856  }
1857 
1858  // Check for Fortran contiguity (if previous inputs were also F contiguous)
1859  if (trivial_broadcast_f) {
1860  ssize_t expect_stride = buffers[i].itemsize;
1861  auto end = buffers[i].shape.cend();
1862  for (auto shape_iter = buffers[i].shape.cbegin(),
1863  stride_iter = buffers[i].strides.cbegin();
1864  trivial_broadcast_f && shape_iter != end;
1865  ++shape_iter, ++stride_iter) {
1866  if (expect_stride == *stride_iter) {
1867  expect_stride *= *shape_iter;
1868  } else {
1869  trivial_broadcast_f = false;
1870  }
1871  }
1872  }
1873  }
1874 
1875  return trivial_broadcast_c ? broadcast_trivial::c_trivial
1876  : trivial_broadcast_f ? broadcast_trivial::f_trivial
1878 }
1879 
1880 template <typename T>
1882  static_assert(!std::is_rvalue_reference<T>::value,
1883  "Functions with rvalue reference arguments cannot be vectorized");
1884  // The wrapped function gets called with this type:
1886  // Is this a vectorized argument?
1887  static constexpr bool vectorize
1890  std::is_pointer,
1891  std::is_array,
1892  is_std_array,
1893  std::is_enum>::value
1896  // Accept this type: an array for vectorized types, otherwise the type as-is:
1898 };
1899 
1900 // py::vectorize when a return type is present
1901 template <typename Func, typename Return, typename... Args>
1904 
1905  static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) {
1906  if (trivial == broadcast_trivial::f_trivial) {
1907  return array_t<Return, array::f_style>(shape);
1908  }
1909  return array_t<Return>(shape);
1910  }
1911 
1912  static Return *mutable_data(Type &array) { return array.mutable_data(); }
1913 
1914  static Return call(Func &f, Args &...args) { return f(args...); }
1915 
1916  static void call(Return *out, size_t i, Func &f, Args &...args) { out[i] = f(args...); }
1917 };
1918 
1919 // py::vectorize when a return type is not present
1920 template <typename Func, typename... Args>
1921 struct vectorize_returned_array<Func, void, Args...> {
1922  using Type = none;
1923 
1924  static Type create(broadcast_trivial, const std::vector<ssize_t> &) { return none(); }
1925 
1926  static void *mutable_data(Type &) { return nullptr; }
1927 
1928  static detail::void_type call(Func &f, Args &...args) {
1929  f(args...);
1930  return {};
1931  }
1932 
1933  static void call(void *, size_t, Func &f, Args &...args) { f(args...); }
1934 };
1935 
1936 template <typename Func, typename Return, typename... Args>
1938 
1939 // NVCC for some reason breaks if NVectorized is private
1940 #ifdef __CUDACC__
1941 public:
1942 #else
1943 private:
1944 #endif
1945 
1946  static constexpr size_t N = sizeof...(Args);
1947  static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
1948  static_assert(
1949  NVectorized >= 1,
1950  "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
1951 
1952 public:
1953  template <typename T,
1954  // SFINAE to prevent shadowing the copy constructor.
1955  typename = detail::enable_if_t<
1957  explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) {}
1958 
1960  return run(args...,
1964  }
1965 
1966 private:
1968 
1969  // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling
1970  // with "/permissive-" flag when arg_call_types is manually inlined.
1971  using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;
1972  template <size_t Index>
1974 
1975  using returned_array = vectorize_returned_array<Func, Return, Args...>;
1976 
1977  // Runs a vectorized function given arguments tuple and three index sequences:
1978  // - Index is the full set of 0 ... (N-1) argument indices;
1979  // - VIndex is the subset of argument indices with vectorized parameters, letting us access
1980  // vectorized arguments (anything not in this sequence is passed through)
1981  // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
1982  // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
1983  // index BIndex in the array).
1984  template <size_t... Index, size_t... VIndex, size_t... BIndex>
1985  object run(typename vectorize_arg<Args>::type &...args,
1988  index_sequence<BIndex...> bi_seq) {
1989 
1990  // Pointers to values the function was called with; the vectorized ones set here will start
1991  // out as array_t<T> pointers, but they will be changed them to T pointers before we make
1992  // call the wrapped function. Non-vectorized pointers are left as-is.
1993  std::array<void *, N> params{{reinterpret_cast<void *>(&args)...}};
1994 
1995  // The array of `buffer_info`s of vectorized arguments:
1996  std::array<buffer_info, NVectorized> buffers{
1997  {reinterpret_cast<array *>(params[VIndex])->request()...}};
1998 
1999  /* Determine dimensions parameters of output array */
2000  ssize_t nd = 0;
2001  std::vector<ssize_t> shape(0);
2002  auto trivial = broadcast(buffers, nd, shape);
2003  auto ndim = (size_t) nd;
2004 
2005  size_t size
2006  = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
2007 
2008  // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
2009  // not wrapped in an array).
2010  if (size == 1 && ndim == 0) {
2011  PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
2012  return cast(
2013  returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...));
2014  }
2015 
2016  auto result = returned_array::create(trivial, shape);
2017 
2018  PYBIND11_WARNING_PUSH
2019 #ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
2020  PYBIND11_WARNING_DISABLE_CLANG("-Wreturn-std-move")
2021 #endif
2022 
2023  if (size == 0) {
2024  return result;
2025  }
2026 
2027  /* Call the function */
2028  auto *mutable_data = returned_array::mutable_data(result);
2029  if (trivial == broadcast_trivial::non_trivial) {
2030  apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq);
2031  } else {
2032  apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq);
2033  }
2034 
2035  return result;
2037  }
2038 
2039  template <size_t... Index, size_t... VIndex, size_t... BIndex>
2040  void apply_trivial(std::array<buffer_info, NVectorized> &buffers,
2041  std::array<void *, N> &params,
2042  Return *out,
2043  size_t size,
2047 
2048  // Initialize an array of mutable byte references and sizes with references set to the
2049  // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
2050  // (except for singletons, which get an increment of 0).
2051  std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{
2052  {std::pair<unsigned char *&, const size_t>(
2053  reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
2054  buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>))...}};
2055 
2056  for (size_t i = 0; i < size; ++i) {
2057  returned_array::call(
2058  out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...);
2059  for (auto &x : vecparams) {
2060  x.first += x.second;
2061  }
2062  }
2063  }
2064 
2065  template <size_t... Index, size_t... VIndex, size_t... BIndex>
2066  void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
2067  std::array<void *, N> &params,
2068  Return *out,
2069  size_t size,
2070  const std::vector<ssize_t> &output_shape,
2074 
2075  multi_array_iterator<NVectorized> input_iter(buffers, output_shape);
2076 
2077  for (size_t i = 0; i < size; ++i, ++input_iter) {
2078  PYBIND11_EXPAND_SIDE_EFFECTS((params[VIndex] = input_iter.template data<BIndex>()));
2079  returned_array::call(
2080  out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
2081  }
2082  }
2083 };
2084 
2085 template <typename Func, typename Return, typename... Args>
2086 vectorize_helper<Func, Return, Args...> vectorize_extractor(const Func &f, Return (*)(Args...)) {
2087  return detail::vectorize_helper<Func, Return, Args...>(f);
2088 }
2089 
2090 template <typename T, int Flags>
2091 struct handle_type_name<array_t<T, Flags>> {
2092  static constexpr auto name
2094 };
2095 
2097 
2098 // Vanilla pointer vectorizer:
2099 template <typename Return, typename... Args>
2100 detail::vectorize_helper<Return (*)(Args...), Return, Args...> vectorize(Return (*f)(Args...)) {
2101  return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
2102 }
2103 
2104 // lambda vectorizer:
2106 auto vectorize(Func &&f)
2107  -> decltype(detail::vectorize_extractor(std::forward<Func>(f),
2108  (detail::function_signature_t<Func> *) nullptr)) {
2109  return detail::vectorize_extractor(std::forward<Func>(f),
2110  (detail::function_signature_t<Func> *) nullptr);
2111 }
2112 
2113 // Vectorize a class method (non-const):
2114 template <typename Return,
2115  typename Class,
2116  typename... Args,
2117  typename Helper = detail::vectorize_helper<
2118  decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())),
2119  Return,
2120  Class *,
2121  Args...>>
2122 Helper vectorize(Return (Class::*f)(Args...)) {
2123  return Helper(std::mem_fn(f));
2124 }
2125 
2126 // Vectorize a class method (const):
2127 template <typename Return,
2128  typename Class,
2129  typename... Args,
2130  typename Helper = detail::vectorize_helper<
2131  decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())),
2132  Return,
2133  const Class *,
2134  Args...>>
2135 Helper vectorize(Return (Class::*f)(Args...) const) {
2136  return Helper(std::mem_fn(f));
2137 }
2138 
common_iterator::m_strides
container_type m_strides
Definition: numpy.h:1709
array_t::itemsize
constexpr ssize_t itemsize() const
Definition: numpy.h:1215
select_indices
typename select_indices_impl< index_sequence<>, 0, Bs... >::type select_indices
Definition: wrap/pybind11/include/pybind11/detail/common.h:726
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:1229
npy_format_descriptor::dtype_ptr
static PyObject * dtype_ptr()
Definition: numpy.h:1587
create
ADT create(const Signature &signature)
Definition: testAlgebraicDecisionTree.cpp:145
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:1055
vectorize_helper
Definition: numpy.h:1937
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:759
array_t::ensure
static array_t ensure(handle h)
Definition: numpy.h:1277
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:1967
array::strides
ssize_t strides(ssize_t dim) const
Stride along a given axis.
Definition: numpy.h:958
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:1957
PYBIND11_EXPAND_SIDE_EFFECTS
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
Definition: wrap/pybind11/include/pybind11/detail/common.h:1010
array::fail_dim_check
void fail_dim_check(ssize_t dim, const std::string &msg) const
Definition: numpy.h:1113
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:177
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:1784
array::unchecked
detail::unchecked_reference< T, Dims > unchecked() const &
Definition: numpy.h:1038
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:1089
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:704
npy_api::NPY_BOOL_
@ NPY_BOOL_
Definition: numpy.h:223
vectorize_arg
Definition: numpy.h:1881
gtsam.examples.DogLegOptimizerExample.type
type
Definition: DogLegOptimizerExample.py:111
ssize_t
Py_ssize_t ssize_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:508
array::check_dimensions
void check_dimensions(Ix... index) const
Definition: numpy.h:1131
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:989
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:1788
return_value_policy
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: wrap/pybind11/include/pybind11/detail/common.h:518
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:947
array< double >::ShapeContainer
detail::any_container< ssize_t > ShapeContainer
Definition: numpy.h:833
list
Definition: pytypes.h:2168
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:1484
npy_api::NPY_INT_
@ NPY_INT_
Definition: numpy.h:228
array_t::mutable_data
T * mutable_data(Ix... index)
Definition: numpy.h:1228
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:1985
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:847
PYBIND11_OBJECT_CVT
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:1409
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:1177
array_t::data
const T * data(Ix... index) const
Definition: numpy.h:1223
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:1688
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:1336
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:938
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:932
npy_api::NPY_BYTE_
@ NPY_BYTE_
Definition: numpy.h:224
array_t::array_t
array_t()
Definition: numpy.h:1175
vectorize_returned_array< Func, void, Args... >::mutable_data
static void * mutable_data(Type &)
Definition: numpy.h:1926
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:1356
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:31
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:1912
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:1527
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:247
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:1364
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:1796
detail
Definition: testSerializationNonlinear.cpp:69
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:1592
buffer
Definition: pytypes.h:2272
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:1462
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:1285
array_t::array_t
array_t(ssize_t count, const T *ptr=nullptr, handle base=handle())
Definition: numpy.h:1212
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:163
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:944
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:675
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:1574
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:1004
PyArrayDescr1_Proxy::fields
PyObject * fields
Definition: numpy.h:79
field_descriptor::name
const char * name
Definition: numpy.h:1483
vectorize_returned_array
Definition: numpy.h:1902
vectorize_returned_array::call
static void call(Return *out, size_t i, Func &f, Args &...args)
Definition: numpy.h:1916
any_container
Definition: wrap/pybind11/include/pybind11/detail/common.h:1173
array_t
Definition: numpy.h:1159
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:1744
vectorize_arg::type
conditional_t< vectorize, array_t< remove_cv_t< call_type >, array::forcecast >, T > type
Definition: numpy.h:1897
vectorize_returned_array< Func, void, Args... >::call
static void call(void *, size_t, Func &f, Args &...args)
Definition: numpy.h:1933
dict
Definition: pytypes.h:2109
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:974
array_t::array_t
array_t(const object &o)
Definition: numpy.h:1190
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:1204
npy_api::lookup
static npy_api lookup()
Definition: numpy.h:346
array::array
array(const buffer_info &info, handle base=handle())
Definition: numpy.h:918
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:1885
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:1390
multi_array_iterator::increment_common_iterator
void increment_common_iterator(size_t dim)
Definition: numpy.h:1777
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:1161
field_descriptor::descr
dtype descr
Definition: numpy.h:1487
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:1427
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:1971
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:1713
multi_array_iterator::container_type
std::vector< ssize_t > container_type
Definition: numpy.h:1715
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:935
common_iterator
Definition: numpy.h:1685
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:2100
negation
Definition: wrap/pybind11/include/pybind11/detail/common.h:732
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:911
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:1691
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:1259
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:1045
vectorize_returned_array::call
static Return call(Func &f, Args &...args)
Definition: numpy.h:1914
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:1045
gil_safe_call_once_and_store
Definition: gil_safe_call_once.h:50
vectorize_returned_array::create
static Type create(broadcast_trivial trivial, const std::vector< ssize_t > &shape)
Definition: numpy.h:1905
format_descriptor< std::array< char, N > >::format
static std::string format()
Definition: numpy.h:1323
gil_safe_call_once_and_store::get_stored
T & get_stored()
Definition: gil_safe_call_once.h:72
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:1693
size_t
std::size_t size_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:509
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:1234
npy_api::PyArray_Dims
Definition: numpy.h:265
multi_array_iterator::operator++
multi_array_iterator & operator++()
Definition: numpy.h:1731
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:1464
pytypes.h
format_descriptor< T, detail::enable_if_t< detail::is_pod_struct< T >::value > >::format
static std::string format()
Definition: numpy.h:1312
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:1560
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:1689
npy_format_descriptor::register_dtype
static void register_dtype(any_container< field_descriptor > fields)
Definition: numpy.h:1579
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:696
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:1783
array::size
ssize_t size() const
Total number of elements.
Definition: numpy.h:927
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:1020
field_descriptor::size
ssize_t size
Definition: numpy.h:1485
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:1135
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:1124
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:730
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:1572
multi_array_iterator::m_common_iterator
std::array< common_iter, N > m_common_iterator
Definition: numpy.h:1785
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:1447
platform_lookup
constexpr int platform_lookup()
Definition: numpy.h:204
array
Definition: numpy.h:821
field_descriptor
Definition: numpy.h:1482
array::squeeze
array squeeze()
Return a new view with all of the dimensions of length 1 removed.
Definition: numpy.h:1048
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:193
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:712
handle_type_name
Definition: cast.h:901
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:981
multi_array_iterator::multi_array_iterator
multi_array_iterator(const std::array< buffer_info, N > &buffers, const container_type &shape)
Definition: numpy.h:1717
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:1148
forward
Definition: testScenarioRunner.cpp:79
PyArrayDescr2_Proxy::elsize
ssize_t elsize
Definition: numpy.h:109
module_
Wrapper for Python extension modules.
Definition: pybind11.h:1171
PyArrayDescr2_Proxy::subarray
char * subarray
Definition: numpy.h:115
with_internals
auto with_internals(const F &cb) -> decltype(cb(get_internals()))
Definition: internals.h:640
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:1328
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:922
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:1271
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:1295
array::byte_offset
ssize_t byte_offset(Ix... index) const
Definition: numpy.h:1119
array::reshape
array reshape(ShapeContainer new_shape)
Optional order parameter omitted, to be added as needed.
Definition: numpy.h:1073
iter
iterator iter(handle obj)
Definition: pytypes.h:2477
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:2066
array::ensure
static array ensure(handle h, int ExtraFlags=0)
Definition: numpy.h:1101
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:1973
args
Definition: pytypes.h:2212
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:54
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:1198
vectorize_returned_array< Func, void, Args... >::create
static Type create(broadcast_trivial, const std::vector< ssize_t > &)
Definition: numpy.h:1924
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:1196
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:701
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:1176
array::resize
void resize(ShapeContainer new_shape, bool refcheck=true)
Definition: numpy.h:1056
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:2079
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:1751
field_descriptor::format
std::string format
Definition: numpy.h:1486
list::append
void append(T &&val)
Definition: pytypes.h:2189
array_t::mutable_at
T & mutable_at(Ix... index)
Definition: numpy.h:1244
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:1218
vectorize_returned_array< Func, void, Args... >::call
static detail::void_type call(Func &f, Args &...args)
Definition: numpy.h:1928
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:1319
array::base
object base() const
Base object.
Definition: numpy.h:941
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:2086
PYBIND11_DECL_CHAR_FMT
#define PYBIND11_DECL_CHAR_FMT
Definition: numpy.h:1439
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:2448
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:1490
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:1300
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:1788
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:1163
array_info_scalar::is_empty
static constexpr bool is_empty
Definition: numpy.h:426
npy_format_descriptor_name
Definition: numpy.h:1370
common_iterator::container_type
std::vector< ssize_t > container_type
Definition: numpy.h:1687
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:1703
vectorize_helper::operator()
object operator()(typename vectorize_arg< Args >::type... args)
Definition: numpy.h:1959
gtsam::convert
static BinaryMeasurement< Rot3 > convert(const BetweenFactor< Pose3 >::shared_ptr &f)
Definition: ShonanAveraging.cpp:995
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:673
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:966
PyArrayDescr_Proxy::typeobj
PyObject_HEAD PyObject * typeobj
Definition: numpy.h:86
test_callbacks.value
value
Definition: test_callbacks.py:162
array::writeable
bool writeable() const
If set, the array is writeable (otherwise the buffer is read-only)
Definition: numpy.h:969
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:1348
common_iterator::data
void * data() const
Definition: numpy.h:1705
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:997
array::strides
const ssize_t * strides() const
Strides of the array.
Definition: numpy.h:955
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:679
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:1009
array::check_dimensions_impl
void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const
Definition: numpy.h:1138
complex
Definition: datatypes.h:12
array::array
array(ssize_t count, const T *ptr, handle base=handle())
Definition: numpy.h:915
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:1436
npy_format_descriptor< T, enable_if_t< std::is_enum< T >::value > >::dtype
static pybind11::dtype dtype()
Definition: numpy.h:1479
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:2040
PyArrayDescr_Proxy
Definition: numpy.h:84
npy_api::NPY_VOID_
@ NPY_VOID_
Definition: numpy.h:243


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