]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - tidl/tidl-api.git/blob - tidl_api/pybind11/include/pybind11/numpy.h
Merge branch 'hotfix/v01.05.01'
[tidl/tidl-api.git] / tidl_api / pybind11 / include / pybind11 / numpy.h
1 /*
2     pybind11/numpy.h: Basic NumPy support, vectorize() wrapper
4     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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 */
10 #pragma once
12 #include "pybind11.h"
13 #include "complex.h"
14 #include <numeric>
15 #include <algorithm>
16 #include <array>
17 #include <cstdlib>
18 #include <cstring>
19 #include <sstream>
20 #include <string>
21 #include <initializer_list>
22 #include <functional>
23 #include <utility>
24 #include <typeindex>
26 #if defined(_MSC_VER)
27 #  pragma warning(push)
28 #  pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
29 #endif
31 /* This will be true on all flat address space platforms and allows us to reduce the
32    whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size
33    and dimension types (e.g. shape, strides, indexing), instead of inflicting this
34    upon the library user. */
35 static_assert(sizeof(ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
37 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
39 class array; // Forward declaration
41 NAMESPACE_BEGIN(detail)
42 template <typename type, typename SFINAE = void> struct npy_format_descriptor;
44 struct PyArrayDescr_Proxy {
45     PyObject_HEAD
46     PyObject *typeobj;
47     char kind;
48     char type;
49     char byteorder;
50     char flags;
51     int type_num;
52     int elsize;
53     int alignment;
54     char *subarray;
55     PyObject *fields;
56     PyObject *names;
57 };
59 struct PyArray_Proxy {
60     PyObject_HEAD
61     char *data;
62     int nd;
63     ssize_t *dimensions;
64     ssize_t *strides;
65     PyObject *base;
66     PyObject *descr;
67     int flags;
68 };
70 struct PyVoidScalarObject_Proxy {
71     PyObject_VAR_HEAD
72     char *obval;
73     PyArrayDescr_Proxy *descr;
74     int flags;
75     PyObject *base;
76 };
78 struct numpy_type_info {
79     PyObject* dtype_ptr;
80     std::string format_str;
81 };
83 struct numpy_internals {
84     std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;
86     numpy_type_info *get_type_info(const std::type_info& tinfo, bool throw_if_missing = true) {
87         auto it = registered_dtypes.find(std::type_index(tinfo));
88         if (it != registered_dtypes.end())
89             return &(it->second);
90         if (throw_if_missing)
91             pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name());
92         return nullptr;
93     }
95     template<typename T> numpy_type_info *get_type_info(bool throw_if_missing = true) {
96         return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);
97     }
98 };
100 inline PYBIND11_NOINLINE void load_numpy_internals(numpy_internals* &ptr) {
101     ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals");
104 inline numpy_internals& get_numpy_internals() {
105     static numpy_internals* ptr = nullptr;
106     if (!ptr)
107         load_numpy_internals(ptr);
108     return *ptr;
111 struct npy_api {
112     enum constants {
113         NPY_ARRAY_C_CONTIGUOUS_ = 0x0001,
114         NPY_ARRAY_F_CONTIGUOUS_ = 0x0002,
115         NPY_ARRAY_OWNDATA_ = 0x0004,
116         NPY_ARRAY_FORCECAST_ = 0x0010,
117         NPY_ARRAY_ENSUREARRAY_ = 0x0040,
118         NPY_ARRAY_ALIGNED_ = 0x0100,
119         NPY_ARRAY_WRITEABLE_ = 0x0400,
120         NPY_BOOL_ = 0,
121         NPY_BYTE_, NPY_UBYTE_,
122         NPY_SHORT_, NPY_USHORT_,
123         NPY_INT_, NPY_UINT_,
124         NPY_LONG_, NPY_ULONG_,
125         NPY_LONGLONG_, NPY_ULONGLONG_,
126         NPY_FLOAT_, NPY_DOUBLE_, NPY_LONGDOUBLE_,
127         NPY_CFLOAT_, NPY_CDOUBLE_, NPY_CLONGDOUBLE_,
128         NPY_OBJECT_ = 17,
129         NPY_STRING_, NPY_UNICODE_, NPY_VOID_
130     };
132     typedef struct {
133         Py_intptr_t *ptr;
134         int len;
135     } PyArray_Dims;
137     static npy_api& get() {
138         static npy_api api = lookup();
139         return api;
140     }
142     bool PyArray_Check_(PyObject *obj) const {
143         return (bool) PyObject_TypeCheck(obj, PyArray_Type_);
144     }
145     bool PyArrayDescr_Check_(PyObject *obj) const {
146         return (bool) PyObject_TypeCheck(obj, PyArrayDescr_Type_);
147     }
149     unsigned int (*PyArray_GetNDArrayCFeatureVersion_)();
150     PyObject *(*PyArray_DescrFromType_)(int);
151     PyObject *(*PyArray_NewFromDescr_)
152         (PyTypeObject *, PyObject *, int, Py_intptr_t *,
153          Py_intptr_t *, void *, int, PyObject *);
154     PyObject *(*PyArray_DescrNewFromType_)(int);
155     int (*PyArray_CopyInto_)(PyObject *, PyObject *);
156     PyObject *(*PyArray_NewCopy_)(PyObject *, int);
157     PyTypeObject *PyArray_Type_;
158     PyTypeObject *PyVoidArrType_Type_;
159     PyTypeObject *PyArrayDescr_Type_;
160     PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
161     PyObject *(*PyArray_FromAny_) (PyObject *, PyObject *, int, int, int, PyObject *);
162     int (*PyArray_DescrConverter_) (PyObject *, PyObject **);
163     bool (*PyArray_EquivTypes_) (PyObject *, PyObject *);
164     int (*PyArray_GetArrayParamsFromObject_)(PyObject *, PyObject *, char, PyObject **, int *,
165                                              Py_ssize_t *, PyObject **, PyObject *);
166     PyObject *(*PyArray_Squeeze_)(PyObject *);
167     int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);
168     PyObject* (*PyArray_Resize_)(PyObject*, PyArray_Dims*, int, int);
169 private:
170     enum functions {
171         API_PyArray_GetNDArrayCFeatureVersion = 211,
172         API_PyArray_Type = 2,
173         API_PyArrayDescr_Type = 3,
174         API_PyVoidArrType_Type = 39,
175         API_PyArray_DescrFromType = 45,
176         API_PyArray_DescrFromScalar = 57,
177         API_PyArray_FromAny = 69,
178         API_PyArray_Resize = 80,
179         API_PyArray_CopyInto = 82,
180         API_PyArray_NewCopy = 85,
181         API_PyArray_NewFromDescr = 94,
182         API_PyArray_DescrNewFromType = 9,
183         API_PyArray_DescrConverter = 174,
184         API_PyArray_EquivTypes = 182,
185         API_PyArray_GetArrayParamsFromObject = 278,
186         API_PyArray_Squeeze = 136,
187         API_PyArray_SetBaseObject = 282
188     };
190     static npy_api lookup() {
191         module m = module::import("numpy.core.multiarray");
192         auto c = m.attr("_ARRAY_API");
193 #if PY_MAJOR_VERSION >= 3
194         void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), NULL);
195 #else
196         void **api_ptr = (void **) PyCObject_AsVoidPtr(c.ptr());
197 #endif
198         npy_api api;
199 #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
200         DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);
201         if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7)
202             pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0");
203         DECL_NPY_API(PyArray_Type);
204         DECL_NPY_API(PyVoidArrType_Type);
205         DECL_NPY_API(PyArrayDescr_Type);
206         DECL_NPY_API(PyArray_DescrFromType);
207         DECL_NPY_API(PyArray_DescrFromScalar);
208         DECL_NPY_API(PyArray_FromAny);
209         DECL_NPY_API(PyArray_Resize);
210         DECL_NPY_API(PyArray_CopyInto);
211         DECL_NPY_API(PyArray_NewCopy);
212         DECL_NPY_API(PyArray_NewFromDescr);
213         DECL_NPY_API(PyArray_DescrNewFromType);
214         DECL_NPY_API(PyArray_DescrConverter);
215         DECL_NPY_API(PyArray_EquivTypes);
216         DECL_NPY_API(PyArray_GetArrayParamsFromObject);
217         DECL_NPY_API(PyArray_Squeeze);
218         DECL_NPY_API(PyArray_SetBaseObject);
219 #undef DECL_NPY_API
220         return api;
221     }
222 };
224 inline PyArray_Proxy* array_proxy(void* ptr) {
225     return reinterpret_cast<PyArray_Proxy*>(ptr);
228 inline const PyArray_Proxy* array_proxy(const void* ptr) {
229     return reinterpret_cast<const PyArray_Proxy*>(ptr);
232 inline PyArrayDescr_Proxy* array_descriptor_proxy(PyObject* ptr) {
233    return reinterpret_cast<PyArrayDescr_Proxy*>(ptr);
236 inline const PyArrayDescr_Proxy* array_descriptor_proxy(const PyObject* ptr) {
237    return reinterpret_cast<const PyArrayDescr_Proxy*>(ptr);
240 inline bool check_flags(const void* ptr, int flag) {
241     return (flag == (array_proxy(ptr)->flags & flag));
244 template <typename T> struct is_std_array : std::false_type { };
245 template <typename T, size_t N> struct is_std_array<std::array<T, N>> : std::true_type { };
246 template <typename T> struct is_complex : std::false_type { };
247 template <typename T> struct is_complex<std::complex<T>> : std::true_type { };
249 template <typename T> struct array_info_scalar {
250     typedef T type;
251     static constexpr bool is_array = false;
252     static constexpr bool is_empty = false;
253     static PYBIND11_DESCR extents() { return _(""); }
254     static void append_extents(list& /* shape */) { }
255 };
256 // Computes underlying type and a comma-separated list of extents for array
257 // types (any mix of std::array and built-in arrays). An array of char is
258 // treated as scalar because it gets special handling.
259 template <typename T> struct array_info : array_info_scalar<T> { };
260 template <typename T, size_t N> struct array_info<std::array<T, N>> {
261     using type = typename array_info<T>::type;
262     static constexpr bool is_array = true;
263     static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;
264     static constexpr size_t extent = N;
266     // appends the extents to shape
267     static void append_extents(list& shape) {
268         shape.append(N);
269         array_info<T>::append_extents(shape);
270     }
272     template<typename T2 = T, enable_if_t<!array_info<T2>::is_array, int> = 0>
273     static PYBIND11_DESCR extents() {
274         return _<N>();
275     }
277     template<typename T2 = T, enable_if_t<array_info<T2>::is_array, int> = 0>
278     static PYBIND11_DESCR extents() {
279         return concat(_<N>(), array_info<T>::extents());
280     }
281 };
282 // For numpy we have special handling for arrays of characters, so we don't include
283 // the size in the array extents.
284 template <size_t N> struct array_info<char[N]> : array_info_scalar<char[N]> { };
285 template <size_t N> struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> { };
286 template <typename T, size_t N> struct array_info<T[N]> : array_info<std::array<T, N>> { };
287 template <typename T> using remove_all_extents_t = typename array_info<T>::type;
289 template <typename T> using is_pod_struct = all_of<
290     std::is_standard_layout<T>,     // since we're accessing directly in memory we need a standard layout type
291 #if !defined(__GNUG__) || defined(_LIBCPP_VERSION) || defined(_GLIBCXX_USE_CXX11_ABI)
292     // _GLIBCXX_USE_CXX11_ABI indicates that we're using libstdc++ from GCC 5 or newer, independent
293     // of the actual compiler (Clang can also use libstdc++, but it always defines __GNUC__ == 4).
294     std::is_trivially_copyable<T>,
295 #else
296     // GCC 4 doesn't implement is_trivially_copyable, so approximate it
297     std::is_trivially_destructible<T>,
298     satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>,
299 #endif
300     satisfies_none_of<T, std::is_reference, std::is_array, is_std_array, std::is_arithmetic, is_complex, std::is_enum>
301 >;
303 template <ssize_t Dim = 0, typename Strides> ssize_t byte_offset_unsafe(const Strides &) { return 0; }
304 template <ssize_t Dim = 0, typename Strides, typename... Ix>
305 ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {
306     return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);
309 /**
310  * Proxy class providing unsafe, unchecked const access to array data.  This is constructed through
311  * the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`.  `Dims`
312  * will be -1 for dimensions determined at runtime.
313  */
314 template <typename T, ssize_t Dims>
315 class unchecked_reference {
316 protected:
317     static constexpr bool Dynamic = Dims < 0;
318     const unsigned char *data_;
319     // Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
320     // make large performance gains on big, nested loops, but requires compile-time dimensions
321     conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>>
322             shape_, strides_;
323     const ssize_t dims_;
325     friend class pybind11::array;
326     // Constructor for compile-time dimensions:
327     template <bool Dyn = Dynamic>
328     unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<!Dyn, ssize_t>)
329     : data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
330         for (size_t i = 0; i < (size_t) dims_; i++) {
331             shape_[i] = shape[i];
332             strides_[i] = strides[i];
333         }
334     }
335     // Constructor for runtime dimensions:
336     template <bool Dyn = Dynamic>
337     unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<Dyn, ssize_t> dims)
338     : data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides}, dims_{dims} {}
340 public:
341     /**
342      * Unchecked const reference access to data at the given indices.  For a compile-time known
343      * number of dimensions, this requires the correct number of arguments; for run-time
344      * dimensionality, this is not checked (and so is up to the caller to use safely).
345      */
346     template <typename... Ix> const T &operator()(Ix... index) const {
347         static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
348                 "Invalid number of indices for unchecked array reference");
349         return *reinterpret_cast<const T *>(data_ + byte_offset_unsafe(strides_, ssize_t(index)...));
350     }
351     /**
352      * Unchecked const reference access to data; this operator only participates if the reference
353      * is to a 1-dimensional array.  When present, this is exactly equivalent to `obj(index)`.
354      */
355     template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
356     const T &operator[](ssize_t index) const { return operator()(index); }
358     /// Pointer access to the data at the given indices.
359     template <typename... Ix> const T *data(Ix... ix) const { return &operator()(ssize_t(ix)...); }
361     /// Returns the item size, i.e. sizeof(T)
362     constexpr static ssize_t itemsize() { return sizeof(T); }
364     /// Returns the shape (i.e. size) of dimension `dim`
365     ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; }
367     /// Returns the number of dimensions of the array
368     ssize_t ndim() const { return dims_; }
370     /// Returns the total number of elements in the referenced array, i.e. the product of the shapes
371     template <bool Dyn = Dynamic>
372     enable_if_t<!Dyn, ssize_t> size() const {
373         return std::accumulate(shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
374     }
375     template <bool Dyn = Dynamic>
376     enable_if_t<Dyn, ssize_t> size() const {
377         return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
378     }
380     /// Returns the total number of bytes used by the referenced data.  Note that the actual span in
381     /// memory may be larger if the referenced array has non-contiguous strides (e.g. for a slice).
382     ssize_t nbytes() const {
383         return size() * itemsize();
384     }
385 };
387 template <typename T, ssize_t Dims>
388 class unchecked_mutable_reference : public unchecked_reference<T, Dims> {
389     friend class pybind11::array;
390     using ConstBase = unchecked_reference<T, Dims>;
391     using ConstBase::ConstBase;
392     using ConstBase::Dynamic;
393 public:
394     /// Mutable, unchecked access to data at the given indices.
395     template <typename... Ix> T& operator()(Ix... index) {
396         static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
397                 "Invalid number of indices for unchecked array reference");
398         return const_cast<T &>(ConstBase::operator()(index...));
399     }
400     /**
401      * Mutable, unchecked access data at the given index; this operator only participates if the
402      * reference is to a 1-dimensional array (or has runtime dimensions).  When present, this is
403      * exactly equivalent to `obj(index)`.
404      */
405     template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
406     T &operator[](ssize_t index) { return operator()(index); }
408     /// Mutable pointer access to the data at the given indices.
409     template <typename... Ix> T *mutable_data(Ix... ix) { return &operator()(ssize_t(ix)...); }
410 };
412 template <typename T, ssize_t Dim>
413 struct type_caster<unchecked_reference<T, Dim>> {
414     static_assert(Dim == 0 && Dim > 0 /* always fail */, "unchecked array proxy object is not castable");
415 };
416 template <typename T, ssize_t Dim>
417 struct type_caster<unchecked_mutable_reference<T, Dim>> : type_caster<unchecked_reference<T, Dim>> {};
419 NAMESPACE_END(detail)
421 class dtype : public object {
422 public:
423     PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_);
425     explicit dtype(const buffer_info &info) {
426         dtype descr(_dtype_from_pep3118()(PYBIND11_STR_TYPE(info.format)));
427         // If info.itemsize == 0, use the value calculated from the format string
428         m_ptr = descr.strip_padding(info.itemsize ? info.itemsize : descr.itemsize()).release().ptr();
429     }
431     explicit dtype(const std::string &format) {
432         m_ptr = from_args(pybind11::str(format)).release().ptr();
433     }
435     dtype(const char *format) : dtype(std::string(format)) { }
437     dtype(list names, list formats, list offsets, ssize_t itemsize) {
438         dict args;
439         args["names"] = names;
440         args["formats"] = formats;
441         args["offsets"] = offsets;
442         args["itemsize"] = pybind11::int_(itemsize);
443         m_ptr = from_args(args).release().ptr();
444     }
446     /// This is essentially the same as calling numpy.dtype(args) in Python.
447     static dtype from_args(object args) {
448         PyObject *ptr = nullptr;
449         if (!detail::npy_api::get().PyArray_DescrConverter_(args.release().ptr(), &ptr) || !ptr)
450             throw error_already_set();
451         return reinterpret_steal<dtype>(ptr);
452     }
454     /// Return dtype associated with a C++ type.
455     template <typename T> static dtype of() {
456         return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();
457     }
459     /// Size of the data type in bytes.
460     ssize_t itemsize() const {
461         return detail::array_descriptor_proxy(m_ptr)->elsize;
462     }
464     /// Returns true for structured data types.
465     bool has_fields() const {
466         return detail::array_descriptor_proxy(m_ptr)->names != nullptr;
467     }
469     /// Single-character type code.
470     char kind() const {
471         return detail::array_descriptor_proxy(m_ptr)->kind;
472     }
474 private:
475     static object _dtype_from_pep3118() {
476         static PyObject *obj = module::import("numpy.core._internal")
477             .attr("_dtype_from_pep3118").cast<object>().release().ptr();
478         return reinterpret_borrow<object>(obj);
479     }
481     dtype strip_padding(ssize_t itemsize) {
482         // Recursively strip all void fields with empty names that are generated for
483         // padding fields (as of NumPy v1.11).
484         if (!has_fields())
485             return *this;
487         struct field_descr { PYBIND11_STR_TYPE name; object format; pybind11::int_ offset; };
488         std::vector<field_descr> field_descriptors;
490         for (auto field : attr("fields").attr("items")()) {
491             auto spec = field.cast<tuple>();
492             auto name = spec[0].cast<pybind11::str>();
493             auto format = spec[1].cast<tuple>()[0].cast<dtype>();
494             auto offset = spec[1].cast<tuple>()[1].cast<pybind11::int_>();
495             if (!len(name) && format.kind() == 'V')
496                 continue;
497             field_descriptors.push_back({(PYBIND11_STR_TYPE) name, format.strip_padding(format.itemsize()), offset});
498         }
500         std::sort(field_descriptors.begin(), field_descriptors.end(),
501                   [](const field_descr& a, const field_descr& b) {
502                       return a.offset.cast<int>() < b.offset.cast<int>();
503                   });
505         list names, formats, offsets;
506         for (auto& descr : field_descriptors) {
507             names.append(descr.name);
508             formats.append(descr.format);
509             offsets.append(descr.offset);
510         }
511         return dtype(names, formats, offsets, itemsize);
512     }
513 };
515 class array : public buffer {
516 public:
517     PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array)
519     enum {
520         c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,
521         f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,
522         forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_
523     };
525     array() : array({{0}}, static_cast<const double *>(nullptr)) {}
527     using ShapeContainer = detail::any_container<ssize_t>;
528     using StridesContainer = detail::any_container<ssize_t>;
530     // Constructs an array taking shape/strides from arbitrary container types
531     array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides,
532           const void *ptr = nullptr, handle base = handle()) {
534         if (strides->empty())
535             *strides = c_strides(*shape, dt.itemsize());
537         auto ndim = shape->size();
538         if (ndim != strides->size())
539             pybind11_fail("NumPy: shape ndim doesn't match strides ndim");
540         auto descr = dt;
542         int flags = 0;
543         if (base && ptr) {
544             if (isinstance<array>(base))
545                 /* Copy flags from base (except ownership bit) */
546                 flags = reinterpret_borrow<array>(base).flags() & ~detail::npy_api::NPY_ARRAY_OWNDATA_;
547             else
548                 /* Writable by default, easy to downgrade later on if needed */
549                 flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
550         }
552         auto &api = detail::npy_api::get();
553         auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(
554             api.PyArray_Type_, descr.release().ptr(), (int) ndim, shape->data(), strides->data(),
555             const_cast<void *>(ptr), flags, nullptr));
556         if (!tmp)
557             throw error_already_set();
558         if (ptr) {
559             if (base) {
560                 api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());
561             } else {
562                 tmp = reinterpret_steal<object>(api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
563             }
564         }
565         m_ptr = tmp.release().ptr();
566     }
568     array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr = nullptr, handle base = handle())
569         : array(dt, std::move(shape), {}, ptr, base) { }
571     template <typename T, typename = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>>
572     array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())
573         : array(dt, {{count}}, ptr, base) { }
575     template <typename T>
576     array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle())
577         : array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) { }
579     template <typename T>
580     array(ShapeContainer shape, const T *ptr, handle base = handle())
581         : array(std::move(shape), {}, ptr, base) { }
583     template <typename T>
584     explicit array(ssize_t count, const T *ptr, handle base = handle()) : array({count}, {}, ptr, base) { }
586     explicit array(const buffer_info &info)
587     : array(pybind11::dtype(info), info.shape, info.strides, info.ptr) { }
589     /// Array descriptor (dtype)
590     pybind11::dtype dtype() const {
591         return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);
592     }
594     /// Total number of elements
595     ssize_t size() const {
596         return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
597     }
599     /// Byte size of a single element
600     ssize_t itemsize() const {
601         return detail::array_descriptor_proxy(detail::array_proxy(m_ptr)->descr)->elsize;
602     }
604     /// Total number of bytes
605     ssize_t nbytes() const {
606         return size() * itemsize();
607     }
609     /// Number of dimensions
610     ssize_t ndim() const {
611         return detail::array_proxy(m_ptr)->nd;
612     }
614     /// Base object
615     object base() const {
616         return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base);
617     }
619     /// Dimensions of the array
620     const ssize_t* shape() const {
621         return detail::array_proxy(m_ptr)->dimensions;
622     }
624     /// Dimension along a given axis
625     ssize_t shape(ssize_t dim) const {
626         if (dim >= ndim())
627             fail_dim_check(dim, "invalid axis");
628         return shape()[dim];
629     }
631     /// Strides of the array
632     const ssize_t* strides() const {
633         return detail::array_proxy(m_ptr)->strides;
634     }
636     /// Stride along a given axis
637     ssize_t strides(ssize_t dim) const {
638         if (dim >= ndim())
639             fail_dim_check(dim, "invalid axis");
640         return strides()[dim];
641     }
643     /// Return the NumPy array flags
644     int flags() const {
645         return detail::array_proxy(m_ptr)->flags;
646     }
648     /// If set, the array is writeable (otherwise the buffer is read-only)
649     bool writeable() const {
650         return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);
651     }
653     /// If set, the array owns the data (will be freed when the array is deleted)
654     bool owndata() const {
655         return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);
656     }
658     /// Pointer to the contained data. If index is not provided, points to the
659     /// beginning of the buffer. May throw if the index would lead to out of bounds access.
660     template<typename... Ix> const void* data(Ix... index) const {
661         return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
662     }
664     /// Mutable pointer to the contained data. If index is not provided, points to the
665     /// beginning of the buffer. May throw if the index would lead to out of bounds access.
666     /// May throw if the array is not writeable.
667     template<typename... Ix> void* mutable_data(Ix... index) {
668         check_writeable();
669         return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
670     }
672     /// Byte offset from beginning of the array to a given index (full or partial).
673     /// May throw if the index would lead to out of bounds access.
674     template<typename... Ix> ssize_t offset_at(Ix... index) const {
675         if ((ssize_t) sizeof...(index) > ndim())
676             fail_dim_check(sizeof...(index), "too many indices for an array");
677         return byte_offset(ssize_t(index)...);
678     }
680     ssize_t offset_at() const { return 0; }
682     /// Item count from beginning of the array to a given index (full or partial).
683     /// May throw if the index would lead to out of bounds access.
684     template<typename... Ix> ssize_t index_at(Ix... index) const {
685         return offset_at(index...) / itemsize();
686     }
688     /**
689      * Returns a proxy object that provides access to the array's data without bounds or
690      * dimensionality checking.  Will throw if the array is missing the `writeable` flag.  Use with
691      * care: the array must not be destroyed or reshaped for the duration of the returned object,
692      * and the caller must take care not to access invalid dimensions or dimension indices.
693      */
694     template <typename T, ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
695         if (Dims >= 0 && ndim() != Dims)
696             throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
697                     "; expected " + std::to_string(Dims));
698         return detail::unchecked_mutable_reference<T, Dims>(mutable_data(), shape(), strides(), ndim());
699     }
701     /**
702      * Returns a proxy object that provides const access to the array's data without bounds or
703      * dimensionality checking.  Unlike `mutable_unchecked()`, this does not require that the
704      * underlying array have the `writable` flag.  Use with care: the array must not be destroyed or
705      * reshaped for the duration of the returned object, and the caller must take care not to access
706      * invalid dimensions or dimension indices.
707      */
708     template <typename T, ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
709         if (Dims >= 0 && ndim() != Dims)
710             throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
711                     "; expected " + std::to_string(Dims));
712         return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
713     }
715     /// Return a new view with all of the dimensions of length 1 removed
716     array squeeze() {
717         auto& api = detail::npy_api::get();
718         return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
719     }
721     /// Resize array to given shape
722     /// If refcheck is true and more that one reference exist to this array
723     /// then resize will succeed only if it makes a reshape, i.e. original size doesn't change
724     void resize(ShapeContainer new_shape, bool refcheck = true) {
725         detail::npy_api::PyArray_Dims d = {
726             new_shape->data(), int(new_shape->size())
727         };
728         // try to resize, set ordering param to -1 cause it's not used anyway
729         object new_array = reinterpret_steal<object>(
730             detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1)
731         );
732         if (!new_array) throw error_already_set();
733         if (isinstance<array>(new_array)) { *this = std::move(new_array); }
734     }
736     /// Ensure that the argument is a NumPy array
737     /// In case of an error, nullptr is returned and the Python error is cleared.
738     static array ensure(handle h, int ExtraFlags = 0) {
739         auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
740         if (!result)
741             PyErr_Clear();
742         return result;
743     }
745 protected:
746     template<typename, typename> friend struct detail::npy_format_descriptor;
748     void fail_dim_check(ssize_t dim, const std::string& msg) const {
749         throw index_error(msg + ": " + std::to_string(dim) +
750                           " (ndim = " + std::to_string(ndim()) + ")");
751     }
753     template<typename... Ix> ssize_t byte_offset(Ix... index) const {
754         check_dimensions(index...);
755         return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
756     }
758     void check_writeable() const {
759         if (!writeable())
760             throw std::domain_error("array is not writeable");
761     }
763     // Default, C-style strides
764     static std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
765         auto ndim = shape.size();
766         std::vector<ssize_t> strides(ndim, itemsize);
767         if (ndim > 0)
768             for (size_t i = ndim - 1; i > 0; --i)
769                 strides[i - 1] = strides[i] * shape[i];
770         return strides;
771     }
773     // F-style strides; default when constructing an array_t with `ExtraFlags & f_style`
774     static std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
775         auto ndim = shape.size();
776         std::vector<ssize_t> strides(ndim, itemsize);
777         for (size_t i = 1; i < ndim; ++i)
778             strides[i] = strides[i - 1] * shape[i - 1];
779         return strides;
780     }
782     template<typename... Ix> void check_dimensions(Ix... index) const {
783         check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
784     }
786     void check_dimensions_impl(ssize_t, const ssize_t*) const { }
788     template<typename... Ix> void check_dimensions_impl(ssize_t axis, const ssize_t* shape, ssize_t i, Ix... index) const {
789         if (i >= *shape) {
790             throw index_error(std::string("index ") + std::to_string(i) +
791                               " is out of bounds for axis " + std::to_string(axis) +
792                               " with size " + std::to_string(*shape));
793         }
794         check_dimensions_impl(axis + 1, shape + 1, index...);
795     }
797     /// Create array from any object -- always returns a new reference
798     static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {
799         if (ptr == nullptr) {
800             PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array from a nullptr");
801             return nullptr;
802         }
803         return detail::npy_api::get().PyArray_FromAny_(
804             ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
805     }
806 };
808 template <typename T, int ExtraFlags = array::forcecast> class array_t : public array {
809 private:
810     struct private_ctor {};
811     // Delegating constructor needed when both moving and accessing in the same constructor
812     array_t(private_ctor, ShapeContainer &&shape, StridesContainer &&strides, const T *ptr, handle base)
813         : array(std::move(shape), std::move(strides), ptr, base) {}
814 public:
815     static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
817     using value_type = T;
819     array_t() : array(0, static_cast<const T *>(nullptr)) {}
820     array_t(handle h, borrowed_t) : array(h, borrowed_t{}) { }
821     array_t(handle h, stolen_t) : array(h, stolen_t{}) { }
823     PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
824     array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) {
825         if (!m_ptr) PyErr_Clear();
826         if (!is_borrowed) Py_XDECREF(h.ptr());
827     }
829     array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
830         if (!m_ptr) throw error_already_set();
831     }
833     explicit array_t(const buffer_info& info) : array(info) { }
835     array_t(ShapeContainer shape, StridesContainer strides, const T *ptr = nullptr, handle base = handle())
836         : array(std::move(shape), std::move(strides), ptr, base) { }
838     explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
839         : array_t(private_ctor{}, std::move(shape),
840                 ExtraFlags & f_style ? f_strides(*shape, itemsize()) : c_strides(*shape, itemsize()),
841                 ptr, base) { }
843     explicit array_t(size_t count, const T *ptr = nullptr, handle base = handle())
844         : array({count}, {}, ptr, base) { }
846     constexpr ssize_t itemsize() const {
847         return sizeof(T);
848     }
850     template<typename... Ix> ssize_t index_at(Ix... index) const {
851         return offset_at(index...) / itemsize();
852     }
854     template<typename... Ix> const T* data(Ix... index) const {
855         return static_cast<const T*>(array::data(index...));
856     }
858     template<typename... Ix> T* mutable_data(Ix... index) {
859         return static_cast<T*>(array::mutable_data(index...));
860     }
862     // Reference to element at a given index
863     template<typename... Ix> const T& at(Ix... index) const {
864         if (sizeof...(index) != ndim())
865             fail_dim_check(sizeof...(index), "index dimension mismatch");
866         return *(static_cast<const T*>(array::data()) + byte_offset(ssize_t(index)...) / itemsize());
867     }
869     // Mutable reference to element at a given index
870     template<typename... Ix> T& mutable_at(Ix... index) {
871         if (sizeof...(index) != ndim())
872             fail_dim_check(sizeof...(index), "index dimension mismatch");
873         return *(static_cast<T*>(array::mutable_data()) + byte_offset(ssize_t(index)...) / itemsize());
874     }
876     /**
877      * Returns a proxy object that provides access to the array's data without bounds or
878      * dimensionality checking.  Will throw if the array is missing the `writeable` flag.  Use with
879      * care: the array must not be destroyed or reshaped for the duration of the returned object,
880      * and the caller must take care not to access invalid dimensions or dimension indices.
881      */
882     template <ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
883         return array::mutable_unchecked<T, Dims>();
884     }
886     /**
887      * Returns a proxy object that provides const access to the array's data without bounds or
888      * dimensionality checking.  Unlike `unchecked()`, this does not require that the underlying
889      * array have the `writable` flag.  Use with care: the array must not be destroyed or reshaped
890      * for the duration of the returned object, and the caller must take care not to access invalid
891      * dimensions or dimension indices.
892      */
893     template <ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
894         return array::unchecked<T, Dims>();
895     }
897     /// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert
898     /// it).  In case of an error, nullptr is returned and the Python error is cleared.
899     static array_t ensure(handle h) {
900         auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
901         if (!result)
902             PyErr_Clear();
903         return result;
904     }
906     static bool check_(handle h) {
907         const auto &api = detail::npy_api::get();
908         return api.PyArray_Check_(h.ptr())
909                && api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr, dtype::of<T>().ptr());
910     }
912 protected:
913     /// Create array from any object -- always returns a new reference
914     static PyObject *raw_array_t(PyObject *ptr) {
915         if (ptr == nullptr) {
916             PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
917             return nullptr;
918         }
919         return detail::npy_api::get().PyArray_FromAny_(
920             ptr, dtype::of<T>().release().ptr(), 0, 0,
921             detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
922     }
923 };
925 template <typename T>
926 struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
927     static std::string format() {
928         return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format();
929     }
930 };
932 template <size_t N> struct format_descriptor<char[N]> {
933     static std::string format() { return std::to_string(N) + "s"; }
934 };
935 template <size_t N> struct format_descriptor<std::array<char, N>> {
936     static std::string format() { return std::to_string(N) + "s"; }
937 };
939 template <typename T>
940 struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {
941     static std::string format() {
942         return format_descriptor<
943             typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format();
944     }
945 };
947 template <typename T>
948 struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
949     static std::string format() {
950         using namespace detail;
951         PYBIND11_DESCR extents = _("(") + array_info<T>::extents() + _(")");
952         return extents.text() + format_descriptor<remove_all_extents_t<T>>::format();
953     }
954 };
956 NAMESPACE_BEGIN(detail)
957 template <typename T, int ExtraFlags>
958 struct pyobject_caster<array_t<T, ExtraFlags>> {
959     using type = array_t<T, ExtraFlags>;
961     bool load(handle src, bool convert) {
962         if (!convert && !type::check_(src))
963             return false;
964         value = type::ensure(src);
965         return static_cast<bool>(value);
966     }
968     static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
969         return src.inc_ref();
970     }
971     PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name());
972 };
974 template <typename T>
975 struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
976     static bool compare(const buffer_info& b) {
977         return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
978     }
979 };
981 template <typename T> struct npy_format_descriptor<T, enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>> {
982 private:
983     // NB: the order here must match the one in common.h
984     constexpr static const int values[15] = {
985         npy_api::NPY_BOOL_,
986         npy_api::NPY_BYTE_,   npy_api::NPY_UBYTE_,   npy_api::NPY_SHORT_,    npy_api::NPY_USHORT_,
987         npy_api::NPY_INT_,    npy_api::NPY_UINT_,    npy_api::NPY_LONGLONG_, npy_api::NPY_ULONGLONG_,
988         npy_api::NPY_FLOAT_,  npy_api::NPY_DOUBLE_,  npy_api::NPY_LONGDOUBLE_,
989         npy_api::NPY_CFLOAT_, npy_api::NPY_CDOUBLE_, npy_api::NPY_CLONGDOUBLE_
990     };
992 public:
993     static constexpr int value = values[detail::is_fmt_numeric<T>::index];
995     static pybind11::dtype dtype() {
996         if (auto ptr = npy_api::get().PyArray_DescrFromType_(value))
997             return reinterpret_borrow<pybind11::dtype>(ptr);
998         pybind11_fail("Unsupported buffer format!");
999     }
1000     template <typename T2 = T, enable_if_t<std::is_integral<T2>::value, int> = 0>
1001     static PYBIND11_DESCR name() {
1002         return _<std::is_same<T, bool>::value>(_("bool"),
1003             _<std::is_signed<T>::value>("int", "uint") + _<sizeof(T)*8>());
1004     }
1005     template <typename T2 = T, enable_if_t<std::is_floating_point<T2>::value, int> = 0>
1006     static PYBIND11_DESCR name() {
1007         return _<std::is_same<T, float>::value || std::is_same<T, double>::value>(
1008                 _("float") + _<sizeof(T)*8>(), _("longdouble"));
1009     }
1010     template <typename T2 = T, enable_if_t<is_complex<T2>::value, int> = 0>
1011     static PYBIND11_DESCR name() {
1012         return _<std::is_same<typename T2::value_type, float>::value || std::is_same<typename T2::value_type, double>::value>(
1013                 _("complex") + _<sizeof(typename T2::value_type)*16>(), _("longcomplex"));
1014     }
1015 };
1017 #define PYBIND11_DECL_CHAR_FMT \
1018     static PYBIND11_DESCR name() { return _("S") + _<N>(); } \
1019     static pybind11::dtype dtype() { return pybind11::dtype(std::string("S") + std::to_string(N)); }
1020 template <size_t N> struct npy_format_descriptor<char[N]> { PYBIND11_DECL_CHAR_FMT };
1021 template <size_t N> struct npy_format_descriptor<std::array<char, N>> { PYBIND11_DECL_CHAR_FMT };
1022 #undef PYBIND11_DECL_CHAR_FMT
1024 template<typename T> struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {
1025 private:
1026     using base_descr = npy_format_descriptor<typename array_info<T>::type>;
1027 public:
1028     static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
1030     static PYBIND11_DESCR name() { return _("(") + array_info<T>::extents() + _(")") + base_descr::name(); }
1031     static pybind11::dtype dtype() {
1032         list shape;
1033         array_info<T>::append_extents(shape);
1034         return pybind11::dtype::from_args(pybind11::make_tuple(base_descr::dtype(), shape));
1035     }
1036 };
1038 template<typename T> struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {
1039 private:
1040     using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>;
1041 public:
1042     static PYBIND11_DESCR name() { return base_descr::name(); }
1043     static pybind11::dtype dtype() { return base_descr::dtype(); }
1044 };
1046 struct field_descriptor {
1047     const char *name;
1048     ssize_t offset;
1049     ssize_t size;
1050     std::string format;
1051     dtype descr;
1052 };
1054 inline PYBIND11_NOINLINE void register_structured_dtype(
1055     const std::initializer_list<field_descriptor>& fields,
1056     const std::type_info& tinfo, ssize_t itemsize,
1057     bool (*direct_converter)(PyObject *, void *&)) {
1059     auto& numpy_internals = get_numpy_internals();
1060     if (numpy_internals.get_type_info(tinfo, false))
1061         pybind11_fail("NumPy: dtype is already registered");
1063     list names, formats, offsets;
1064     for (auto field : fields) {
1065         if (!field.descr)
1066             pybind11_fail(std::string("NumPy: unsupported field dtype: `") +
1067                             field.name + "` @ " + tinfo.name());
1068         names.append(PYBIND11_STR_TYPE(field.name));
1069         formats.append(field.descr);
1070         offsets.append(pybind11::int_(field.offset));
1071     }
1072     auto dtype_ptr = pybind11::dtype(names, formats, offsets, itemsize).release().ptr();
1074     // There is an existing bug in NumPy (as of v1.11): trailing bytes are
1075     // not encoded explicitly into the format string. This will supposedly
1076     // get fixed in v1.12; for further details, see these:
1077     // - https://github.com/numpy/numpy/issues/7797
1078     // - https://github.com/numpy/numpy/pull/7798
1079     // Because of this, we won't use numpy's logic to generate buffer format
1080     // strings and will just do it ourselves.
1081     std::vector<field_descriptor> ordered_fields(fields);
1082     std::sort(ordered_fields.begin(), ordered_fields.end(),
1083         [](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
1084     ssize_t offset = 0;
1085     std::ostringstream oss;
1086     // mark the structure as unaligned with '^', because numpy and C++ don't
1087     // always agree about alignment (particularly for complex), and we're
1088     // explicitly listing all our padding. This depends on none of the fields
1089     // overriding the endianness. Putting the ^ in front of individual fields
1090     // isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
1091     oss << "^T{";
1092     for (auto& field : ordered_fields) {
1093         if (field.offset > offset)
1094             oss << (field.offset - offset) << 'x';
1095         oss << field.format << ':' << field.name << ':';
1096         offset = field.offset + field.size;
1097     }
1098     if (itemsize > offset)
1099         oss << (itemsize - offset) << 'x';
1100     oss << '}';
1101     auto format_str = oss.str();
1103     // Sanity check: verify that NumPy properly parses our buffer format string
1104     auto& api = npy_api::get();
1105     auto arr =  array(buffer_info(nullptr, itemsize, format_str, 1));
1106     if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr()))
1107         pybind11_fail("NumPy: invalid buffer descriptor!");
1109     auto tindex = std::type_index(tinfo);
1110     numpy_internals.registered_dtypes[tindex] = { dtype_ptr, format_str };
1111     get_internals().direct_conversions[tindex].push_back(direct_converter);
1114 template <typename T, typename SFINAE> struct npy_format_descriptor {
1115     static_assert(is_pod_struct<T>::value, "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1117     static PYBIND11_DESCR name() { return make_caster<T>::name(); }
1119     static pybind11::dtype dtype() {
1120         return reinterpret_borrow<pybind11::dtype>(dtype_ptr());
1121     }
1123     static std::string format() {
1124         static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
1125         return format_str;
1126     }
1128     static void register_dtype(const std::initializer_list<field_descriptor>& fields) {
1129         register_structured_dtype(fields, typeid(typename std::remove_cv<T>::type),
1130                                   sizeof(T), &direct_converter);
1131     }
1133 private:
1134     static PyObject* dtype_ptr() {
1135         static PyObject* ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
1136         return ptr;
1137     }
1139     static bool direct_converter(PyObject *obj, void*& value) {
1140         auto& api = npy_api::get();
1141         if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_))
1142             return false;
1143         if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
1144             if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
1145                 value = ((PyVoidScalarObject_Proxy *) obj)->obval;
1146                 return true;
1147             }
1148         }
1149         return false;
1150     }
1151 };
1153 #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1154 # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void)0)
1155 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void)0)
1156 #else
1158 #define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name)                                          \
1159     ::pybind11::detail::field_descriptor {                                                    \
1160         Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)),                  \
1161         ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(),           \
1162         ::pybind11::detail::npy_format_descriptor<decltype(std::declval<T>().Field)>::dtype() \
1163     }
1165 // Extract name, offset and format descriptor for a struct field
1166 #define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
1168 // The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
1169 // (C) William Swanson, Paul Fultz
1170 #define PYBIND11_EVAL0(...) __VA_ARGS__
1171 #define PYBIND11_EVAL1(...) PYBIND11_EVAL0 (PYBIND11_EVAL0 (PYBIND11_EVAL0 (__VA_ARGS__)))
1172 #define PYBIND11_EVAL2(...) PYBIND11_EVAL1 (PYBIND11_EVAL1 (PYBIND11_EVAL1 (__VA_ARGS__)))
1173 #define PYBIND11_EVAL3(...) PYBIND11_EVAL2 (PYBIND11_EVAL2 (PYBIND11_EVAL2 (__VA_ARGS__)))
1174 #define PYBIND11_EVAL4(...) PYBIND11_EVAL3 (PYBIND11_EVAL3 (PYBIND11_EVAL3 (__VA_ARGS__)))
1175 #define PYBIND11_EVAL(...)  PYBIND11_EVAL4 (PYBIND11_EVAL4 (PYBIND11_EVAL4 (__VA_ARGS__)))
1176 #define PYBIND11_MAP_END(...)
1177 #define PYBIND11_MAP_OUT
1178 #define PYBIND11_MAP_COMMA ,
1179 #define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1180 #define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1181 #define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0 (test, next, 0)
1182 #define PYBIND11_MAP_NEXT(test, next)  PYBIND11_MAP_NEXT1 (PYBIND11_MAP_GET_END test, next)
1183 #ifdef _MSC_VER // MSVC is not as eager to expand macros, hence this workaround
1184 #define PYBIND11_MAP_LIST_NEXT1(test, next) \
1185     PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
1186 #else
1187 #define PYBIND11_MAP_LIST_NEXT1(test, next) \
1188     PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
1189 #endif
1190 #define PYBIND11_MAP_LIST_NEXT(test, next) \
1191     PYBIND11_MAP_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
1192 #define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1193     f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST1) (f, t, peek, __VA_ARGS__)
1194 #define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1195     f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST0) (f, t, peek, __VA_ARGS__)
1196 // PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
1197 #define PYBIND11_MAP_LIST(f, t, ...) \
1198     PYBIND11_EVAL (PYBIND11_MAP_LIST1 (f, t, __VA_ARGS__, (), 0))
1200 #define PYBIND11_NUMPY_DTYPE(Type, ...) \
1201     ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
1202         ({PYBIND11_MAP_LIST (PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1204 #ifdef _MSC_VER
1205 #define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1206     PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
1207 #else
1208 #define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1209     PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
1210 #endif
1211 #define PYBIND11_MAP2_LIST_NEXT(test, next) \
1212     PYBIND11_MAP2_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
1213 #define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1214     f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST1) (f, t, peek, __VA_ARGS__)
1215 #define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1216     f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST0) (f, t, peek, __VA_ARGS__)
1217 // PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
1218 #define PYBIND11_MAP2_LIST(f, t, ...) \
1219     PYBIND11_EVAL (PYBIND11_MAP2_LIST1 (f, t, __VA_ARGS__, (), 0))
1221 #define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1222     ::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
1223         ({PYBIND11_MAP2_LIST (PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1225 #endif // __CLION_IDE__
1227 template  <class T>
1228 using array_iterator = typename std::add_pointer<T>::type;
1230 template <class T>
1231 array_iterator<T> array_begin(const buffer_info& buffer) {
1232     return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr));
1235 template <class T>
1236 array_iterator<T> array_end(const buffer_info& buffer) {
1237     return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr) + buffer.size);
1240 class common_iterator {
1241 public:
1242     using container_type = std::vector<ssize_t>;
1243     using value_type = container_type::value_type;
1244     using size_type = container_type::size_type;
1246     common_iterator() : p_ptr(0), m_strides() {}
1248     common_iterator(void* ptr, const container_type& strides, const container_type& shape)
1249         : p_ptr(reinterpret_cast<char*>(ptr)), m_strides(strides.size()) {
1250         m_strides.back() = static_cast<value_type>(strides.back());
1251         for (size_type i = m_strides.size() - 1; i != 0; --i) {
1252             size_type j = i - 1;
1253             value_type s = static_cast<value_type>(shape[i]);
1254             m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
1255         }
1256     }
1258     void increment(size_type dim) {
1259         p_ptr += m_strides[dim];
1260     }
1262     void* data() const {
1263         return p_ptr;
1264     }
1266 private:
1267     char* p_ptr;
1268     container_type m_strides;
1269 };
1271 template <size_t N> class multi_array_iterator {
1272 public:
1273     using container_type = std::vector<ssize_t>;
1275     multi_array_iterator(const std::array<buffer_info, N> &buffers,
1276                          const container_type &shape)
1277         : m_shape(shape.size()), m_index(shape.size(), 0),
1278           m_common_iterator() {
1280         // Manual copy to avoid conversion warning if using std::copy
1281         for (size_t i = 0; i < shape.size(); ++i)
1282             m_shape[i] = shape[i];
1284         container_type strides(shape.size());
1285         for (size_t i = 0; i < N; ++i)
1286             init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
1287     }
1289     multi_array_iterator& operator++() {
1290         for (size_t j = m_index.size(); j != 0; --j) {
1291             size_t i = j - 1;
1292             if (++m_index[i] != m_shape[i]) {
1293                 increment_common_iterator(i);
1294                 break;
1295             } else {
1296                 m_index[i] = 0;
1297             }
1298         }
1299         return *this;
1300     }
1302     template <size_t K, class T = void> T* data() const {
1303         return reinterpret_cast<T*>(m_common_iterator[K].data());
1304     }
1306 private:
1308     using common_iter = common_iterator;
1310     void init_common_iterator(const buffer_info &buffer,
1311                               const container_type &shape,
1312                               common_iter &iterator,
1313                               container_type &strides) {
1314         auto buffer_shape_iter = buffer.shape.rbegin();
1315         auto buffer_strides_iter = buffer.strides.rbegin();
1316         auto shape_iter = shape.rbegin();
1317         auto strides_iter = strides.rbegin();
1319         while (buffer_shape_iter != buffer.shape.rend()) {
1320             if (*shape_iter == *buffer_shape_iter)
1321                 *strides_iter = *buffer_strides_iter;
1322             else
1323                 *strides_iter = 0;
1325             ++buffer_shape_iter;
1326             ++buffer_strides_iter;
1327             ++shape_iter;
1328             ++strides_iter;
1329         }
1331         std::fill(strides_iter, strides.rend(), 0);
1332         iterator = common_iter(buffer.ptr, strides, shape);
1333     }
1335     void increment_common_iterator(size_t dim) {
1336         for (auto &iter : m_common_iterator)
1337             iter.increment(dim);
1338     }
1340     container_type m_shape;
1341     container_type m_index;
1342     std::array<common_iter, N> m_common_iterator;
1343 };
1345 enum class broadcast_trivial { non_trivial, c_trivial, f_trivial };
1347 // Populates the shape and number of dimensions for the set of buffers.  Returns a broadcast_trivial
1348 // enum value indicating whether the broadcast is "trivial"--that is, has each buffer being either a
1349 // singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous (`f_trivial`) storage
1350 // buffer; returns `non_trivial` otherwise.
1351 template <size_t N>
1352 broadcast_trivial broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
1353     ndim = std::accumulate(buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
1354         return std::max(res, buf.ndim);
1355     });
1357     shape.clear();
1358     shape.resize((size_t) ndim, 1);
1360     // Figure out the output size, and make sure all input arrays conform (i.e. are either size 1 or
1361     // the full size).
1362     for (size_t i = 0; i < N; ++i) {
1363         auto res_iter = shape.rbegin();
1364         auto end = buffers[i].shape.rend();
1365         for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end; ++shape_iter, ++res_iter) {
1366             const auto &dim_size_in = *shape_iter;
1367             auto &dim_size_out = *res_iter;
1369             // Each input dimension can either be 1 or `n`, but `n` values must match across buffers
1370             if (dim_size_out == 1)
1371                 dim_size_out = dim_size_in;
1372             else if (dim_size_in != 1 && dim_size_in != dim_size_out)
1373                 pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
1374         }
1375     }
1377     bool trivial_broadcast_c = true;
1378     bool trivial_broadcast_f = true;
1379     for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
1380         if (buffers[i].size == 1)
1381             continue;
1383         // Require the same number of dimensions:
1384         if (buffers[i].ndim != ndim)
1385             return broadcast_trivial::non_trivial;
1387         // Require all dimensions be full-size:
1388         if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin()))
1389             return broadcast_trivial::non_trivial;
1391         // Check for C contiguity (but only if previous inputs were also C contiguous)
1392         if (trivial_broadcast_c) {
1393             ssize_t expect_stride = buffers[i].itemsize;
1394             auto end = buffers[i].shape.crend();
1395             for (auto shape_iter = buffers[i].shape.crbegin(), stride_iter = buffers[i].strides.crbegin();
1396                     trivial_broadcast_c && shape_iter != end; ++shape_iter, ++stride_iter) {
1397                 if (expect_stride == *stride_iter)
1398                     expect_stride *= *shape_iter;
1399                 else
1400                     trivial_broadcast_c = false;
1401             }
1402         }
1404         // Check for Fortran contiguity (if previous inputs were also F contiguous)
1405         if (trivial_broadcast_f) {
1406             ssize_t expect_stride = buffers[i].itemsize;
1407             auto end = buffers[i].shape.cend();
1408             for (auto shape_iter = buffers[i].shape.cbegin(), stride_iter = buffers[i].strides.cbegin();
1409                     trivial_broadcast_f && shape_iter != end; ++shape_iter, ++stride_iter) {
1410                 if (expect_stride == *stride_iter)
1411                     expect_stride *= *shape_iter;
1412                 else
1413                     trivial_broadcast_f = false;
1414             }
1415         }
1416     }
1418     return
1419         trivial_broadcast_c ? broadcast_trivial::c_trivial :
1420         trivial_broadcast_f ? broadcast_trivial::f_trivial :
1421         broadcast_trivial::non_trivial;
1424 template <typename T>
1425 struct vectorize_arg {
1426     static_assert(!std::is_rvalue_reference<T>::value, "Functions with rvalue reference arguments cannot be vectorized");
1427     // The wrapped function gets called with this type:
1428     using call_type = remove_reference_t<T>;
1429     // Is this a vectorized argument?
1430     static constexpr bool vectorize =
1431         satisfies_any_of<call_type, std::is_arithmetic, is_complex, std::is_pod>::value &&
1432         satisfies_none_of<call_type, std::is_pointer, std::is_array, is_std_array, std::is_enum>::value &&
1433         (!std::is_reference<T>::value ||
1434          (std::is_lvalue_reference<T>::value && std::is_const<call_type>::value));
1435     // Accept this type: an array for vectorized types, otherwise the type as-is:
1436     using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>;
1437 };
1439 template <typename Func, typename Return, typename... Args>
1440 struct vectorize_helper {
1441 private:
1442     static constexpr size_t N = sizeof...(Args);
1443     static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
1444     static_assert(NVectorized >= 1,
1445             "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
1447 public:
1448     template <typename T>
1449     explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) { }
1451     object operator()(typename vectorize_arg<Args>::type... args) {
1452         return run(args...,
1453                    make_index_sequence<N>(),
1454                    select_indices<vectorize_arg<Args>::vectorize...>(),
1455                    make_index_sequence<NVectorized>());
1456     }
1458 private:
1459     remove_reference_t<Func> f;
1461     template <size_t Index> using param_n_t = typename pack_element<Index, typename vectorize_arg<Args>::call_type...>::type;
1463     // Runs a vectorized function given arguments tuple and three index sequences:
1464     //     - Index is the full set of 0 ... (N-1) argument indices;
1465     //     - VIndex is the subset of argument indices with vectorized parameters, letting us access
1466     //       vectorized arguments (anything not in this sequence is passed through)
1467     //     - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
1468     //       we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
1469     //       index BIndex in the array).
1470     template <size_t... Index, size_t... VIndex, size_t... BIndex> object run(
1471             typename vectorize_arg<Args>::type &...args,
1472             index_sequence<Index...> i_seq, index_sequence<VIndex...> vi_seq, index_sequence<BIndex...> bi_seq) {
1474         // Pointers to values the function was called with; the vectorized ones set here will start
1475         // out as array_t<T> pointers, but they will be changed them to T pointers before we make
1476         // call the wrapped function.  Non-vectorized pointers are left as-is.
1477         std::array<void *, N> params{{ &args... }};
1479         // The array of `buffer_info`s of vectorized arguments:
1480         std::array<buffer_info, NVectorized> buffers{{ reinterpret_cast<array *>(params[VIndex])->request()... }};
1482         /* Determine dimensions parameters of output array */
1483         ssize_t nd = 0;
1484         std::vector<ssize_t> shape(0);
1485         auto trivial = broadcast(buffers, nd, shape);
1486         size_t ndim = (size_t) nd;
1488         size_t size = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
1490         // If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
1491         // not wrapped in an array).
1492         if (size == 1 && ndim == 0) {
1493             PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
1494             return cast(f(*reinterpret_cast<param_n_t<Index> *>(params[Index])...));
1495         }
1497         array_t<Return> result;
1498         if (trivial == broadcast_trivial::f_trivial) result = array_t<Return, array::f_style>(shape);
1499         else result = array_t<Return>(shape);
1501         if (size == 0) return result;
1503         /* Call the function */
1504         if (trivial == broadcast_trivial::non_trivial)
1505             apply_broadcast(buffers, params, result, i_seq, vi_seq, bi_seq);
1506         else
1507             apply_trivial(buffers, params, result.mutable_data(), size, i_seq, vi_seq, bi_seq);
1509         return result;
1510     }
1512     template <size_t... Index, size_t... VIndex, size_t... BIndex>
1513     void apply_trivial(std::array<buffer_info, NVectorized> &buffers,
1514                        std::array<void *, N> &params,
1515                        Return *out,
1516                        size_t size,
1517                        index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) {
1519         // Initialize an array of mutable byte references and sizes with references set to the
1520         // appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
1521         // (except for singletons, which get an increment of 0).
1522         std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{{
1523             std::pair<unsigned char *&, const size_t>(
1524                     reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
1525                     buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>)
1526             )...
1527         }};
1529         for (size_t i = 0; i < size; ++i) {
1530             out[i] = f(*reinterpret_cast<param_n_t<Index> *>(params[Index])...);
1531             for (auto &x : vecparams) x.first += x.second;
1532         }
1533     }
1535     template <size_t... Index, size_t... VIndex, size_t... BIndex>
1536     void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
1537                          std::array<void *, N> &params,
1538                          array_t<Return> &output_array,
1539                          index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) {
1541         buffer_info output = output_array.request();
1542         multi_array_iterator<NVectorized> input_iter(buffers, output.shape);
1544         for (array_iterator<Return> iter = array_begin<Return>(output), end = array_end<Return>(output);
1545              iter != end;
1546              ++iter, ++input_iter) {
1547             PYBIND11_EXPAND_SIDE_EFFECTS((
1548                 params[VIndex] = input_iter.template data<BIndex>()
1549             ));
1550             *iter = f(*reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
1551         }
1552     }
1553 };
1555 template <typename Func, typename Return, typename... Args>
1556 vectorize_helper<Func, Return, Args...>
1557 vectorize_extractor(const Func &f, Return (*) (Args ...)) {
1558     return detail::vectorize_helper<Func, Return, Args...>(f);
1561 template <typename T, int Flags> struct handle_type_name<array_t<T, Flags>> {
1562     static PYBIND11_DESCR name() {
1563         return _("numpy.ndarray[") + npy_format_descriptor<T>::name() + _("]");
1564     }
1565 };
1567 NAMESPACE_END(detail)
1569 // Vanilla pointer vectorizer:
1570 template <typename Return, typename... Args>
1571 detail::vectorize_helper<Return (*)(Args...), Return, Args...>
1572 vectorize(Return (*f) (Args ...)) {
1573     return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
1576 // lambda vectorizer:
1577 template <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0>
1578 auto vectorize(Func &&f) -> decltype(
1579         detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr)) {
1580     return detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr);
1583 // Vectorize a class method (non-const):
1584 template <typename Return, typename Class, typename... Args,
1585           typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())), Return, Class *, Args...>>
1586 Helper vectorize(Return (Class::*f)(Args...)) {
1587     return Helper(std::mem_fn(f));
1590 // Vectorize a class method (const):
1591 template <typename Return, typename Class, typename... Args,
1592           typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())), Return, const Class *, Args...>>
1593 Helper vectorize(Return (Class::*f)(Args...) const) {
1594     return Helper(std::mem_fn(f));
1597 NAMESPACE_END(PYBIND11_NAMESPACE)
1599 #if defined(_MSC_VER)
1600 #pragma warning(pop)
1601 #endif