cppyabm  1.0.17
An agent-based library to integrate C++ and Python
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 "complex.h"
14 #include <numeric>
15 #include <algorithm>
16 #include <array>
17 #include <cstdint>
18 #include <cstdlib>
19 #include <cstring>
20 #include <sstream>
21 #include <string>
22 #include <functional>
23 #include <type_traits>
24 #include <utility>
25 #include <vector>
26 #include <typeindex>
27 
28 #if defined(_MSC_VER)
29 # pragma warning(push)
30 # pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
31 #endif
32 
33 /* This will be true on all flat address space platforms and allows us to reduce the
34  whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size
35  and dimension types (e.g. shape, strides, indexing), instead of inflicting this
36  upon the library user. */
37 static_assert(sizeof(::pybind11::ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
38 static_assert(std::is_signed<Py_intptr_t>::value, "Py_intptr_t must be signed");
39 // We now can reinterpret_cast between py::ssize_t and Py_intptr_t (MSVC + PyPy cares)
40 
42 
43 class array; // Forward declaration
44 
46 
47 template <> struct handle_type_name<array> { static constexpr auto name = _("numpy.ndarray"); };
48 
49 template <typename type, typename SFINAE = void> struct npy_format_descriptor;
50 
52  PyObject_HEAD
53  PyObject *typeobj;
54  char kind;
55  char type;
56  char byteorder;
57  char flags;
58  int type_num;
59  int elsize;
60  int alignment;
61  char *subarray;
62  PyObject *fields;
63  PyObject *names;
64 };
65 
66 struct PyArray_Proxy {
67  PyObject_HEAD
68  char *data;
69  int nd;
72  PyObject *base;
73  PyObject *descr;
74  int flags;
75 };
76 
78  PyObject_VAR_HEAD
79  char *obval;
81  int flags;
82  PyObject *base;
83 };
84 
86  PyObject* dtype_ptr;
87  std::string format_str;
88 };
89 
91  std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;
92 
93  numpy_type_info *get_type_info(const std::type_info& tinfo, bool throw_if_missing = true) {
94  auto it = registered_dtypes.find(std::type_index(tinfo));
95  if (it != registered_dtypes.end())
96  return &(it->second);
97  if (throw_if_missing)
98  pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name());
99  return nullptr;
100  }
101 
102  template<typename T> numpy_type_info *get_type_info(bool throw_if_missing = true) {
103  return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);
104  }
105 };
106 
108  ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals");
109 }
110 
112  static numpy_internals* ptr = nullptr;
113  if (!ptr)
115  return *ptr;
116 }
117 
118 template <typename T> struct same_size {
119  template <typename U> using as = bool_constant<sizeof(T) == sizeof(U)>;
120 };
121 
122 template <typename Concrete> constexpr int platform_lookup() { return -1; }
123 
124 // Lookup a type according to its size, and return a value corresponding to the NumPy typenum.
125 template <typename Concrete, typename T, typename... Ts, typename... Ints>
126 constexpr int platform_lookup(int I, Ints... Is) {
127  return sizeof(Concrete) == sizeof(T) ? I : platform_lookup<Concrete, Ts...>(Is...);
128 }
129 
130 struct npy_api {
131  enum constants {
149  // Platform-dependent normalization
154  // `npy_common.h` defines the integer aliases. In order, it checks:
155  // NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR
156  // and assigns the alias to the first matching size, so we should check in this order.
157  NPY_INT32_ = platform_lookup<std::int32_t, long, int, short>(
159  NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(
161  NPY_INT64_ = platform_lookup<std::int64_t, long, long long, int>(
163  NPY_UINT64_ = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(
165  };
166 
167  typedef struct {
168  Py_intptr_t *ptr;
169  int len;
170  } PyArray_Dims;
171 
172  static npy_api& get() {
173  static npy_api api = lookup();
174  return api;
175  }
176 
177  bool PyArray_Check_(PyObject *obj) const {
178  return (bool) PyObject_TypeCheck(obj, PyArray_Type_);
179  }
180  bool PyArrayDescr_Check_(PyObject *obj) const {
181  return (bool) PyObject_TypeCheck(obj, PyArrayDescr_Type_);
182  }
183 
185  PyObject *(*PyArray_DescrFromType_)(int);
186  PyObject *(*PyArray_NewFromDescr_)
187  (PyTypeObject *, PyObject *, int, Py_intptr_t const *,
188  Py_intptr_t const *, void *, int, PyObject *);
189  // Unused. Not removed because that affects ABI of the class.
190  PyObject *(*PyArray_DescrNewFromType_)(int);
191  int (*PyArray_CopyInto_)(PyObject *, PyObject *);
192  PyObject *(*PyArray_NewCopy_)(PyObject *, int);
193  PyTypeObject *PyArray_Type_;
194  PyTypeObject *PyVoidArrType_Type_;
195  PyTypeObject *PyArrayDescr_Type_;
196  PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
197  PyObject *(*PyArray_FromAny_) (PyObject *, PyObject *, int, int, int, PyObject *);
198  int (*PyArray_DescrConverter_) (PyObject *, PyObject **);
199  bool (*PyArray_EquivTypes_) (PyObject *, PyObject *);
200  int (*PyArray_GetArrayParamsFromObject_)(PyObject *, PyObject *, unsigned char, PyObject **, int *,
201  Py_intptr_t *, PyObject **, PyObject *);
202  PyObject *(*PyArray_Squeeze_)(PyObject *);
203  // Unused. Not removed because that affects ABI of the class.
204  int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);
205  PyObject* (*PyArray_Resize_)(PyObject*, PyArray_Dims*, int, int);
206 private:
207  enum functions {
208  API_PyArray_GetNDArrayCFeatureVersion = 211,
209  API_PyArray_Type = 2,
210  API_PyArrayDescr_Type = 3,
211  API_PyVoidArrType_Type = 39,
212  API_PyArray_DescrFromType = 45,
213  API_PyArray_DescrFromScalar = 57,
214  API_PyArray_FromAny = 69,
215  API_PyArray_Resize = 80,
216  API_PyArray_CopyInto = 82,
217  API_PyArray_NewCopy = 85,
218  API_PyArray_NewFromDescr = 94,
219  API_PyArray_DescrNewFromType = 96,
220  API_PyArray_DescrConverter = 174,
221  API_PyArray_EquivTypes = 182,
222  API_PyArray_GetArrayParamsFromObject = 278,
223  API_PyArray_Squeeze = 136,
224  API_PyArray_SetBaseObject = 282
225  };
226 
227  static npy_api lookup() {
228  module_ m = module_::import("numpy.core.multiarray");
229  auto c = m.attr("_ARRAY_API");
230 #if PY_MAJOR_VERSION >= 3
231  void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), NULL);
232 #else
233  void **api_ptr = (void **) PyCObject_AsVoidPtr(c.ptr());
234 #endif
235  npy_api api;
236 #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
237  DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);
238  if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7)
239  pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0");
240  DECL_NPY_API(PyArray_Type);
241  DECL_NPY_API(PyVoidArrType_Type);
242  DECL_NPY_API(PyArrayDescr_Type);
243  DECL_NPY_API(PyArray_DescrFromType);
244  DECL_NPY_API(PyArray_DescrFromScalar);
245  DECL_NPY_API(PyArray_FromAny);
246  DECL_NPY_API(PyArray_Resize);
247  DECL_NPY_API(PyArray_CopyInto);
248  DECL_NPY_API(PyArray_NewCopy);
249  DECL_NPY_API(PyArray_NewFromDescr);
250  DECL_NPY_API(PyArray_DescrNewFromType);
251  DECL_NPY_API(PyArray_DescrConverter);
252  DECL_NPY_API(PyArray_EquivTypes);
253  DECL_NPY_API(PyArray_GetArrayParamsFromObject);
254  DECL_NPY_API(PyArray_Squeeze);
255  DECL_NPY_API(PyArray_SetBaseObject);
256 #undef DECL_NPY_API
257  return api;
258  }
259 };
260 
261 inline PyArray_Proxy* array_proxy(void* ptr) {
262  return reinterpret_cast<PyArray_Proxy*>(ptr);
263 }
264 
265 inline const PyArray_Proxy* array_proxy(const void* ptr) {
266  return reinterpret_cast<const PyArray_Proxy*>(ptr);
267 }
268 
270  return reinterpret_cast<PyArrayDescr_Proxy*>(ptr);
271 }
272 
273 inline const PyArrayDescr_Proxy* array_descriptor_proxy(const PyObject* ptr) {
274  return reinterpret_cast<const PyArrayDescr_Proxy*>(ptr);
275 }
276 
277 inline bool check_flags(const void* ptr, int flag) {
278  return (flag == (array_proxy(ptr)->flags & flag));
279 }
280 
281 template <typename T> struct is_std_array : std::false_type { };
282 template <typename T, size_t N> struct is_std_array<std::array<T, N>> : std::true_type { };
283 template <typename T> struct is_complex : std::false_type { };
284 template <typename T> struct is_complex<std::complex<T>> : std::true_type { };
285 
286 template <typename T> struct array_info_scalar {
287  using type = T;
288  static constexpr bool is_array = false;
289  static constexpr bool is_empty = false;
290  static constexpr auto extents = _("");
291  static void append_extents(list& /* shape */) { }
292 };
293 // Computes underlying type and a comma-separated list of extents for array
294 // types (any mix of std::array and built-in arrays). An array of char is
295 // treated as scalar because it gets special handling.
296 template <typename T> struct array_info : array_info_scalar<T> { };
297 template <typename T, size_t N> struct array_info<std::array<T, N>> {
298  using type = typename array_info<T>::type;
299  static constexpr bool is_array = true;
300  static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;
301  static constexpr size_t extent = N;
302 
303  // appends the extents to shape
304  static void append_extents(list& shape) {
305  shape.append(N);
307  }
308 
309  static constexpr auto extents = _<array_info<T>::is_array>(
310  concat(_<N>(), array_info<T>::extents), _<N>()
311  );
312 };
313 // For numpy we have special handling for arrays of characters, so we don't include
314 // the size in the array extents.
315 template <size_t N> struct array_info<char[N]> : array_info_scalar<char[N]> { };
316 template <size_t N> struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> { };
317 template <typename T, size_t N> struct array_info<T[N]> : array_info<std::array<T, N>> { };
318 template <typename T> using remove_all_extents_t = typename array_info<T>::type;
319 
320 template <typename T> using is_pod_struct = all_of<
321  std::is_standard_layout<T>, // since we're accessing directly in memory we need a standard layout type
322 #if !defined(__GNUG__) || defined(_LIBCPP_VERSION) || defined(_GLIBCXX_USE_CXX11_ABI)
323  // _GLIBCXX_USE_CXX11_ABI indicates that we're using libstdc++ from GCC 5 or newer, independent
324  // of the actual compiler (Clang can also use libstdc++, but it always defines __GNUC__ == 4).
325  std::is_trivially_copyable<T>,
326 #else
327  // GCC 4 doesn't implement is_trivially_copyable, so approximate it
328  std::is_trivially_destructible<T>,
330 #endif
332 >;
333 
334 // Replacement for std::is_pod (deprecated in C++20)
335 template <typename T> using is_pod = all_of<
336  std::is_standard_layout<T>,
337  std::is_trivial<T>
338 >;
339 
340 template <ssize_t Dim = 0, typename Strides> ssize_t byte_offset_unsafe(const Strides &) { return 0; }
341 template <ssize_t Dim = 0, typename Strides, typename... Ix>
342 ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {
343  return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);
344 }
345 
346 /**
347  * Proxy class providing unsafe, unchecked const access to array data. This is constructed through
348  * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims`
349  * will be -1 for dimensions determined at runtime.
350  */
351 template <typename T, ssize_t Dims>
353 protected:
354  static constexpr bool Dynamic = Dims < 0;
355  const unsigned char *data_;
356  // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
357  // make large performance gains on big, nested loops, but requires compile-time dimensions
358  conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>>
360  const ssize_t dims_;
361 
362  friend class pybind11::array;
363  // Constructor for compile-time dimensions:
364  template <bool Dyn = Dynamic>
366  : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
367  for (size_t i = 0; i < (size_t) dims_; i++) {
368  shape_[i] = shape[i];
369  strides_[i] = strides[i];
370  }
371  }
372  // Constructor for runtime dimensions:
373  template <bool Dyn = Dynamic>
374  unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<Dyn, ssize_t> dims)
375  : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides}, dims_{dims} {}
376 
377 public:
378  /**
379  * Unchecked const reference access to data at the given indices. For a compile-time known
380  * number of dimensions, this requires the correct number of arguments; for run-time
381  * dimensionality, this is not checked (and so is up to the caller to use safely).
382  */
383  template <typename... Ix> const T &operator()(Ix... index) const {
384  static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
385  "Invalid number of indices for unchecked array reference");
386  return *reinterpret_cast<const T *>(data_ + byte_offset_unsafe(strides_, ssize_t(index)...));
387  }
388  /**
389  * Unchecked const reference access to data; this operator only participates if the reference
390  * is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`.
391  */
392  template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
393  const T &operator[](ssize_t index) const { return operator()(index); }
394 
395  /// Pointer access to the data at the given indices.
396  template <typename... Ix> const T *data(Ix... ix) const { return &operator()(ssize_t(ix)...); }
397 
398  /// Returns the item size, i.e. sizeof(T)
399  constexpr static ssize_t itemsize() { return sizeof(T); }
400 
401  /// Returns the shape (i.e. size) of dimension `dim`
402  ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; }
403 
404  /// Returns the number of dimensions of the array
405  ssize_t ndim() const { return dims_; }
406 
407  /// Returns the total number of elements in the referenced array, i.e. the product of the shapes
408  template <bool Dyn = Dynamic>
410  return std::accumulate(shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
411  }
412  template <bool Dyn = Dynamic>
414  return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
415  }
416 
417  /// Returns the total number of bytes used by the referenced data. Note that the actual span in
418  /// memory may be larger if the referenced array has non-contiguous strides (e.g. for a slice).
419  ssize_t nbytes() const {
420  return size() * itemsize();
421  }
422 };
423 
424 template <typename T, ssize_t Dims>
426  friend class pybind11::array;
428  using ConstBase::ConstBase;
429  using ConstBase::Dynamic;
430 public:
431  // Bring in const-qualified versions from base class
432  using ConstBase::operator();
433  using ConstBase::operator[];
434 
435  /// Mutable, unchecked access to data at the given indices.
436  template <typename... Ix> T& operator()(Ix... index) {
437  static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
438  "Invalid number of indices for unchecked array reference");
439  return const_cast<T &>(ConstBase::operator()(index...));
440  }
441  /**
442  * Mutable, unchecked access data at the given index; this operator only participates if the
443  * reference is to a 1-dimensional array (or has runtime dimensions). When present, this is
444  * exactly equivalent to `obj(index)`.
445  */
446  template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
447  T &operator[](ssize_t index) { return operator()(index); }
448 
449  /// Mutable pointer access to the data at the given indices.
450  template <typename... Ix> T *mutable_data(Ix... ix) { return &operator()(ssize_t(ix)...); }
451 };
452 
453 template <typename T, ssize_t Dim>
455  static_assert(Dim == 0 && Dim > 0 /* always fail */, "unchecked array proxy object is not castable");
456 };
457 template <typename T, ssize_t Dim>
458 struct type_caster<unchecked_mutable_reference<T, Dim>> : type_caster<unchecked_reference<T, Dim>> {};
459 
461 
462 class dtype : public object {
463 public:
464  PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_);
465 
466  explicit dtype(const buffer_info &info) {
467  dtype descr(_dtype_from_pep3118()(PYBIND11_STR_TYPE(info.format)));
468  // If info.itemsize == 0, use the value calculated from the format string
469  m_ptr = descr.strip_padding(info.itemsize ? info.itemsize : descr.itemsize()).release().ptr();
470  }
471 
472  explicit dtype(const std::string &format) {
473  m_ptr = from_args(pybind11::str(format)).release().ptr();
474  }
475 
476  dtype(const char *format) : dtype(std::string(format)) { }
477 
478  dtype(list names, list formats, list offsets, ssize_t itemsize) {
479  dict args;
480  args["names"] = names;
481  args["formats"] = formats;
482  args["offsets"] = offsets;
483  args["itemsize"] = pybind11::int_(itemsize);
484  m_ptr = from_args(args).release().ptr();
485  }
486 
487  /// This is essentially the same as calling numpy.dtype(args) in Python.
488  static dtype from_args(object args) {
489  PyObject *ptr = nullptr;
490  if (!detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) || !ptr)
491  throw error_already_set();
492  return reinterpret_steal<dtype>(ptr);
493  }
494 
495  /// Return dtype associated with a C++ type.
496  template <typename T> static dtype of() {
497  return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();
498  }
499 
500  /// Size of the data type in bytes.
501  ssize_t itemsize() const {
502  return detail::array_descriptor_proxy(m_ptr)->elsize;
503  }
504 
505  /// Returns true for structured data types.
506  bool has_fields() const {
507  return detail::array_descriptor_proxy(m_ptr)->names != nullptr;
508  }
509 
510  /// Single-character type code.
511  char kind() const {
512  return detail::array_descriptor_proxy(m_ptr)->kind;
513  }
514 
515 private:
516  static object _dtype_from_pep3118() {
517  static PyObject *obj = module_::import("numpy.core._internal")
518  .attr("_dtype_from_pep3118").cast<object>().release().ptr();
519  return reinterpret_borrow<object>(obj);
520  }
521 
522  dtype strip_padding(ssize_t itemsize) {
523  // Recursively strip all void fields with empty names that are generated for
524  // padding fields (as of NumPy v1.11).
525  if (!has_fields())
526  return *this;
527 
528  struct field_descr { PYBIND11_STR_TYPE name; object format; pybind11::int_ offset; };
529  std::vector<field_descr> field_descriptors;
530 
531  for (auto field : attr("fields").attr("items")()) {
532  auto spec = field.cast<tuple>();
533  auto name = spec[0].cast<pybind11::str>();
534  auto format = spec[1].cast<tuple>()[0].cast<dtype>();
535  auto offset = spec[1].cast<tuple>()[1].cast<pybind11::int_>();
536  if (!len(name) && format.kind() == 'V')
537  continue;
538  field_descriptors.push_back({(PYBIND11_STR_TYPE) name, format.strip_padding(format.itemsize()), offset});
539  }
540 
541  std::sort(field_descriptors.begin(), field_descriptors.end(),
542  [](const field_descr& a, const field_descr& b) {
543  return a.offset.cast<int>() < b.offset.cast<int>();
544  });
545 
546  list names, formats, offsets;
547  for (auto& descr : field_descriptors) {
548  names.append(descr.name);
549  formats.append(descr.format);
550  offsets.append(descr.offset);
551  }
552  return dtype(names, formats, offsets, itemsize);
553  }
554 };
555 
556 class array : public buffer {
557 public:
558  PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array)
559 
560  enum {
561  c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,
562  f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,
563  forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_
564  };
565 
566  array() : array(0, static_cast<const double *>(nullptr)) {}
567 
568  using ShapeContainer = detail::any_container<ssize_t>;
569  using StridesContainer = detail::any_container<ssize_t>;
570 
571  // Constructs an array taking shape/strides from arbitrary container types
572  array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides,
573  const void *ptr = nullptr, handle base = handle()) {
574 
575  if (strides->empty())
576  *strides = detail::c_strides(*shape, dt.itemsize());
577 
578  auto ndim = shape->size();
579  if (ndim != strides->size())
580  pybind11_fail("NumPy: shape ndim doesn't match strides ndim");
581  auto descr = dt;
582 
583  int flags = 0;
584  if (base && ptr) {
585  if (isinstance<array>(base))
586  /* Copy flags from base (except ownership bit) */
587  flags = reinterpret_borrow<array>(base).flags() & ~detail::npy_api::NPY_ARRAY_OWNDATA_;
588  else
589  /* Writable by default, easy to downgrade later on if needed */
590  flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
591  }
592 
593  auto &api = detail::npy_api::get();
594  auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(
595  api.PyArray_Type_, descr.release().ptr(), (int) ndim,
596  // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
597  reinterpret_cast<Py_intptr_t*>(shape->data()),
598  reinterpret_cast<Py_intptr_t*>(strides->data()),
599  const_cast<void *>(ptr), flags, nullptr));
600  if (!tmp)
601  throw error_already_set();
602  if (ptr) {
603  if (base) {
604  api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());
605  } else {
606  tmp = reinterpret_steal<object>(api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
607  }
608  }
609  m_ptr = tmp.release().ptr();
610  }
611 
612  array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr = nullptr, handle base = handle())
613  : array(dt, std::move(shape), {}, ptr, base) { }
614 
616  array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())
617  : array(dt, {{count}}, ptr, base) { }
618 
619  template <typename T>
621  : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) { }
622 
623  template <typename T>
625  : array(std::move(shape), {}, ptr, base) { }
626 
627  template <typename T>
628  explicit array(ssize_t count, const T *ptr, handle base = handle()) : array({count}, {}, ptr, base) { }
629 
630  explicit array(const buffer_info &info, handle base = handle())
631  : array(pybind11::dtype(info), info.shape, info.strides, info.ptr, base) { }
632 
633  /// Array descriptor (dtype)
634  pybind11::dtype dtype() const {
635  return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);
636  }
637 
638  /// Total number of elements
639  ssize_t size() const {
640  return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
641  }
642 
643  /// Byte size of a single element
644  ssize_t itemsize() const {
646  }
647 
648  /// Total number of bytes
649  ssize_t nbytes() const {
650  return size() * itemsize();
651  }
652 
653  /// Number of dimensions
654  ssize_t ndim() const {
655  return detail::array_proxy(m_ptr)->nd;
656  }
657 
658  /// Base object
659  object base() const {
660  return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base);
661  }
662 
663  /// Dimensions of the array
664  const ssize_t* shape() const {
666  }
667 
668  /// Dimension along a given axis
669  ssize_t shape(ssize_t dim) const {
670  if (dim >= ndim())
671  fail_dim_check(dim, "invalid axis");
672  return shape()[dim];
673  }
674 
675  /// Strides of the array
676  const ssize_t* strides() const {
678  }
679 
680  /// Stride along a given axis
681  ssize_t strides(ssize_t dim) const {
682  if (dim >= ndim())
683  fail_dim_check(dim, "invalid axis");
684  return strides()[dim];
685  }
686 
687  /// Return the NumPy array flags
688  int flags() const {
690  }
691 
692  /// If set, the array is writeable (otherwise the buffer is read-only)
693  bool writeable() const {
694  return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);
695  }
696 
697  /// If set, the array owns the data (will be freed when the array is deleted)
698  bool owndata() const {
699  return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);
700  }
701 
702  /// Pointer to the contained data. If index is not provided, points to the
703  /// beginning of the buffer. May throw if the index would lead to out of bounds access.
704  template<typename... Ix> const void* data(Ix... index) const {
705  return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
706  }
707 
708  /// Mutable pointer to the contained data. If index is not provided, points to the
709  /// beginning of the buffer. May throw if the index would lead to out of bounds access.
710  /// May throw if the array is not writeable.
711  template<typename... Ix> void* mutable_data(Ix... index) {
712  check_writeable();
713  return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
714  }
715 
716  /// Byte offset from beginning of the array to a given index (full or partial).
717  /// May throw if the index would lead to out of bounds access.
718  template<typename... Ix> ssize_t offset_at(Ix... index) const {
719  if ((ssize_t) sizeof...(index) > ndim())
720  fail_dim_check(sizeof...(index), "too many indices for an array");
721  return byte_offset(ssize_t(index)...);
722  }
723 
724  ssize_t offset_at() const { return 0; }
725 
726  /// Item count from beginning of the array to a given index (full or partial).
727  /// May throw if the index would lead to out of bounds access.
728  template<typename... Ix> ssize_t index_at(Ix... index) const {
729  return offset_at(index...) / itemsize();
730  }
731 
732  /**
733  * Returns a proxy object that provides access to the array's data without bounds or
734  * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
735  * care: the array must not be destroyed or reshaped for the duration of the returned object,
736  * and the caller must take care not to access invalid dimensions or dimension indices.
737  */
738  template <typename T, ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
739  if (Dims >= 0 && ndim() != Dims)
740  throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
741  "; expected " + std::to_string(Dims));
742  return detail::unchecked_mutable_reference<T, Dims>(mutable_data(), shape(), strides(), ndim());
743  }
744 
745  /**
746  * Returns a proxy object that provides const access to the array's data without bounds or
747  * dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the
748  * underlying array have the `writable` flag. Use with care: the array must not be destroyed or
749  * reshaped for the duration of the returned object, and the caller must take care not to access
750  * invalid dimensions or dimension indices.
751  */
752  template <typename T, ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
753  if (Dims >= 0 && ndim() != Dims)
754  throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
755  "; expected " + std::to_string(Dims));
756  return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
757  }
758 
759  /// Return a new view with all of the dimensions of length 1 removed
761  auto& api = detail::npy_api::get();
762  return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
763  }
764 
765  /// Resize array to given shape
766  /// If refcheck is true and more that one reference exist to this array
767  /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change
768  void resize(ShapeContainer new_shape, bool refcheck = true) {
769  detail::npy_api::PyArray_Dims d = {
770  // Use reinterpret_cast for PyPy on Windows (remove if fixed, checked on 7.3.1)
771  reinterpret_cast<Py_intptr_t*>(new_shape->data()),
772  int(new_shape->size())
773  };
774  // try to resize, set ordering param to -1 cause it's not used anyway
775  auto new_array = reinterpret_steal<object>(
776  detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1)
777  );
778  if (!new_array) throw error_already_set();
779  if (isinstance<array>(new_array)) { *this = std::move(new_array); }
780  }
781 
782  /// Ensure that the argument is a NumPy array
783  /// In case of an error, nullptr is returned and the Python error is cleared.
784  static array ensure(handle h, int ExtraFlags = 0) {
785  auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
786  if (!result)
787  PyErr_Clear();
788  return result;
789  }
790 
791 protected:
792  template<typename, typename> friend struct detail::npy_format_descriptor;
793 
794  void fail_dim_check(ssize_t dim, const std::string& msg) const {
795  throw index_error(msg + ": " + std::to_string(dim) +
796  " (ndim = " + std::to_string(ndim()) + ")");
797  }
798 
799  template<typename... Ix> ssize_t byte_offset(Ix... index) const {
800  check_dimensions(index...);
801  return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
802  }
803 
804  void check_writeable() const {
805  if (!writeable())
806  throw std::domain_error("array is not writeable");
807  }
808 
809  template<typename... Ix> void check_dimensions(Ix... index) const {
810  check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
811  }
812 
813  void check_dimensions_impl(ssize_t, const ssize_t*) const { }
814 
815  template<typename... Ix> void check_dimensions_impl(ssize_t axis, const ssize_t* shape, ssize_t i, Ix... index) const {
816  if (i >= *shape) {
817  throw index_error(std::string("index ") + std::to_string(i) +
818  " is out of bounds for axis " + std::to_string(axis) +
819  " with size " + std::to_string(*shape));
820  }
821  check_dimensions_impl(axis + 1, shape + 1, index...);
822  }
823 
824  /// Create array from any object -- always returns a new reference
825  static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {
826  if (ptr == nullptr) {
827  PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array from a nullptr");
828  return nullptr;
829  }
830  return detail::npy_api::get().PyArray_FromAny_(
831  ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
832  }
833 };
834 
835 template <typename T, int ExtraFlags = array::forcecast> class array_t : public array {
836 private:
837  struct private_ctor {};
838  // Delegating constructor needed when both moving and accessing in the same constructor
839  array_t(private_ctor, ShapeContainer &&shape, StridesContainer &&strides, const T *ptr, handle base)
841 public:
842  static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
843 
844  using value_type = T;
845 
846  array_t() : array(0, static_cast<const T *>(nullptr)) {}
849 
850  PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
852  if (!m_ptr) PyErr_Clear();
853  if (!is_borrowed) Py_XDECREF(h.ptr());
854  }
855 
856  array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
857  if (!m_ptr) throw error_already_set();
858  }
859 
860  explicit array_t(const buffer_info& info, handle base = handle()) : array(info, base) { }
861 
863  : array(std::move(shape), std::move(strides), ptr, base) { }
864 
865  explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
866  : array_t(private_ctor{}, std::move(shape),
867  ExtraFlags & f_style
869  : detail::c_strides(*shape, itemsize()),
870  ptr, base) { }
871 
872  explicit array_t(ssize_t count, const T *ptr = nullptr, handle base = handle())
873  : array({count}, {}, ptr, base) { }
874 
875  constexpr ssize_t itemsize() const {
876  return sizeof(T);
877  }
878 
879  template<typename... Ix> ssize_t index_at(Ix... index) const {
880  return offset_at(index...) / itemsize();
881  }
882 
883  template<typename... Ix> const T* data(Ix... index) const {
884  return static_cast<const T*>(array::data(index...));
885  }
886 
887  template<typename... Ix> T* mutable_data(Ix... index) {
888  return static_cast<T*>(array::mutable_data(index...));
889  }
890 
891  // Reference to element at a given index
892  template<typename... Ix> const T& at(Ix... index) const {
893  if ((ssize_t) sizeof...(index) != ndim())
894  fail_dim_check(sizeof...(index), "index dimension mismatch");
895  return *(static_cast<const T*>(array::data()) + byte_offset(ssize_t(index)...) / itemsize());
896  }
897 
898  // Mutable reference to element at a given index
899  template<typename... Ix> T& mutable_at(Ix... index) {
900  if ((ssize_t) sizeof...(index) != ndim())
901  fail_dim_check(sizeof...(index), "index dimension mismatch");
902  return *(static_cast<T*>(array::mutable_data()) + byte_offset(ssize_t(index)...) / itemsize());
903  }
904 
905  /**
906  * Returns a proxy object that provides access to the array's data without bounds or
907  * dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
908  * care: the array must not be destroyed or reshaped for the duration of the returned object,
909  * and the caller must take care not to access invalid dimensions or dimension indices.
910  */
911  template <ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
912  return array::mutable_unchecked<T, Dims>();
913  }
914 
915  /**
916  * Returns a proxy object that provides const access to the array's data without bounds or
917  * dimensionality checking. Unlike `unchecked()`, this does not require that the underlying
918  * array have the `writable` flag. Use with care: the array must not be destroyed or reshaped
919  * for the duration of the returned object, and the caller must take care not to access invalid
920  * dimensions or dimension indices.
921  */
922  template <ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
923  return array::unchecked<T, Dims>();
924  }
925 
926  /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert
927  /// it). In case of an error, nullptr is returned and the Python error is cleared.
928  static array_t ensure(handle h) {
929  auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
930  if (!result)
931  PyErr_Clear();
932  return result;
933  }
934 
935  static bool check_(handle h) {
936  const auto &api = detail::npy_api::get();
937  return api.PyArray_Check_(h.ptr())
938  && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr, dtype::of<T>().ptr())
939  && detail::check_flags(h.ptr(), ExtraFlags & (array::c_style | array::f_style));
940  }
941 
942 protected:
943  /// Create array from any object -- always returns a new reference
944  static PyObject *raw_array_t(PyObject *ptr) {
945  if (ptr == nullptr) {
946  PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
947  return nullptr;
948  }
949  return detail::npy_api::get().PyArray_FromAny_(
950  ptr, dtype::of<T>().release().ptr(), 0, 0,
951  detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
952  }
953 };
954 
955 template <typename T>
956 struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
957  static std::string format() {
958  return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format();
959  }
960 };
961 
962 template <size_t N> struct format_descriptor<char[N]> {
963  static std::string format() { return std::to_string(N) + "s"; }
964 };
965 template <size_t N> struct format_descriptor<std::array<char, N>> {
966  static std::string format() { return std::to_string(N) + "s"; }
967 };
968 
969 template <typename T>
970 struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {
971  static std::string format() {
972  return format_descriptor<
973  typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format();
974  }
975 };
976 
977 template <typename T>
978 struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
979  static std::string format() {
980  using namespace detail;
981  static constexpr auto extents = _("(") + array_info<T>::extents + _(")");
982  return extents.text + format_descriptor<remove_all_extents_t<T>>::format();
983  }
984 };
985 
987 template <typename T, int ExtraFlags>
988 struct pyobject_caster<array_t<T, ExtraFlags>> {
990 
991  bool load(handle src, bool convert) {
992  if (!convert && !type::check_(src))
993  return false;
994  value = type::ensure(src);
995  return static_cast<bool>(value);
996  }
997 
998  static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
999  return src.inc_ref();
1000  }
1002 };
1003 
1004 template <typename T>
1005 struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
1006  static bool compare(const buffer_info& b) {
1007  return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
1008  }
1009 };
1010 
1011 template <typename T, typename = void>
1013 
1014 template <typename T>
1015 struct npy_format_descriptor_name<T, enable_if_t<std::is_integral<T>::value>> {
1016  static constexpr auto name = _<std::is_same<T, bool>::value>(
1017  _("bool"), _<std::is_signed<T>::value>("numpy.int", "numpy.uint") + _<sizeof(T)*8>()
1018  );
1019 };
1020 
1021 template <typename T>
1022 struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {
1024  _("numpy.float") + _<sizeof(T)*8>(), _("numpy.longdouble")
1025  );
1026 };
1027 
1028 template <typename T>
1032  _("numpy.complex") + _<sizeof(typename T::value_type)*16>(), _("numpy.longcomplex")
1033  );
1034 };
1035 
1036 template <typename T>
1039 private:
1040  // NB: the order here must match the one in common.h
1041  constexpr static const int values[15] = {
1047  };
1048 
1049 public:
1050  static constexpr int value = values[detail::is_fmt_numeric<T>::index];
1051 
1052  static pybind11::dtype dtype() {
1053  if (auto ptr = npy_api::get().PyArray_DescrFromType_(value))
1054  return reinterpret_steal<pybind11::dtype>(ptr);
1055  pybind11_fail("Unsupported buffer format!");
1056  }
1057 };
1058 
1059 #define PYBIND11_DECL_CHAR_FMT \
1060  static constexpr auto name = _("S") + _<N>(); \
1061  static pybind11::dtype dtype() { return pybind11::dtype(std::string("S") + std::to_string(N)); }
1062 template <size_t N> struct npy_format_descriptor<char[N]> { PYBIND11_DECL_CHAR_FMT };
1063 template <size_t N> struct npy_format_descriptor<std::array<char, N>> { PYBIND11_DECL_CHAR_FMT };
1064 #undef PYBIND11_DECL_CHAR_FMT
1065 
1066 template<typename T> struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {
1067 private:
1069 public:
1070  static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
1071 
1072  static constexpr auto name = _("(") + array_info<T>::extents + _(")") + base_descr::name;
1073  static pybind11::dtype dtype() {
1074  list shape;
1076  return pybind11::dtype::from_args(pybind11::make_tuple(base_descr::dtype(), shape));
1077  }
1078 };
1079 
1080 template<typename T> struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {
1081 private:
1083 public:
1084  static constexpr auto name = base_descr::name;
1085  static pybind11::dtype dtype() { return base_descr::dtype(); }
1086 };
1087 
1089  const char *name;
1092  std::string format;
1094 };
1095 
1098  const std::type_info& tinfo, ssize_t itemsize,
1099  bool (*direct_converter)(PyObject *, void *&)) {
1100 
1102  if (numpy_internals.get_type_info(tinfo, false))
1103  pybind11_fail("NumPy: dtype is already registered");
1104 
1105  // Use ordered fields because order matters as of NumPy 1.14:
1106  // https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays
1107  std::vector<field_descriptor> ordered_fields(std::move(fields));
1108  std::sort(ordered_fields.begin(), ordered_fields.end(),
1109  [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
1110 
1111  list names, formats, offsets;
1112  for (auto& field : ordered_fields) {
1113  if (!field.descr)
1114  pybind11_fail(std::string("NumPy: unsupported field dtype: `") +
1115  field.name + "` @ " + tinfo.name());
1116  names.append(PYBIND11_STR_TYPE(field.name));
1117  formats.append(field.descr);
1118  offsets.append(pybind11::int_(field.offset));
1119  }
1120  auto dtype_ptr = pybind11::dtype(names, formats, offsets, itemsize).release().ptr();
1121 
1122  // There is an existing bug in NumPy (as of v1.11): trailing bytes are
1123  // not encoded explicitly into the format string. This will supposedly
1124  // get fixed in v1.12; for further details, see these:
1125  // - https://github.com/numpy/numpy/issues/7797
1126  // - https://github.com/numpy/numpy/pull/7798
1127  // Because of this, we won't use numpy's logic to generate buffer format
1128  // strings and will just do it ourselves.
1129  ssize_t offset = 0;
1130  std::ostringstream oss;
1131  // mark the structure as unaligned with '^', because numpy and C++ don't
1132  // always agree about alignment (particularly for complex), and we're
1133  // explicitly listing all our padding. This depends on none of the fields
1134  // overriding the endianness. Putting the ^ in front of individual fields
1135  // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
1136  oss << "^T{";
1137  for (auto& field : ordered_fields) {
1138  if (field.offset > offset)
1139  oss << (field.offset - offset) << 'x';
1140  oss << field.format << ':' << field.name << ':';
1141  offset = field.offset + field.size;
1142  }
1143  if (itemsize > offset)
1144  oss << (itemsize - offset) << 'x';
1145  oss << '}';
1146  auto format_str = oss.str();
1147 
1148  // Sanity check: verify that NumPy properly parses our buffer format string
1149  auto& api = npy_api::get();
1150  auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));
1151  if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr()))
1152  pybind11_fail("NumPy: invalid buffer descriptor!");
1153 
1154  auto tindex = std::type_index(tinfo);
1155  numpy_internals.registered_dtypes[tindex] = { dtype_ptr, format_str };
1156  get_internals().direct_conversions[tindex].push_back(direct_converter);
1157 }
1158 
1159 template <typename T, typename SFINAE> struct npy_format_descriptor {
1160  static_assert(is_pod_struct<T>::value, "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1161 
1162  static constexpr auto name = make_caster<T>::name;
1163 
1164  static pybind11::dtype dtype() {
1165  return reinterpret_borrow<pybind11::dtype>(dtype_ptr());
1166  }
1167 
1168  static std::string format() {
1169  static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
1170  return format_str;
1171  }
1172 
1174  register_structured_dtype(std::move(fields), typeid(typename std::remove_cv<T>::type),
1175  sizeof(T), &direct_converter);
1176  }
1177 
1178 private:
1179  static PyObject* dtype_ptr() {
1180  static PyObject* ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
1181  return ptr;
1182  }
1183 
1184  static bool direct_converter(PyObject *obj, void*& value) {
1185  auto& api = npy_api::get();
1186  if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_))
1187  return false;
1188  if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
1189  if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
1190  value = ((PyVoidScalarObject_Proxy *) obj)->obval;
1191  return true;
1192  }
1193  }
1194  return false;
1195  }
1196 };
1197 
1198 #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1199 # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void)0)
1200 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void)0)
1201 #else
1202 
1203 #define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
1204  ::pybind11::detail::field_descriptor { \
1205  Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
1206  ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
1207  ::pybind11::detail::npy_format_descriptor<decltype(std::declval<T>().Field)>::dtype() \
1208  }
1209 
1210 // Extract name, offset and format descriptor for a struct field
1211 #define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
1213 // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
1214 // (C) William Swanson, Paul Fultz
1215 #define PYBIND11_EVAL0(...) __VA_ARGS__
1216 #define PYBIND11_EVAL1(...) PYBIND11_EVAL0 (PYBIND11_EVAL0 (PYBIND11_EVAL0 (__VA_ARGS__)))
1217 #define PYBIND11_EVAL2(...) PYBIND11_EVAL1 (PYBIND11_EVAL1 (PYBIND11_EVAL1 (__VA_ARGS__)))
1218 #define PYBIND11_EVAL3(...) PYBIND11_EVAL2 (PYBIND11_EVAL2 (PYBIND11_EVAL2 (__VA_ARGS__)))
1219 #define PYBIND11_EVAL4(...) PYBIND11_EVAL3 (PYBIND11_EVAL3 (PYBIND11_EVAL3 (__VA_ARGS__)))
1220 #define PYBIND11_EVAL(...) PYBIND11_EVAL4 (PYBIND11_EVAL4 (PYBIND11_EVAL4 (__VA_ARGS__)))
1221 #define PYBIND11_MAP_END(...)
1222 #define PYBIND11_MAP_OUT
1223 #define PYBIND11_MAP_COMMA ,
1224 #define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1225 #define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1226 #define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0 (test, next, 0)
1227 #define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1 (PYBIND11_MAP_GET_END test, next)
1228 #if defined(_MSC_VER) && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
1229 #define PYBIND11_MAP_LIST_NEXT1(test, next) \
1230  PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
1231 #else
1232 #define PYBIND11_MAP_LIST_NEXT1(test, next) \
1233  PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
1234 #endif
1235 #define PYBIND11_MAP_LIST_NEXT(test, next) \
1236  PYBIND11_MAP_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
1237 #define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1238  f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST1) (f, t, peek, __VA_ARGS__)
1239 #define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1240  f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST0) (f, t, peek, __VA_ARGS__)
1241 // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
1242 #define PYBIND11_MAP_LIST(f, t, ...) \
1243  PYBIND11_EVAL (PYBIND11_MAP_LIST1 (f, t, __VA_ARGS__, (), 0))
1244 
1245 #define PYBIND11_NUMPY_DTYPE(Type, ...) \
1246  ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
1247  (::std::vector<::pybind11::detail::field_descriptor> \
1248  {PYBIND11_MAP_LIST (PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1249 
1250 #if defined(_MSC_VER) && !defined(__clang__)
1251 #define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1252  PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
1253 #else
1254 #define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1255  PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
1256 #endif
1257 #define PYBIND11_MAP2_LIST_NEXT(test, next) \
1258  PYBIND11_MAP2_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
1259 #define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1260  f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST1) (f, t, peek, __VA_ARGS__)
1261 #define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1262  f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST0) (f, t, peek, __VA_ARGS__)
1263 // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
1264 #define PYBIND11_MAP2_LIST(f, t, ...) \
1265  PYBIND11_EVAL (PYBIND11_MAP2_LIST1 (f, t, __VA_ARGS__, (), 0))
1266 
1267 #define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1268  ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
1269  (::std::vector<::pybind11::detail::field_descriptor> \
1270  {PYBIND11_MAP2_LIST (PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1271 
1272 #endif // __CLION_IDE__
1273 
1275 public:
1276  using container_type = std::vector<ssize_t>;
1277  using value_type = container_type::value_type;
1278  using size_type = container_type::size_type;
1279 
1280  common_iterator() : p_ptr(0), m_strides() {}
1281 
1282  common_iterator(void* ptr, const container_type& strides, const container_type& shape)
1283  : p_ptr(reinterpret_cast<char*>(ptr)), m_strides(strides.size()) {
1284  m_strides.back() = static_cast<value_type>(strides.back());
1285  for (size_type i = m_strides.size() - 1; i != 0; --i) {
1286  size_type j = i - 1;
1287  auto s = static_cast<value_type>(shape[i]);
1288  m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
1289  }
1290  }
1291 
1292  void increment(size_type dim) {
1293  p_ptr += m_strides[dim];
1294  }
1295 
1296  void* data() const {
1297  return p_ptr;
1298  }
1299 
1300 private:
1301  char* p_ptr;
1302  container_type m_strides;
1303 };
1304 
1305 template <size_t N> class multi_array_iterator {
1306 public:
1307  using container_type = std::vector<ssize_t>;
1308 
1309  multi_array_iterator(const std::array<buffer_info, N> &buffers,
1310  const container_type &shape)
1311  : m_shape(shape.size()), m_index(shape.size(), 0),
1312  m_common_iterator() {
1313 
1314  // Manual copy to avoid conversion warning if using std::copy
1315  for (size_t i = 0; i < shape.size(); ++i)
1316  m_shape[i] = shape[i];
1317 
1318  container_type strides(shape.size());
1319  for (size_t i = 0; i < N; ++i)
1320  init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
1321  }
1322 
1324  for (size_t j = m_index.size(); j != 0; --j) {
1325  size_t i = j - 1;
1326  if (++m_index[i] != m_shape[i]) {
1327  increment_common_iterator(i);
1328  break;
1329  } else {
1330  m_index[i] = 0;
1331  }
1332  }
1333  return *this;
1334  }
1335 
1336  template <size_t K, class T = void> T* data() const {
1337  return reinterpret_cast<T*>(m_common_iterator[K].data());
1338  }
1339 
1340 private:
1341 
1342  using common_iter = common_iterator;
1343 
1344  void init_common_iterator(const buffer_info &buffer,
1345  const container_type &shape,
1346  common_iter &iterator,
1347  container_type &strides) {
1348  auto buffer_shape_iter = buffer.shape.rbegin();
1349  auto buffer_strides_iter = buffer.strides.rbegin();
1350  auto shape_iter = shape.rbegin();
1351  auto strides_iter = strides.rbegin();
1352 
1353  while (buffer_shape_iter != buffer.shape.rend()) {
1354  if (*shape_iter == *buffer_shape_iter)
1355  *strides_iter = *buffer_strides_iter;
1356  else
1357  *strides_iter = 0;
1358 
1359  ++buffer_shape_iter;
1360  ++buffer_strides_iter;
1361  ++shape_iter;
1362  ++strides_iter;
1363  }
1364 
1365  std::fill(strides_iter, strides.rend(), 0);
1366  iterator = common_iter(buffer.ptr, strides, shape);
1367  }
1368 
1369  void increment_common_iterator(size_t dim) {
1370  for (auto &iter : m_common_iterator)
1371  iter.increment(dim);
1372  }
1373 
1374  container_type m_shape;
1375  container_type m_index;
1376  std::array<common_iter, N> m_common_iterator;
1377 };
1378 
1379 enum class broadcast_trivial { non_trivial, c_trivial, f_trivial };
1380 
1381 // Populates the shape and number of dimensions for the set of buffers. Returns a broadcast_trivial
1382 // enum value indicating whether the broadcast is "trivial"--that is, has each buffer being either a
1383 // singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous (`f_trivial`) storage
1384 // buffer; returns `non_trivial` otherwise.
1385 template <size_t N>
1386 broadcast_trivial broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
1387  ndim = std::accumulate(buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
1388  return std::max(res, buf.ndim);
1389  });
1390 
1391  shape.clear();
1392  shape.resize((size_t) ndim, 1);
1393 
1394  // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1 or
1395  // the full size).
1396  for (size_t i = 0; i < N; ++i) {
1397  auto res_iter = shape.rbegin();
1398  auto end = buffers[i].shape.rend();
1399  for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end; ++shape_iter, ++res_iter) {
1400  const auto &dim_size_in = *shape_iter;
1401  auto &dim_size_out = *res_iter;
1402 
1403  // Each input dimension can either be 1 or `n`, but `n` values must match across buffers
1404  if (dim_size_out == 1)
1405  dim_size_out = dim_size_in;
1406  else if (dim_size_in != 1 && dim_size_in != dim_size_out)
1407  pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
1408  }
1409  }
1410 
1411  bool trivial_broadcast_c = true;
1412  bool trivial_broadcast_f = true;
1413  for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
1414  if (buffers[i].size == 1)
1415  continue;
1416 
1417  // Require the same number of dimensions:
1418  if (buffers[i].ndim != ndim)
1419  return broadcast_trivial::non_trivial;
1420 
1421  // Require all dimensions be full-size:
1422  if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin()))
1423  return broadcast_trivial::non_trivial;
1424 
1425  // Check for C contiguity (but only if previous inputs were also C contiguous)
1426  if (trivial_broadcast_c) {
1427  ssize_t expect_stride = buffers[i].itemsize;
1428  auto end = buffers[i].shape.crend();
1429  for (auto shape_iter = buffers[i].shape.crbegin(), stride_iter = buffers[i].strides.crbegin();
1430  trivial_broadcast_c && shape_iter != end; ++shape_iter, ++stride_iter) {
1431  if (expect_stride == *stride_iter)
1432  expect_stride *= *shape_iter;
1433  else
1434  trivial_broadcast_c = false;
1435  }
1436  }
1437 
1438  // Check for Fortran contiguity (if previous inputs were also F contiguous)
1439  if (trivial_broadcast_f) {
1440  ssize_t expect_stride = buffers[i].itemsize;
1441  auto end = buffers[i].shape.cend();
1442  for (auto shape_iter = buffers[i].shape.cbegin(), stride_iter = buffers[i].strides.cbegin();
1443  trivial_broadcast_f && shape_iter != end; ++shape_iter, ++stride_iter) {
1444  if (expect_stride == *stride_iter)
1445  expect_stride *= *shape_iter;
1446  else
1447  trivial_broadcast_f = false;
1448  }
1449  }
1450  }
1451 
1452  return
1453  trivial_broadcast_c ? broadcast_trivial::c_trivial :
1454  trivial_broadcast_f ? broadcast_trivial::f_trivial :
1455  broadcast_trivial::non_trivial;
1456 }
1457 
1458 template <typename T>
1460  static_assert(!std::is_rvalue_reference<T>::value, "Functions with rvalue reference arguments cannot be vectorized");
1461  // The wrapped function gets called with this type:
1463  // Is this a vectorized argument?
1464  static constexpr bool vectorize =
1469  // Accept this type: an array for vectorized types, otherwise the type as-is:
1471 };
1472 
1473 
1474 // py::vectorize when a return type is present
1475 template <typename Func, typename Return, typename... Args>
1478 
1479  static Type create(broadcast_trivial trivial, const std::vector<ssize_t> &shape) {
1480  if (trivial == broadcast_trivial::f_trivial)
1481  return array_t<Return, array::f_style>(shape);
1482  else
1483  return array_t<Return>(shape);
1484  }
1485 
1486  static Return *mutable_data(Type &array) {
1487  return array.mutable_data();
1488  }
1489 
1490  static Return call(Func &f, Args &... args) {
1491  return f(args...);
1492  }
1493 
1494  static void call(Return *out, size_t i, Func &f, Args &... args) {
1495  out[i] = f(args...);
1496  }
1497 };
1498 
1499 // py::vectorize when a return type is not present
1500 template <typename Func, typename... Args>
1501 struct vectorize_returned_array<Func, void, Args...> {
1502  using Type = none;
1503 
1504  static Type create(broadcast_trivial, const std::vector<ssize_t> &) {
1505  return none();
1506  }
1507 
1508  static void *mutable_data(Type &) {
1509  return nullptr;
1510  }
1511 
1512  static detail::void_type call(Func &f, Args &... args) {
1513  f(args...);
1514  return {};
1515  }
1516 
1517  static void call(void *, size_t, Func &f, Args &... args) {
1518  f(args...);
1519  }
1520 };
1521 
1522 
1523 template <typename Func, typename Return, typename... Args>
1525 
1526 // NVCC for some reason breaks if NVectorized is private
1527 #ifdef __CUDACC__
1528 public:
1529 #else
1530 private:
1531 #endif
1532 
1533  static constexpr size_t N = sizeof...(Args);
1534  static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
1535  static_assert(NVectorized >= 1,
1536  "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
1537 
1538 public:
1539  template <typename T>
1540  explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) { }
1541 
1543  return run(args...,
1547  }
1548 
1549 private:
1551 
1552  // Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling with "/permissive-" flag
1553  // when arg_call_types is manually inlined.
1554  using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;
1555  template <size_t Index> using param_n_t = typename std::tuple_element<Index, arg_call_types>::type;
1556 
1557  using returned_array = vectorize_returned_array<Func, Return, Args...>;
1558 
1559  // Runs a vectorized function given arguments tuple and three index sequences:
1560  // - Index is the full set of 0 ... (N-1) argument indices;
1561  // - VIndex is the subset of argument indices with vectorized parameters, letting us access
1562  // vectorized arguments (anything not in this sequence is passed through)
1563  // - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
1564  // we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
1565  // index BIndex in the array).
1566  template <size_t... Index, size_t... VIndex, size_t... BIndex> object run(
1567  typename vectorize_arg<Args>::type &...args,
1569 
1570  // Pointers to values the function was called with; the vectorized ones set here will start
1571  // out as array_t<T> pointers, but they will be changed them to T pointers before we make
1572  // call the wrapped function. Non-vectorized pointers are left as-is.
1573  std::array<void *, N> params{{ &args... }};
1574 
1575  // The array of `buffer_info`s of vectorized arguments:
1576  std::array<buffer_info, NVectorized> buffers{{ reinterpret_cast<array *>(params[VIndex])->request()... }};
1577 
1578  /* Determine dimensions parameters of output array */
1579  ssize_t nd = 0;
1580  std::vector<ssize_t> shape(0);
1581  auto trivial = broadcast(buffers, nd, shape);
1582  auto ndim = (size_t) nd;
1583 
1584  size_t size = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
1585 
1586  // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
1587  // not wrapped in an array).
1588  if (size == 1 && ndim == 0) {
1589  PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
1590  return cast(returned_array::call(f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...));
1591  }
1592 
1593  auto result = returned_array::create(trivial, shape);
1594 
1595  if (size == 0) return std::move(result);
1596 
1597  /* Call the function */
1598  auto mutable_data = returned_array::mutable_data(result);
1599  if (trivial == broadcast_trivial::non_trivial)
1600  apply_broadcast(buffers, params, mutable_data, size, shape, i_seq, vi_seq, bi_seq);
1601  else
1602  apply_trivial(buffers, params, mutable_data, size, i_seq, vi_seq, bi_seq);
1603 
1604  return std::move(result);
1605  }
1606 
1607  template <size_t... Index, size_t... VIndex, size_t... BIndex>
1608  void apply_trivial(std::array<buffer_info, NVectorized> &buffers,
1609  std::array<void *, N> &params,
1610  Return *out,
1611  size_t size,
1613 
1614  // Initialize an array of mutable byte references and sizes with references set to the
1615  // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
1616  // (except for singletons, which get an increment of 0).
1617  std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{{
1618  std::pair<unsigned char *&, const size_t>(
1619  reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
1620  buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>)
1621  )...
1622  }};
1623 
1624  for (size_t i = 0; i < size; ++i) {
1625  returned_array::call(out, i, f, *reinterpret_cast<param_n_t<Index> *>(params[Index])...);
1626  for (auto &x : vecparams) x.first += x.second;
1627  }
1628  }
1629 
1630  template <size_t... Index, size_t... VIndex, size_t... BIndex>
1631  void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
1632  std::array<void *, N> &params,
1633  Return *out,
1634  size_t size,
1635  const std::vector<ssize_t> &output_shape,
1637 
1638  multi_array_iterator<NVectorized> input_iter(buffers, output_shape);
1639 
1640  for (size_t i = 0; i < size; ++i, ++input_iter) {
1642  params[VIndex] = input_iter.template data<BIndex>()
1643  ));
1644  returned_array::call(out, i, f, *reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
1645  }
1646  }
1647 };
1648 
1649 template <typename Func, typename Return, typename... Args>
1650 vectorize_helper<Func, Return, Args...>
1651 vectorize_extractor(const Func &f, Return (*) (Args ...)) {
1652  return detail::vectorize_helper<Func, Return, Args...>(f);
1653 }
1654 
1655 template <typename T, int Flags> struct handle_type_name<array_t<T, Flags>> {
1656  static constexpr auto name = _("numpy.ndarray[") + npy_format_descriptor<T>::name + _("]");
1657 };
1658 
1659 PYBIND11_NAMESPACE_END(detail)
1660 
1661 // Vanilla pointer vectorizer:
1662 template <typename Return, typename... Args>
1663 detail::vectorize_helper<Return (*)(Args...), Return, Args...>
1664 vectorize(Return (*f) (Args ...)) {
1665  return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
1666 }
1667 
1668 // lambda vectorizer:
1670 auto vectorize(Func &&f) -> decltype(
1671  detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr)) {
1672  return detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr);
1673 }
1674 
1675 // Vectorize a class method (non-const):
1676 template <typename Return, typename Class, typename... Args,
1677  typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())), Return, Class *, Args...>>
1678 Helper vectorize(Return (Class::*f)(Args...)) {
1679  return Helper(std::mem_fn(f));
1680 }
1681 
1682 // Vectorize a class method (const):
1683 template <typename Return, typename Class, typename... Args,
1684  typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())), Return, const Class *, Args...>>
1685 Helper vectorize(Return (Class::*f)(Args...) const) {
1686  return Helper(std::mem_fn(f));
1687 }
1688 
1690 
1691 #if defined(_MSC_VER)
1692 #pragma warning(pop)
1693 #endif
array_t::itemsize
constexpr ssize_t itemsize() const
Definition: numpy.h:875
module_::import
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Definition: pybind11.h:991
npy_api::NPY_ARRAY_WRITEABLE_
@ NPY_ARRAY_WRITEABLE_
Definition: numpy.h:138
enable_if_t
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: common.h:504
PyArrayDescr_Proxy::typeobj
PyObject_HEAD PyObject * typeobj
Definition: numpy.h:53
npy_api::NPY_DOUBLE_
@ NPY_DOUBLE_
Definition: numpy.h:145
test_multiple_inheritance.i
i
Definition: test_multiple_inheritance.py:22
format_descriptor
Definition: common.h:754
vectorize_helper
Definition: numpy.h:1524
array_t::ensure
static array_t ensure(handle h)
Definition: numpy.h:928
pyobject_caster< array_t< T, ExtraFlags > >::cast
static handle cast(const handle &src, return_value_policy, handle)
Definition: numpy.h:998
array::strides
ssize_t strides(ssize_t dim) const
Stride along a given axis.
Definition: numpy.h:681
npy_format_descriptor
Definition: numpy.h:1159
name
Annotation for function names.
Definition: attr.h:36
cast
T cast(const handle &handle)
Definition: cast.h:1769
array::fail_dim_check
void fail_dim_check(ssize_t dim, const std::string &msg) const
Definition: numpy.h:794
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:16
unchecked_reference::shape_
conditional_t< Dynamic, const ssize_t *, std::array< ssize_t,(size_t) Dims > > shape_
Definition: numpy.h:359
is_std_array
Definition: numpy.h:281
base
Annotation indicating that a class derives from another given type.
Definition: attr.h:42
npy_api::NPY_INT16_
@ NPY_INT16_
Definition: numpy.h:152
array::unchecked
detail::unchecked_reference< T, Dims > unchecked() const &
Definition: numpy.h:752
npy_api::NPY_CDOUBLE_
@ NPY_CDOUBLE_
Definition: numpy.h:146
npy_api::NPY_UINT32_
@ NPY_UINT32_
Definition: numpy.h:159
npy_api::NPY_INT8_
@ NPY_INT8_
Definition: numpy.h:150
npy_api::PyArray_Check_
bool PyArray_Check_(PyObject *obj) const
Definition: numpy.h:177
test_builtin_casters.x
x
Definition: test_builtin_casters.py:467
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:17
index_sequence
Index sequences.
Definition: common.h:515
npy_api::NPY_BOOL_
@ NPY_BOOL_
Definition: numpy.h:139
vectorize_arg
Definition: numpy.h:1459
array::check_dimensions
void check_dimensions(Ix... index) const
Definition: numpy.h:809
array::array
array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base=handle())
Definition: numpy.h:620
error_already_set
Definition: pytypes.h:326
object::stolen_t
Definition: pytypes.h:280
array::mutable_data
void * mutable_data(Ix... index)
Definition: numpy.h:711
numpy_type_info::format_str
std::string format_str
Definition: numpy.h:87
PYBIND11_NAMESPACE
#define PYBIND11_NAMESPACE
Definition: common.h:26
vectorize_returned_array::call
static void call(Return *out, size_t i, Func &f, Args &... args)
Definition: numpy.h:1494
broadcast_trivial
broadcast_trivial
Definition: numpy.h:1379
array::npy_format_descriptor
friend struct detail::npy_format_descriptor
Definition: numpy.h:792
PYBIND11_STR_TYPE
#define PYBIND11_STR_TYPE
Definition: common.h:230
array::shape
ssize_t shape(ssize_t dim) const
Dimension along a given axis.
Definition: numpy.h:669
array::ShapeContainer
detail::any_container< ssize_t > ShapeContainer
Definition: numpy.h:568
list
Definition: pytypes.h:1345
npy_api
Definition: numpy.h:130
npy_api::NPY_STRING_
@ NPY_STRING_
Definition: numpy.h:148
field_descriptor::offset
ssize_t offset
Definition: numpy.h:1090
npy_api::NPY_INT_
@ NPY_INT_
Definition: numpy.h:142
array_t::mutable_data
T * mutable_data(Ix... index)
Definition: numpy.h:887
array::array
array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides, const void *ptr=nullptr, handle base=handle())
Definition: numpy.h:572
f_strides
std::vector< ssize_t > f_strides(const std::vector< ssize_t > &shape, ssize_t itemsize)
Definition: buffer_info.h:29
PYBIND11_OBJECT_CVT
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:812
unchecked_reference
Definition: numpy.h:352
numpy_internals
Definition: numpy.h:90
npy_api::PyArray_Type_
PyTypeObject * PyArray_Type_
Definition: numpy.h:193
array_t::array_t
array_t(handle h, stolen_t)
Definition: numpy.h:848
array_t::data
const T * data(Ix... index) const
Definition: numpy.h:883
common_iterator::value_type
container_type::value_type value_type
Definition: numpy.h:1277
array::ndim
ssize_t ndim() const
Number of dimensions.
Definition: numpy.h:654
handle::inc_ref
const handle & inc_ref() const &
Definition: pytypes.h:192
array::itemsize
ssize_t itemsize() const
Byte size of a single element.
Definition: numpy.h:644
npy_api::NPY_BYTE_
@ NPY_BYTE_
Definition: numpy.h:140
array_t::array_t
array_t()
Definition: numpy.h:846
npy_api::NPY_LONG_
@ NPY_LONG_
Definition: numpy.h:143
npy_api::PyArrayDescr_Check_
bool PyArrayDescr_Check_(PyObject *obj) const
Definition: numpy.h:180
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:1006
PYBIND11_NOINLINE
#define PYBIND11_NOINLINE
Definition: common.h:88
vectorize
detail::vectorize_helper< Return(*)(Args...), Return, Args... > vectorize(Return(*f)(Args ...))
Definition: numpy.h:1664
vectorize_returned_array::mutable_data
static Return * mutable_data(Type &array)
Definition: numpy.h:1486
bool_constant
std::integral_constant< bool, B > bool_constant
Backports of std::bool_constant and std::negation to accommodate older compilers.
Definition: common.h:528
PyArrayDescr_Proxy::subarray
char * subarray
Definition: numpy.h:61
dtype::has_fields
bool has_fields() const
Returns true for structured data types.
Definition: numpy.h:506
unchecked_reference::data_
const unsigned char * data_
Definition: numpy.h:355
broadcast_trivial::non_trivial
@ non_trivial
all_of
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
Definition: common.h:550
npy_api::PyArray_GetNDArrayCFeatureVersion_
unsigned int(* PyArray_GetNDArrayCFeatureVersion_)()
Definition: numpy.h:184
type
Definition: pytypes.h:915
npy_api::NPY_INT64_
@ NPY_INT64_
Definition: numpy.h:161
array::array
array()
Definition: numpy.h:566
_
constexpr descr< N - 1 > _(char const(&text)[N])
Definition: descr.h:54
npy_api::NPY_ARRAY_F_CONTIGUOUS_
@ NPY_ARRAY_F_CONTIGUOUS_
Definition: numpy.h:133
handle::m_ptr
PyObject * m_ptr
Definition: pytypes.h:219
npy_api::PyArray_DescrConverter_
int(* PyArray_DescrConverter_)(PyObject *, PyObject **)
Definition: numpy.h:198
PyArrayDescr_Proxy::fields
PyObject * fields
Definition: numpy.h:62
broadcast
broadcast_trivial broadcast(const std::array< buffer_info, N > &buffers, ssize_t &ndim, std::vector< ssize_t > &shape)
Definition: numpy.h:1386
PyArray_Proxy
Definition: numpy.h:66
buffer
Definition: pytypes.h:1403
array_info_scalar
Definition: numpy.h:286
constexpr_sum
constexpr size_t constexpr_sum()
Compile-time integer sum.
Definition: common.h:589
get_internals
PYBIND11_NOINLINE internals & get_internals()
Return a reference to the current internals data.
Definition: internals.h:256
npy_api::NPY_ULONGLONG_
@ NPY_ULONGLONG_
Definition: numpy.h:144
npy_api::NPY_ARRAY_ENSUREARRAY_
@ NPY_ARRAY_ENSUREARRAY_
Definition: numpy.h:136
iterator
Definition: pytypes.h:854
npy_api::NPY_ARRAY_C_CONTIGUOUS_
@ NPY_ARRAY_C_CONTIGUOUS_
Definition: numpy.h:132
byte_offset_unsafe
ssize_t byte_offset_unsafe(const Strides &)
Definition: numpy.h:340
array_t::check_
static bool check_(handle h)
Definition: numpy.h:935
array_t::array_t
array_t(ssize_t count, const T *ptr=nullptr, handle base=handle())
Definition: numpy.h:872
unchecked_mutable_reference::mutable_data
T * mutable_data(Ix... ix)
Mutable pointer access to the data at the given indices.
Definition: numpy.h:450
array_info_scalar::is_array
static constexpr bool is_array
Definition: numpy.h:288
same_size
Definition: numpy.h:118
is_complex
Definition: numpy.h:283
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:664
vectorize_extractor
vectorize_helper< Func, Return, Args... > vectorize_extractor(const Func &f, Return(*)(Args ...))
Definition: numpy.h:1651
unchecked_reference::strides_
conditional_t< Dynamic, const ssize_t *, std::array< ssize_t,(size_t) Dims > > strides_
Definition: numpy.h:359
PyVoidScalarObject_Proxy::descr
PyArrayDescr_Proxy * descr
Definition: numpy.h:80
conditional_t
typename std::conditional< B, T, F >::type conditional_t
Definition: common.h:505
npy_api::NPY_ARRAY_ALIGNED_
@ NPY_ARRAY_ALIGNED_
Definition: numpy.h:137
npy_api::NPY_ARRAY_FORCECAST_
@ NPY_ARRAY_FORCECAST_
Definition: numpy.h:135
array_info< std::array< T, N > >::append_extents
static void append_extents(list &shape)
Definition: numpy.h:304
remove_reference_t
typename std::remove_reference< T >::type remove_reference_t
Definition: common.h:507
unchecked_mutable_reference
Definition: numpy.h:425
PyArray_Proxy::descr
PyObject * descr
Definition: numpy.h:73
dtype::PYBIND11_OBJECT_DEFAULT
PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_)
unchecked_reference::Dynamic
static constexpr bool Dynamic
Definition: numpy.h:354
npy_format_descriptor::format
static std::string format()
Definition: numpy.h:1168
npy_api::PyArray_Dims
Definition: numpy.h:167
array::offset_at
ssize_t offset_at() const
Definition: numpy.h:724
field_descriptor::name
const char * name
Definition: numpy.h:1089
vectorize_returned_array
Definition: numpy.h:1476
any_container
Definition: common.h:842
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:332
array_t
Definition: numpy.h:835
npy_api::PyArrayDescr_Type_
PyTypeObject * PyArrayDescr_Type_
Definition: numpy.h:195
npy_api::NPY_UINT8_
@ NPY_UINT8_
Definition: numpy.h:151
complex.h
multi_array_iterator::data
T * data() const
Definition: numpy.h:1336
vectorize_arg::type
conditional_t< vectorize, array_t< remove_cv_t< call_type >, array::forcecast >, T > type
Definition: numpy.h:1470
dict
Definition: pytypes.h:1299
dtype
Definition: numpy.h:462
array::owndata
bool owndata() const
If set, the array owns the data (will be freed when the array is deleted)
Definition: numpy.h:698
array_t::array_t
array_t(const object &o)
Definition: numpy.h:856
array_t::array_t
array_t(ShapeContainer shape, const T *ptr=nullptr, handle base=handle())
Definition: numpy.h:865
array::array
array(const buffer_info &info, handle base=handle())
Definition: numpy.h:630
array_info_scalar< std::array< char, N > >::type
std::array< char, N > type
Definition: numpy.h:287
array::StridesContainer
detail::any_container< ssize_t > StridesContainer
Definition: numpy.h:569
handle
Definition: pytypes.h:176
type_caster
Definition: cast.h:954
vectorize_arg::call_type
remove_reference_t< T > call_type
Definition: numpy.h:1462
npy_api::PyArray_Dims::len
int len
Definition: numpy.h:169
buffer_info::format
std::string format
Definition: buffer_info.h:44
npy_api::NPY_LONGLONG_
@ NPY_LONGLONG_
Definition: numpy.h:144
PyVoidScalarObject_Proxy::base
PyObject * base
Definition: numpy.h:82
make_tuple
tuple make_tuple()
Definition: cast.h:1866
array_t< Scalar, array::forcecast|((props::row_major ? props::inner_stride :props::outer_stride)==1 ? array::c_style :(props::row_major ? props::outer_stride :props::inner_stride)==1 ? array::f_style :0)>::value_type
Scalar value_type
Definition: numpy.h:844
npy_api::PyArray_SetBaseObject_
int(* PyArray_SetBaseObject_)(PyObject *, PyObject *)
Definition: numpy.h:204
get_numpy_internals
numpy_internals & get_numpy_internals()
Definition: numpy.h:111
vectorize_returned_array< Func, void, Args... >::mutable_data
static void * mutable_data(Type &)
Definition: numpy.h:1508
field_descriptor::descr
dtype descr
Definition: numpy.h:1093
PyArrayDescr_Proxy::elsize
int elsize
Definition: numpy.h:59
object::release
handle release()
Definition: pytypes.h:249
array_info_scalar::extents
static constexpr auto extents
Definition: numpy.h:290
PyArrayDescr_Proxy::kind
char kind
Definition: numpy.h:54
unchecked_reference::array
friend class pybind11::array
Definition: numpy.h:362
multi_array_iterator
Definition: numpy.h:1305
buffer_info::itemsize
ssize_t itemsize
Definition: buffer_info.h:42
multi_array_iterator::container_type
std::vector< ssize_t > container_type
Definition: numpy.h:1307
vectorize_returned_array::call
static Return call(Func &f, Args &... args)
Definition: numpy.h:1490
numpy_internals::registered_dtypes
std::unordered_map< std::type_index, numpy_type_info > registered_dtypes
Definition: numpy.h:91
array::nbytes
ssize_t nbytes() const
Total number of bytes.
Definition: numpy.h:649
array::forcecast
@ forcecast
Definition: numpy.h:563
common_iterator
Definition: numpy.h:1274
unchecked_mutable_reference::array
friend class pybind11::array
Definition: numpy.h:426
numpy_internals::get_type_info
numpy_type_info * get_type_info(bool throw_if_missing=true)
Definition: numpy.h:102
select_indices
typename select_indices_impl< index_sequence<>, 0, Bs... >::type select_indices
Definition: common.h:525
array::c_style
@ c_style
Definition: numpy.h:561
npy_api::NPY_UINT_
@ NPY_UINT_
Definition: numpy.h:142
negation
Definition: common.h:529
remove_all_extents_t
typename array_info< T >::type remove_all_extents_t
Definition: numpy.h:318
PyArrayDescr_Proxy
Definition: numpy.h:51
npy_api::PyArray_EquivTypes_
bool(* PyArray_EquivTypes_)(PyObject *, PyObject *)
Definition: numpy.h:199
npy_api::PyArray_Dims::ptr
Py_intptr_t * ptr
Definition: numpy.h:168
buffer_info::ndim
ssize_t ndim
Definition: buffer_info.h:45
array::array
array(ShapeContainer shape, const T *ptr, handle base=handle())
Definition: numpy.h:624
object::borrowed_t
Definition: pytypes.h:279
common_iterator::common_iterator
common_iterator()
Definition: numpy.h:1280
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:374
ssize_t
Py_ssize_t ssize_t
Definition: common.h:353
PyArrayDescr_Proxy::alignment
int alignment
Definition: numpy.h:60
npy_api::NPY_UBYTE_
@ NPY_UBYTE_
Definition: numpy.h:140
array_t::mutable_unchecked
detail::unchecked_mutable_reference< T, Dims > mutable_unchecked() &
Definition: numpy.h:911
npy_api::NPY_USHORT_
@ NPY_USHORT_
Definition: numpy.h:141
array_info_scalar::append_extents
static void append_extents(list &)
Definition: numpy.h:291
concat
constexpr descr< 0 > concat()
Definition: descr.h:83
unchecked_mutable_reference::operator()
T & operator()(Ix... index)
Mutable, unchecked access to data at the given indices.
Definition: numpy.h:436
pyobject_caster
Definition: cast.h:1660
unchecked_reference::shape
ssize_t shape(ssize_t dim) const
Returns the shape (i.e. size) of dimension dim
Definition: numpy.h:402
vectorize_returned_array::create
static Type create(broadcast_trivial trivial, const std::vector< ssize_t > &shape)
Definition: numpy.h:1479
vectorize_helper::vectorize_helper
vectorize_helper(T &&f)
Definition: numpy.h:1540
PyVoidScalarObject_Proxy::obval
PyObject_VAR_HEAD char * obval
Definition: numpy.h:79
npy_format_descriptor< T, enable_if_t< array_info< T >::is_array > >::dtype
static pybind11::dtype dtype()
Definition: numpy.h:1073
common_iterator::common_iterator
common_iterator(void *ptr, const container_type &strides, const container_type &shape)
Definition: numpy.h:1282
PyArrayDescr_Proxy::type
char type
Definition: numpy.h:55
size_t
std::size_t size_t
Definition: common.h:354
unchecked_reference::nbytes
ssize_t nbytes() const
Definition: numpy.h:419
npy_api::NPY_UINT16_
@ NPY_UINT16_
Definition: numpy.h:153
dtype::dtype
dtype(const std::string &format)
Definition: numpy.h:472
PYBIND11_EXPAND_SIDE_EFFECTS
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
Definition: common.h:721
PyArray_Proxy::base
PyObject * base
Definition: numpy.h:72
array_t::at
const T & at(Ix... index) const
Definition: numpy.h:892
multi_array_iterator::operator++
multi_array_iterator & operator++()
Definition: numpy.h:1323
check_flags
bool check_flags(const void *ptr, int flag)
Definition: numpy.h:277
vectorize_returned_array< Func, void, Args... >::create
static Type create(broadcast_trivial, const std::vector< ssize_t > &)
Definition: numpy.h:1504
unchecked_reference::ndim
ssize_t ndim() const
Returns the number of dimensions of the array.
Definition: numpy.h:405
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: common.h:751
npy_api::PyArray_CopyInto_
int(* PyArray_CopyInto_)(PyObject *, PyObject *)
Definition: numpy.h:191
common_iterator::size_type
container_type::size_type size_type
Definition: numpy.h:1278
npy_format_descriptor::register_dtype
static void register_dtype(any_container< field_descriptor > fields)
Definition: numpy.h:1173
numpy_type_info
Definition: numpy.h:85
array::size
ssize_t size() const
Total number of elements.
Definition: numpy.h:639
array::mutable_unchecked
detail::unchecked_mutable_reference< T, Dims > mutable_unchecked() &
Definition: numpy.h:738
field_descriptor::size
ssize_t size
Definition: numpy.h:1091
array::check_dimensions_impl
void check_dimensions_impl(ssize_t, const ssize_t *) const
Definition: numpy.h:813
dtype::of
static dtype of()
Return dtype associated with a C++ type.
Definition: numpy.h:496
array::check_writeable
void check_writeable() const
Definition: numpy.h:804
array::array
array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr=nullptr, handle base=handle())
Definition: numpy.h:612
npy_api::NPY_ULONG_
@ NPY_ULONG_
Definition: numpy.h:143
npy_api::NPY_CFLOAT_
@ NPY_CFLOAT_
Definition: numpy.h:146
unchecked_mutable_reference::operator[]
T & operator[](ssize_t index)
Definition: numpy.h:447
unchecked_reference::itemsize
constexpr static ssize_t itemsize()
Returns the item size, i.e. sizeof(T)
Definition: numpy.h:399
pybind11.h
array::array
array(const pybind11::dtype &dt, T count, const void *ptr=nullptr, handle base=handle())
Definition: numpy.h:616
numpy_internals::get_type_info
numpy_type_info * get_type_info(const std::type_info &tinfo, bool throw_if_missing=true)
Definition: numpy.h:93
format_descriptor< T, detail::enable_if_t< detail::array_info< T >::is_array > >::format
static std::string format()
Definition: numpy.h:979
npy_format_descriptor::dtype
static pybind11::dtype dtype()
Definition: numpy.h:1164
npy_api::NPY_OBJECT_
@ NPY_OBJECT_
Definition: numpy.h:147
platform_lookup
constexpr int platform_lookup()
Definition: numpy.h:122
array
Definition: numpy.h:556
field_descriptor
Definition: numpy.h:1088
PyArrayDescr_Proxy::flags
char flags
Definition: numpy.h:57
move
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
Definition: cast.h:1798
array::squeeze
array squeeze()
Return a new view with all of the dimensions of length 1 removed.
Definition: numpy.h:760
arr
py::array arr
Definition: test_numpy_array.cpp:78
list::append
void append(T &&val) const
Definition: pytypes.h:1357
npy_api::NPY_SHORT_
@ NPY_SHORT_
Definition: numpy.h:141
internals::direct_conversions
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
Definition: internals.h:101
npy_api::NPY_FLOAT_
@ NPY_FLOAT_
Definition: numpy.h:145
PyArrayDescr_Proxy::type_num
int type_num
Definition: numpy.h:58
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:1052
handle_type_name
Definition: cast.h:1650
handle::ptr
PyObject * ptr() const
Return the underlying PyObject * pointer.
Definition: pytypes.h:184
array::data
const void * data(Ix... index) const
Definition: numpy.h:704
multi_array_iterator::multi_array_iterator
multi_array_iterator(const std::array< buffer_info, N > &buffers, const container_type &shape)
Definition: numpy.h:1309
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:825
PyArray_Proxy::strides
ssize_t * strides
Definition: numpy.h:71
module_
Wrapper for Python extension modules.
Definition: pybind11.h:941
benchmark.size
size
Definition: benchmark.py:90
vectorize_returned_array< Func, void, Args... >::call
static detail::void_type call(Func &f, Args &... args)
Definition: numpy.h:1512
dtype::from_args
static dtype from_args(object args)
This is essentially the same as calling numpy.dtype(args) in Python.
Definition: numpy.h:488
array::dtype
pybind11::dtype dtype() const
Array descriptor (dtype)
Definition: numpy.h:634
npy_api::NPY_LONGDOUBLE_
@ NPY_LONGDOUBLE_
Definition: numpy.h:145
dtype::dtype
dtype(const buffer_info &info)
Definition: numpy.h:466
handle::handle
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
array_t::unchecked
detail::unchecked_reference< T, Dims > unchecked() const &
Definition: numpy.h:922
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:944
npy_api::PyArray_GetArrayParamsFromObject_
int(* PyArray_GetArrayParamsFromObject_)(PyObject *, PyObject *, unsigned char, PyObject **, int *, Py_intptr_t *, PyObject **, PyObject *)
Definition: numpy.h:200
make_index_sequence
typename make_index_sequence_impl< N >::type make_index_sequence
Definition: common.h:518
array::byte_offset
ssize_t byte_offset(Ix... index) const
Definition: numpy.h:799
PyArray_Proxy::nd
int nd
Definition: numpy.h:69
iter
iterator iter(handle obj)
Definition: pytypes.h:1595
DECL_NPY_API
#define DECL_NPY_API(Func)
array::ensure
static array ensure(handle h, int ExtraFlags=0)
Definition: numpy.h:784
args
Definition: pytypes.h:1366
npy_format_descriptor< T, enable_if_t< std::is_enum< T >::value > >::dtype
static pybind11::dtype dtype()
Definition: numpy.h:1085
array_t::array_t
array_t(ShapeContainer shape, StridesContainer strides, const T *ptr=nullptr, handle base=handle())
Definition: numpy.h:862
buffer_info
Information record describing a Python buffer object.
Definition: buffer_info.h:40
array_t::array_t
array_t(const buffer_info &info, handle base=handle())
Definition: numpy.h:860
npy_api::get
static npy_api & get()
Definition: numpy.h:172
return_value_policy
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
Definition: common.h:357
npy_api::NPY_UINT64_
@ NPY_UINT64_
Definition: numpy.h:163
npy_api::PyVoidArrType_Type_
PyTypeObject * PyVoidArrType_Type_
Definition: numpy.h:194
unchecked_reference::size
enable_if_t<!Dyn, ssize_t > size() const
Returns the total number of elements in the referenced array, i.e. the product of the shapes.
Definition: numpy.h:409
array_t::array_t
array_t(handle h, borrowed_t)
Definition: numpy.h:847
array::resize
void resize(ShapeContainer new_shape, bool refcheck=true)
Definition: numpy.h:768
PyArray_Proxy::flags
int flags
Definition: numpy.h:74
dtype::kind
char kind() const
Single-character type code.
Definition: numpy.h:511
tuple
Definition: pytypes.h:1276
make_changelog.api
api
Definition: make_changelog.py:28
array_info
Definition: numpy.h:296
field_descriptor::format
std::string format
Definition: numpy.h:1092
array_t::mutable_at
T & mutable_at(Ix... index)
Definition: numpy.h:899
unchecked_reference::data
const T * data(Ix... ix) const
Pointer access to the data at the given indices.
Definition: numpy.h:396
unchecked_reference::size
enable_if_t< Dyn, ssize_t > size() const
Definition: numpy.h:413
array_t::index_at
ssize_t index_at(Ix... index) const
Definition: numpy.h:879
numpy_type_info::dtype_ptr
PyObject * dtype_ptr
Definition: numpy.h:86
is_pod
all_of< std::is_standard_layout< T >, std::is_trivial< T > > is_pod
Definition: numpy.h:338
pybind11
Definition: __init__.py:1
array::base
object base() const
Base object.
Definition: numpy.h:659
npy_api::NPY_ARRAY_OWNDATA_
@ NPY_ARRAY_OWNDATA_
Definition: numpy.h:134
PYBIND11_DECL_CHAR_FMT
#define PYBIND11_DECL_CHAR_FMT
Definition: numpy.h:1059
unchecked_reference::dims_
const ssize_t dims_
Definition: numpy.h:360
script.end
end
Definition: script.py:188
PyVoidScalarObject_Proxy
Definition: numpy.h:77
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:1560
format_descriptor< std::array< char, N > >::format
static std::string format()
Definition: numpy.h:966
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:1096
unchecked_reference::operator[]
const T & operator[](ssize_t index) const
Definition: numpy.h:393
object::cast
T cast() const &
array_descriptor_proxy
PyArrayDescr_Proxy * array_descriptor_proxy(PyObject *ptr)
Definition: numpy.h:269
format_descriptor< T, detail::enable_if_t< detail::is_pod_struct< T >::value > >::format
static std::string format()
Definition: numpy.h:957
compare_buffer_info
Definition: buffer_info.h:131
PyArrayDescr_Proxy::names
PyObject * names
Definition: numpy.h:63
none
Definition: pytypes.h:1075
load_numpy_internals
PYBIND11_NOINLINE void load_numpy_internals(numpy_internals *&ptr)
Definition: numpy.h:107
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:365
npy_api::NPY_INT32_
@ NPY_INT32_
Definition: numpy.h:157
format_descriptor< T, detail::enable_if_t< std::is_enum< T >::value > >::format
static std::string format()
Definition: numpy.h:971
c_strides
std::vector< ssize_t > c_strides(const std::vector< ssize_t > &shape, ssize_t itemsize)
Definition: buffer_info.h:19
PyArray_Proxy::data
PyObject_HEAD char * data
Definition: numpy.h:68
PyVoidScalarObject_Proxy::flags
int flags
Definition: numpy.h:81
array_info_scalar::is_empty
static constexpr bool is_empty
Definition: numpy.h:289
npy_format_descriptor_name
Definition: numpy.h:1012
common_iterator::container_type
std::vector< ssize_t > container_type
Definition: numpy.h:1276
npy_api::constants
constants
Definition: numpy.h:131
PyArrayDescr_Proxy::byteorder
char byteorder
Definition: numpy.h:56
common_iterator::increment
void increment(size_type dim)
Definition: numpy.h:1292
test_async.m
m
Definition: test_async.py:5
vectorize_helper::operator()
object operator()(typename vectorize_arg< Args >::type... args)
Definition: numpy.h:1542
same_size::as
bool_constant< sizeof(T)==sizeof(U)> as
Definition: numpy.h:119
PyArray_Proxy::dimensions
ssize_t * dimensions
Definition: numpy.h:70
array::flags
int flags() const
Return the NumPy array flags.
Definition: numpy.h:688
array::f_style
@ f_style
Definition: numpy.h:562
test_callbacks.value
value
Definition: test_callbacks.py:126
array::writeable
bool writeable() const
If set, the array is writeable (otherwise the buffer is read-only)
Definition: numpy.h:693
object::is_borrowed
bool is_borrowed
Definition: pytypes.h:236
pyobject_caster< array_t< T, ExtraFlags > >::load
bool load(handle src, bool convert)
Definition: numpy.h:991
format_descriptor< char[N]>::format
static std::string format()
Definition: numpy.h:963
dtype::itemsize
ssize_t itemsize() const
Size of the data type in bytes.
Definition: numpy.h:501
common_iterator::data
void * data() const
Definition: numpy.h:1296
array_proxy
PyArray_Proxy * array_proxy(void *ptr)
Definition: numpy.h:261
array::offset_at
ssize_t offset_at(Ix... index) const
Definition: numpy.h:718
array::strides
const ssize_t * strides() const
Strides of the array.
Definition: numpy.h:676
unchecked_reference::operator()
const T & operator()(Ix... index) const
Definition: numpy.h:383
npy_api::NPY_CLONGDOUBLE_
@ NPY_CLONGDOUBLE_
Definition: numpy.h:146
npy_api::NPY_UNICODE_
@ NPY_UNICODE_
Definition: numpy.h:148
dtype::dtype
dtype(const char *format)
Definition: numpy.h:476
array::index_at
ssize_t index_at(Ix... index) const
Definition: numpy.h:728
array::check_dimensions_impl
void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const
Definition: numpy.h:815
array::array
array(ssize_t count, const T *ptr, handle base=handle())
Definition: numpy.h:628
vectorize_returned_array< Func, void, Args... >::call
static void call(void *, size_t, Func &f, Args &... args)
Definition: numpy.h:1517
dtype::dtype
dtype(list names, list formats, list offsets, ssize_t itemsize)
Definition: numpy.h:478
setup.msg
msg
Definition: setup.py:47
npy_api::NPY_VOID_
@ NPY_VOID_
Definition: numpy.h:148
pyobject_caster< array_t< T, ExtraFlags > >::PYBIND11_TYPE_CASTER
PYBIND11_TYPE_CASTER(type, handle_type_name< type >::name)