2015-07-26 14:33:49 +00:00
|
|
|
/*
|
2016-05-05 18:33:54 +00:00
|
|
|
pybind11/numpy.h: Basic NumPy support, vectorize() wrapper
|
2015-07-26 14:33:49 +00:00
|
|
|
|
2016-04-17 18:21:41 +00:00
|
|
|
Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
|
2015-07-26 14:33:49 +00:00
|
|
|
|
|
|
|
All rights reserved. Use of this source code is governed by a
|
|
|
|
BSD-style license that can be found in the LICENSE file.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
2015-10-15 16:13:33 +00:00
|
|
|
#include "pybind11.h"
|
|
|
|
#include "complex.h"
|
2016-02-11 09:47:11 +00:00
|
|
|
#include <numeric>
|
|
|
|
#include <algorithm>
|
2016-07-19 23:19:24 +00:00
|
|
|
#include <array>
|
2018-12-01 12:31:44 +00:00
|
|
|
#include <cstdint>
|
2016-06-19 13:50:06 +00:00
|
|
|
#include <cstdlib>
|
2016-06-19 14:48:55 +00:00
|
|
|
#include <cstring>
|
2016-07-05 23:28:12 +00:00
|
|
|
#include <sstream>
|
2016-08-14 12:45:49 +00:00
|
|
|
#include <string>
|
2016-08-29 01:41:05 +00:00
|
|
|
#include <functional>
|
2016-11-01 13:27:35 +00:00
|
|
|
#include <utility>
|
2017-12-27 15:00:27 +00:00
|
|
|
#include <vector>
|
2016-10-31 13:52:32 +00:00
|
|
|
#include <typeindex>
|
2015-07-29 15:51:54 +00:00
|
|
|
|
2015-07-26 14:33:49 +00:00
|
|
|
#if defined(_MSC_VER)
|
2016-10-12 22:57:42 +00:00
|
|
|
# pragma warning(push)
|
|
|
|
# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant
|
2015-07-26 14:33:49 +00:00
|
|
|
#endif
|
|
|
|
|
2016-09-08 20:48:14 +00:00
|
|
|
/* This will be true on all flat address space platforms and allows us to reduce the
|
2017-05-20 15:21:19 +00:00
|
|
|
whole npy_intp / ssize_t / Py_intptr_t business down to just ssize_t for all size
|
2016-09-08 20:48:14 +00:00
|
|
|
and dimension types (e.g. shape, strides, indexing), instead of inflicting this
|
|
|
|
upon the library user. */
|
2017-05-20 15:21:19 +00:00
|
|
|
static_assert(sizeof(ssize_t) == sizeof(Py_intptr_t), "ssize_t != Py_intptr_t");
|
2016-09-08 20:48:14 +00:00
|
|
|
|
2017-08-10 16:03:29 +00:00
|
|
|
NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
2017-03-19 04:14:23 +00:00
|
|
|
|
|
|
|
class array; // Forward declaration
|
|
|
|
|
2016-09-08 20:48:14 +00:00
|
|
|
NAMESPACE_BEGIN(detail)
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
template <typename type, typename SFINAE = void> struct npy_format_descriptor;
|
2015-07-28 14:12:20 +00:00
|
|
|
|
2016-08-29 01:41:05 +00:00
|
|
|
struct PyArrayDescr_Proxy {
|
|
|
|
PyObject_HEAD
|
|
|
|
PyObject *typeobj;
|
|
|
|
char kind;
|
|
|
|
char type;
|
|
|
|
char byteorder;
|
|
|
|
char flags;
|
|
|
|
int type_num;
|
|
|
|
int elsize;
|
|
|
|
int alignment;
|
|
|
|
char *subarray;
|
|
|
|
PyObject *fields;
|
|
|
|
PyObject *names;
|
|
|
|
};
|
|
|
|
|
|
|
|
struct PyArray_Proxy {
|
|
|
|
PyObject_HEAD
|
|
|
|
char *data;
|
|
|
|
int nd;
|
|
|
|
ssize_t *dimensions;
|
|
|
|
ssize_t *strides;
|
|
|
|
PyObject *base;
|
|
|
|
PyObject *descr;
|
|
|
|
int flags;
|
|
|
|
};
|
|
|
|
|
2016-10-20 15:11:08 +00:00
|
|
|
struct PyVoidScalarObject_Proxy {
|
|
|
|
PyObject_VAR_HEAD
|
|
|
|
char *obval;
|
|
|
|
PyArrayDescr_Proxy *descr;
|
|
|
|
int flags;
|
|
|
|
PyObject *base;
|
|
|
|
};
|
|
|
|
|
2016-10-31 13:52:32 +00:00
|
|
|
struct numpy_type_info {
|
|
|
|
PyObject* dtype_ptr;
|
|
|
|
std::string format_str;
|
|
|
|
};
|
|
|
|
|
|
|
|
struct numpy_internals {
|
|
|
|
std::unordered_map<std::type_index, numpy_type_info> registered_dtypes;
|
|
|
|
|
2016-10-31 16:16:47 +00:00
|
|
|
numpy_type_info *get_type_info(const std::type_info& tinfo, bool throw_if_missing = true) {
|
|
|
|
auto it = registered_dtypes.find(std::type_index(tinfo));
|
2016-10-31 13:52:32 +00:00
|
|
|
if (it != registered_dtypes.end())
|
|
|
|
return &(it->second);
|
|
|
|
if (throw_if_missing)
|
2016-10-31 16:16:47 +00:00
|
|
|
pybind11_fail(std::string("NumPy type info missing for ") + tinfo.name());
|
2016-10-31 13:52:32 +00:00
|
|
|
return nullptr;
|
|
|
|
}
|
2016-10-31 16:16:47 +00:00
|
|
|
|
|
|
|
template<typename T> numpy_type_info *get_type_info(bool throw_if_missing = true) {
|
|
|
|
return get_type_info(typeid(typename std::remove_cv<T>::type), throw_if_missing);
|
|
|
|
}
|
2016-10-31 13:52:32 +00:00
|
|
|
};
|
|
|
|
|
2016-10-31 14:11:10 +00:00
|
|
|
inline PYBIND11_NOINLINE void load_numpy_internals(numpy_internals* &ptr) {
|
|
|
|
ptr = &get_or_create_shared_data<numpy_internals>("_numpy_internals");
|
2016-10-31 13:52:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
inline numpy_internals& get_numpy_internals() {
|
2016-10-31 14:11:10 +00:00
|
|
|
static numpy_internals* ptr = nullptr;
|
|
|
|
if (!ptr)
|
|
|
|
load_numpy_internals(ptr);
|
2016-10-31 13:52:32 +00:00
|
|
|
return *ptr;
|
|
|
|
}
|
|
|
|
|
2018-12-01 12:31:44 +00:00
|
|
|
template <typename T> struct same_size {
|
|
|
|
template <typename U> using as = bool_constant<sizeof(T) == sizeof(U)>;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Lookup a type according to its size, and return a value corresponding to the NumPy typenum.
|
|
|
|
template <typename Concrete, typename... Check, typename... Int>
|
|
|
|
constexpr int platform_lookup(Int... codes) {
|
|
|
|
using code_index = std::integral_constant<int, constexpr_first<same_size<Concrete>::template as, Check...>()>;
|
|
|
|
static_assert(code_index::value != sizeof...(Check), "Unable to match type on this platform");
|
|
|
|
return std::get<code_index::value>(std::make_tuple(codes...));
|
|
|
|
}
|
|
|
|
|
2016-07-19 23:54:57 +00:00
|
|
|
struct npy_api {
|
|
|
|
enum constants {
|
2017-01-17 01:15:42 +00:00
|
|
|
NPY_ARRAY_C_CONTIGUOUS_ = 0x0001,
|
|
|
|
NPY_ARRAY_F_CONTIGUOUS_ = 0x0002,
|
2016-08-29 01:41:05 +00:00
|
|
|
NPY_ARRAY_OWNDATA_ = 0x0004,
|
2016-07-19 23:54:57 +00:00
|
|
|
NPY_ARRAY_FORCECAST_ = 0x0010,
|
2017-01-17 01:15:42 +00:00
|
|
|
NPY_ARRAY_ENSUREARRAY_ = 0x0040,
|
2016-08-29 01:41:05 +00:00
|
|
|
NPY_ARRAY_ALIGNED_ = 0x0100,
|
|
|
|
NPY_ARRAY_WRITEABLE_ = 0x0400,
|
2016-07-19 23:54:57 +00:00
|
|
|
NPY_BOOL_ = 0,
|
|
|
|
NPY_BYTE_, NPY_UBYTE_,
|
|
|
|
NPY_SHORT_, NPY_USHORT_,
|
|
|
|
NPY_INT_, NPY_UINT_,
|
|
|
|
NPY_LONG_, NPY_ULONG_,
|
|
|
|
NPY_LONGLONG_, NPY_ULONGLONG_,
|
|
|
|
NPY_FLOAT_, NPY_DOUBLE_, NPY_LONGDOUBLE_,
|
|
|
|
NPY_CFLOAT_, NPY_CDOUBLE_, NPY_CLONGDOUBLE_,
|
|
|
|
NPY_OBJECT_ = 17,
|
2018-12-01 12:31:44 +00:00
|
|
|
NPY_STRING_, NPY_UNICODE_, NPY_VOID_,
|
|
|
|
// Platform-dependent normalization
|
|
|
|
NPY_INT8_ = NPY_BYTE_,
|
|
|
|
NPY_UINT8_ = NPY_UBYTE_,
|
|
|
|
NPY_INT16_ = NPY_SHORT_,
|
|
|
|
NPY_UINT16_ = NPY_USHORT_,
|
|
|
|
// `npy_common.h` defines the integer aliases. In order, it checks:
|
|
|
|
// NPY_BITSOF_LONG, NPY_BITSOF_LONGLONG, NPY_BITSOF_INT, NPY_BITSOF_SHORT, NPY_BITSOF_CHAR
|
|
|
|
// and assigns the alias to the first matching size, so we should check in this order.
|
|
|
|
NPY_INT32_ = platform_lookup<std::int32_t, long, int, short>(
|
|
|
|
NPY_LONG_, NPY_INT_, NPY_SHORT_),
|
|
|
|
NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(
|
|
|
|
NPY_ULONG_, NPY_UINT_, NPY_USHORT_),
|
|
|
|
NPY_INT64_ = platform_lookup<std::int64_t, long, long long, int>(
|
|
|
|
NPY_LONG_, NPY_LONGLONG_, NPY_INT_),
|
|
|
|
NPY_UINT64_ = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(
|
|
|
|
NPY_ULONG_, NPY_ULONGLONG_, NPY_UINT_),
|
2016-07-19 23:54:57 +00:00
|
|
|
};
|
|
|
|
|
2017-04-13 16:41:55 +00:00
|
|
|
typedef struct {
|
|
|
|
Py_intptr_t *ptr;
|
|
|
|
int len;
|
|
|
|
} PyArray_Dims;
|
|
|
|
|
2016-07-19 23:54:57 +00:00
|
|
|
static npy_api& get() {
|
|
|
|
static npy_api api = lookup();
|
|
|
|
return api;
|
|
|
|
}
|
|
|
|
|
2016-07-23 20:55:37 +00:00
|
|
|
bool PyArray_Check_(PyObject *obj) const {
|
|
|
|
return (bool) PyObject_TypeCheck(obj, PyArray_Type_);
|
|
|
|
}
|
|
|
|
bool PyArrayDescr_Check_(PyObject *obj) const {
|
|
|
|
return (bool) PyObject_TypeCheck(obj, PyArrayDescr_Type_);
|
|
|
|
}
|
2016-07-19 23:54:57 +00:00
|
|
|
|
2017-04-28 12:57:13 +00:00
|
|
|
unsigned int (*PyArray_GetNDArrayCFeatureVersion_)();
|
2016-07-19 23:54:57 +00:00
|
|
|
PyObject *(*PyArray_DescrFromType_)(int);
|
|
|
|
PyObject *(*PyArray_NewFromDescr_)
|
|
|
|
(PyTypeObject *, PyObject *, int, Py_intptr_t *,
|
|
|
|
Py_intptr_t *, void *, int, PyObject *);
|
|
|
|
PyObject *(*PyArray_DescrNewFromType_)(int);
|
2017-04-06 22:16:35 +00:00
|
|
|
int (*PyArray_CopyInto_)(PyObject *, PyObject *);
|
2016-07-19 23:54:57 +00:00
|
|
|
PyObject *(*PyArray_NewCopy_)(PyObject *, int);
|
|
|
|
PyTypeObject *PyArray_Type_;
|
2016-10-20 15:09:10 +00:00
|
|
|
PyTypeObject *PyVoidArrType_Type_;
|
2016-07-23 20:55:37 +00:00
|
|
|
PyTypeObject *PyArrayDescr_Type_;
|
2016-10-20 15:09:10 +00:00
|
|
|
PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
|
2016-07-19 23:54:57 +00:00
|
|
|
PyObject *(*PyArray_FromAny_) (PyObject *, PyObject *, int, int, int, PyObject *);
|
|
|
|
int (*PyArray_DescrConverter_) (PyObject *, PyObject **);
|
|
|
|
bool (*PyArray_EquivTypes_) (PyObject *, PyObject *);
|
|
|
|
int (*PyArray_GetArrayParamsFromObject_)(PyObject *, PyObject *, char, PyObject **, int *,
|
|
|
|
Py_ssize_t *, PyObject **, PyObject *);
|
2016-10-07 09:19:25 +00:00
|
|
|
PyObject *(*PyArray_Squeeze_)(PyObject *);
|
2017-01-17 01:22:00 +00:00
|
|
|
int (*PyArray_SetBaseObject_)(PyObject *, PyObject *);
|
2017-04-13 16:41:55 +00:00
|
|
|
PyObject* (*PyArray_Resize_)(PyObject*, PyArray_Dims*, int, int);
|
2016-07-19 23:54:57 +00:00
|
|
|
private:
|
|
|
|
enum functions {
|
2017-04-28 12:57:13 +00:00
|
|
|
API_PyArray_GetNDArrayCFeatureVersion = 211,
|
2016-07-19 23:54:57 +00:00
|
|
|
API_PyArray_Type = 2,
|
2016-07-23 20:55:37 +00:00
|
|
|
API_PyArrayDescr_Type = 3,
|
2016-10-20 15:09:10 +00:00
|
|
|
API_PyVoidArrType_Type = 39,
|
2016-07-19 23:54:57 +00:00
|
|
|
API_PyArray_DescrFromType = 45,
|
2016-10-20 15:09:10 +00:00
|
|
|
API_PyArray_DescrFromScalar = 57,
|
2016-07-19 23:54:57 +00:00
|
|
|
API_PyArray_FromAny = 69,
|
2017-04-13 16:41:55 +00:00
|
|
|
API_PyArray_Resize = 80,
|
2017-04-06 22:16:35 +00:00
|
|
|
API_PyArray_CopyInto = 82,
|
2016-07-19 23:54:57 +00:00
|
|
|
API_PyArray_NewCopy = 85,
|
|
|
|
API_PyArray_NewFromDescr = 94,
|
|
|
|
API_PyArray_DescrNewFromType = 9,
|
|
|
|
API_PyArray_DescrConverter = 174,
|
|
|
|
API_PyArray_EquivTypes = 182,
|
|
|
|
API_PyArray_GetArrayParamsFromObject = 278,
|
2017-01-17 01:22:00 +00:00
|
|
|
API_PyArray_Squeeze = 136,
|
|
|
|
API_PyArray_SetBaseObject = 282
|
2016-07-19 23:54:57 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
static npy_api lookup() {
|
|
|
|
module m = module::import("numpy.core.multiarray");
|
2016-09-08 15:02:04 +00:00
|
|
|
auto c = m.attr("_ARRAY_API");
|
2015-09-04 21:42:12 +00:00
|
|
|
#if PY_MAJOR_VERSION >= 3
|
2016-09-20 23:06:32 +00:00
|
|
|
void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), NULL);
|
2015-09-04 21:42:12 +00:00
|
|
|
#else
|
2016-09-20 23:06:32 +00:00
|
|
|
void **api_ptr = (void **) PyCObject_AsVoidPtr(c.ptr());
|
2015-09-04 21:42:12 +00:00
|
|
|
#endif
|
2016-07-19 23:54:57 +00:00
|
|
|
npy_api api;
|
2016-06-19 13:44:20 +00:00
|
|
|
#define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
|
2017-04-28 12:57:13 +00:00
|
|
|
DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion);
|
|
|
|
if (api.PyArray_GetNDArrayCFeatureVersion_() < 0x7)
|
|
|
|
pybind11_fail("pybind11 numpy support requires numpy >= 1.7.0");
|
2016-07-19 23:54:57 +00:00
|
|
|
DECL_NPY_API(PyArray_Type);
|
2016-10-20 15:09:10 +00:00
|
|
|
DECL_NPY_API(PyVoidArrType_Type);
|
2016-07-23 20:55:37 +00:00
|
|
|
DECL_NPY_API(PyArrayDescr_Type);
|
2016-07-19 23:54:57 +00:00
|
|
|
DECL_NPY_API(PyArray_DescrFromType);
|
2016-10-20 15:09:10 +00:00
|
|
|
DECL_NPY_API(PyArray_DescrFromScalar);
|
2016-07-19 23:54:57 +00:00
|
|
|
DECL_NPY_API(PyArray_FromAny);
|
2017-04-13 16:41:55 +00:00
|
|
|
DECL_NPY_API(PyArray_Resize);
|
2017-04-06 22:16:35 +00:00
|
|
|
DECL_NPY_API(PyArray_CopyInto);
|
2016-07-19 23:54:57 +00:00
|
|
|
DECL_NPY_API(PyArray_NewCopy);
|
|
|
|
DECL_NPY_API(PyArray_NewFromDescr);
|
|
|
|
DECL_NPY_API(PyArray_DescrNewFromType);
|
|
|
|
DECL_NPY_API(PyArray_DescrConverter);
|
|
|
|
DECL_NPY_API(PyArray_EquivTypes);
|
|
|
|
DECL_NPY_API(PyArray_GetArrayParamsFromObject);
|
2016-10-07 09:19:25 +00:00
|
|
|
DECL_NPY_API(PyArray_Squeeze);
|
2017-01-17 01:22:00 +00:00
|
|
|
DECL_NPY_API(PyArray_SetBaseObject);
|
2016-06-19 13:44:20 +00:00
|
|
|
#undef DECL_NPY_API
|
2016-07-19 23:54:57 +00:00
|
|
|
return api;
|
|
|
|
}
|
|
|
|
};
|
2015-07-28 14:12:20 +00:00
|
|
|
|
2016-11-22 10:29:55 +00:00
|
|
|
inline PyArray_Proxy* array_proxy(void* ptr) {
|
|
|
|
return reinterpret_cast<PyArray_Proxy*>(ptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
inline const PyArray_Proxy* array_proxy(const void* ptr) {
|
|
|
|
return reinterpret_cast<const PyArray_Proxy*>(ptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
inline PyArrayDescr_Proxy* array_descriptor_proxy(PyObject* ptr) {
|
|
|
|
return reinterpret_cast<PyArrayDescr_Proxy*>(ptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
inline const PyArrayDescr_Proxy* array_descriptor_proxy(const PyObject* ptr) {
|
|
|
|
return reinterpret_cast<const PyArrayDescr_Proxy*>(ptr);
|
|
|
|
}
|
|
|
|
|
|
|
|
inline bool check_flags(const void* ptr, int flag) {
|
|
|
|
return (flag == (array_proxy(ptr)->flags & flag));
|
|
|
|
}
|
|
|
|
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
template <typename T> struct is_std_array : std::false_type { };
|
|
|
|
template <typename T, size_t N> struct is_std_array<std::array<T, N>> : std::true_type { };
|
|
|
|
template <typename T> struct is_complex : std::false_type { };
|
|
|
|
template <typename T> struct is_complex<std::complex<T>> : std::true_type { };
|
|
|
|
|
2017-05-10 08:21:01 +00:00
|
|
|
template <typename T> struct array_info_scalar {
|
|
|
|
typedef T type;
|
|
|
|
static constexpr bool is_array = false;
|
|
|
|
static constexpr bool is_empty = false;
|
2017-07-02 09:48:56 +00:00
|
|
|
static constexpr auto extents = _("");
|
2017-05-10 08:21:01 +00:00
|
|
|
static void append_extents(list& /* shape */) { }
|
|
|
|
};
|
|
|
|
// Computes underlying type and a comma-separated list of extents for array
|
|
|
|
// types (any mix of std::array and built-in arrays). An array of char is
|
|
|
|
// treated as scalar because it gets special handling.
|
|
|
|
template <typename T> struct array_info : array_info_scalar<T> { };
|
|
|
|
template <typename T, size_t N> struct array_info<std::array<T, N>> {
|
|
|
|
using type = typename array_info<T>::type;
|
|
|
|
static constexpr bool is_array = true;
|
|
|
|
static constexpr bool is_empty = (N == 0) || array_info<T>::is_empty;
|
|
|
|
static constexpr size_t extent = N;
|
|
|
|
|
|
|
|
// appends the extents to shape
|
|
|
|
static void append_extents(list& shape) {
|
|
|
|
shape.append(N);
|
|
|
|
array_info<T>::append_extents(shape);
|
|
|
|
}
|
|
|
|
|
2017-07-02 09:48:56 +00:00
|
|
|
static constexpr auto extents = _<array_info<T>::is_array>(
|
|
|
|
concat(_<N>(), array_info<T>::extents), _<N>()
|
|
|
|
);
|
2017-05-10 08:21:01 +00:00
|
|
|
};
|
|
|
|
// For numpy we have special handling for arrays of characters, so we don't include
|
|
|
|
// the size in the array extents.
|
|
|
|
template <size_t N> struct array_info<char[N]> : array_info_scalar<char[N]> { };
|
|
|
|
template <size_t N> struct array_info<std::array<char, N>> : array_info_scalar<std::array<char, N>> { };
|
|
|
|
template <typename T, size_t N> struct array_info<T[N]> : array_info<std::array<T, N>> { };
|
|
|
|
template <typename T> using remove_all_extents_t = typename array_info<T>::type;
|
|
|
|
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
template <typename T> using is_pod_struct = all_of<
|
2017-05-10 09:36:24 +00:00
|
|
|
std::is_standard_layout<T>, // since we're accessing directly in memory we need a standard layout type
|
2017-09-04 19:16:09 +00:00
|
|
|
#if !defined(__GNUG__) || defined(_LIBCPP_VERSION) || defined(_GLIBCXX_USE_CXX11_ABI)
|
|
|
|
// _GLIBCXX_USE_CXX11_ABI indicates that we're using libstdc++ from GCC 5 or newer, independent
|
|
|
|
// of the actual compiler (Clang can also use libstdc++, but it always defines __GNUC__ == 4).
|
2017-05-10 09:36:24 +00:00
|
|
|
std::is_trivially_copyable<T>,
|
|
|
|
#else
|
|
|
|
// GCC 4 doesn't implement is_trivially_copyable, so approximate it
|
|
|
|
std::is_trivially_destructible<T>,
|
|
|
|
satisfies_any_of<T, std::has_trivial_copy_constructor, std::has_trivial_copy_assign>,
|
|
|
|
#endif
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
satisfies_none_of<T, std::is_reference, std::is_array, is_std_array, std::is_arithmetic, is_complex, std::is_enum>
|
|
|
|
>;
|
|
|
|
|
2017-04-14 20:33:44 +00:00
|
|
|
template <ssize_t Dim = 0, typename Strides> ssize_t byte_offset_unsafe(const Strides &) { return 0; }
|
|
|
|
template <ssize_t Dim = 0, typename Strides, typename... Ix>
|
|
|
|
ssize_t byte_offset_unsafe(const Strides &strides, ssize_t i, Ix... index) {
|
|
|
|
return i * strides[Dim] + byte_offset_unsafe<Dim + 1>(strides, index...);
|
2017-03-19 04:14:23 +00:00
|
|
|
}
|
|
|
|
|
2017-05-22 16:06:16 +00:00
|
|
|
/**
|
|
|
|
* Proxy class providing unsafe, unchecked const access to array data. This is constructed through
|
2017-03-20 20:48:38 +00:00
|
|
|
* the `unchecked<T, N>()` method of `array` or the `unchecked<N>()` method of `array_t<T>`. `Dims`
|
|
|
|
* will be -1 for dimensions determined at runtime.
|
2017-03-19 04:14:23 +00:00
|
|
|
*/
|
2017-03-20 20:48:38 +00:00
|
|
|
template <typename T, ssize_t Dims>
|
2017-03-19 04:14:23 +00:00
|
|
|
class unchecked_reference {
|
|
|
|
protected:
|
2017-03-20 20:48:38 +00:00
|
|
|
static constexpr bool Dynamic = Dims < 0;
|
2017-03-19 04:14:23 +00:00
|
|
|
const unsigned char *data_;
|
|
|
|
// Storing the shape & strides in local variables (i.e. these arrays) allows the compiler to
|
2017-03-20 20:48:38 +00:00
|
|
|
// make large performance gains on big, nested loops, but requires compile-time dimensions
|
2017-04-14 20:33:44 +00:00
|
|
|
conditional_t<Dynamic, const ssize_t *, std::array<ssize_t, (size_t) Dims>>
|
|
|
|
shape_, strides_;
|
|
|
|
const ssize_t dims_;
|
2017-03-19 04:14:23 +00:00
|
|
|
|
|
|
|
friend class pybind11::array;
|
2017-03-20 20:48:38 +00:00
|
|
|
// Constructor for compile-time dimensions:
|
|
|
|
template <bool Dyn = Dynamic>
|
2017-04-14 20:33:44 +00:00
|
|
|
unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<!Dyn, ssize_t>)
|
2017-03-20 20:48:38 +00:00
|
|
|
: data_{reinterpret_cast<const unsigned char *>(data)}, dims_{Dims} {
|
2017-04-14 20:33:44 +00:00
|
|
|
for (size_t i = 0; i < (size_t) dims_; i++) {
|
2017-03-19 04:14:23 +00:00
|
|
|
shape_[i] = shape[i];
|
|
|
|
strides_[i] = strides[i];
|
|
|
|
}
|
|
|
|
}
|
2017-03-20 20:48:38 +00:00
|
|
|
// Constructor for runtime dimensions:
|
|
|
|
template <bool Dyn = Dynamic>
|
2017-04-14 20:33:44 +00:00
|
|
|
unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<Dyn, ssize_t> dims)
|
2017-03-20 20:48:38 +00:00
|
|
|
: data_{reinterpret_cast<const unsigned char *>(data)}, shape_{shape}, strides_{strides}, dims_{dims} {}
|
2017-03-19 04:14:23 +00:00
|
|
|
|
|
|
|
public:
|
2017-05-22 16:06:16 +00:00
|
|
|
/**
|
|
|
|
* Unchecked const reference access to data at the given indices. For a compile-time known
|
2017-03-20 20:48:38 +00:00
|
|
|
* number of dimensions, this requires the correct number of arguments; for run-time
|
|
|
|
* dimensionality, this is not checked (and so is up to the caller to use safely).
|
2017-03-19 04:14:23 +00:00
|
|
|
*/
|
2017-03-20 20:48:38 +00:00
|
|
|
template <typename... Ix> const T &operator()(Ix... index) const {
|
2017-08-22 14:37:51 +00:00
|
|
|
static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
|
2017-03-20 20:48:38 +00:00
|
|
|
"Invalid number of indices for unchecked array reference");
|
2017-04-14 20:33:44 +00:00
|
|
|
return *reinterpret_cast<const T *>(data_ + byte_offset_unsafe(strides_, ssize_t(index)...));
|
2017-03-19 04:14:23 +00:00
|
|
|
}
|
2017-05-22 16:06:16 +00:00
|
|
|
/**
|
|
|
|
* Unchecked const reference access to data; this operator only participates if the reference
|
2017-03-19 04:14:23 +00:00
|
|
|
* is to a 1-dimensional array. When present, this is exactly equivalent to `obj(index)`.
|
|
|
|
*/
|
2017-04-14 20:33:44 +00:00
|
|
|
template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
|
|
|
|
const T &operator[](ssize_t index) const { return operator()(index); }
|
2017-03-19 04:14:23 +00:00
|
|
|
|
2017-03-20 20:48:38 +00:00
|
|
|
/// Pointer access to the data at the given indices.
|
2017-04-14 20:33:44 +00:00
|
|
|
template <typename... Ix> const T *data(Ix... ix) const { return &operator()(ssize_t(ix)...); }
|
2017-03-20 20:48:38 +00:00
|
|
|
|
|
|
|
/// Returns the item size, i.e. sizeof(T)
|
2017-04-14 20:33:44 +00:00
|
|
|
constexpr static ssize_t itemsize() { return sizeof(T); }
|
2017-03-20 20:48:38 +00:00
|
|
|
|
2017-03-19 04:14:23 +00:00
|
|
|
/// Returns the shape (i.e. size) of dimension `dim`
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t shape(ssize_t dim) const { return shape_[(size_t) dim]; }
|
2017-03-19 04:14:23 +00:00
|
|
|
|
|
|
|
/// Returns the number of dimensions of the array
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t ndim() const { return dims_; }
|
2017-03-20 20:48:38 +00:00
|
|
|
|
|
|
|
/// Returns the total number of elements in the referenced array, i.e. the product of the shapes
|
|
|
|
template <bool Dyn = Dynamic>
|
2017-04-14 20:33:44 +00:00
|
|
|
enable_if_t<!Dyn, ssize_t> size() const {
|
|
|
|
return std::accumulate(shape_.begin(), shape_.end(), (ssize_t) 1, std::multiplies<ssize_t>());
|
2017-03-20 20:48:38 +00:00
|
|
|
}
|
|
|
|
template <bool Dyn = Dynamic>
|
2017-04-14 20:33:44 +00:00
|
|
|
enable_if_t<Dyn, ssize_t> size() const {
|
|
|
|
return std::accumulate(shape_, shape_ + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
|
2017-03-20 20:48:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the total number of bytes used by the referenced data. Note that the actual span in
|
|
|
|
/// memory may be larger if the referenced array has non-contiguous strides (e.g. for a slice).
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t nbytes() const {
|
2017-03-20 20:48:38 +00:00
|
|
|
return size() * itemsize();
|
|
|
|
}
|
2017-03-19 04:14:23 +00:00
|
|
|
};
|
|
|
|
|
2017-03-20 20:48:38 +00:00
|
|
|
template <typename T, ssize_t Dims>
|
2017-03-19 04:14:23 +00:00
|
|
|
class unchecked_mutable_reference : public unchecked_reference<T, Dims> {
|
|
|
|
friend class pybind11::array;
|
|
|
|
using ConstBase = unchecked_reference<T, Dims>;
|
|
|
|
using ConstBase::ConstBase;
|
2017-03-20 20:48:38 +00:00
|
|
|
using ConstBase::Dynamic;
|
2017-03-19 04:14:23 +00:00
|
|
|
public:
|
|
|
|
/// Mutable, unchecked access to data at the given indices.
|
|
|
|
template <typename... Ix> T& operator()(Ix... index) {
|
2017-08-22 14:37:51 +00:00
|
|
|
static_assert(ssize_t{sizeof...(Ix)} == Dims || Dynamic,
|
2017-03-20 20:48:38 +00:00
|
|
|
"Invalid number of indices for unchecked array reference");
|
2017-03-19 04:14:23 +00:00
|
|
|
return const_cast<T &>(ConstBase::operator()(index...));
|
|
|
|
}
|
2017-05-22 16:06:16 +00:00
|
|
|
/**
|
|
|
|
* Mutable, unchecked access data at the given index; this operator only participates if the
|
2017-03-20 20:48:38 +00:00
|
|
|
* reference is to a 1-dimensional array (or has runtime dimensions). When present, this is
|
|
|
|
* exactly equivalent to `obj(index)`.
|
2017-03-19 04:14:23 +00:00
|
|
|
*/
|
2017-04-14 20:33:44 +00:00
|
|
|
template <ssize_t D = Dims, typename = enable_if_t<D == 1 || Dynamic>>
|
|
|
|
T &operator[](ssize_t index) { return operator()(index); }
|
2017-03-20 20:48:38 +00:00
|
|
|
|
|
|
|
/// Mutable pointer access to the data at the given indices.
|
2017-04-14 20:33:44 +00:00
|
|
|
template <typename... Ix> T *mutable_data(Ix... ix) { return &operator()(ssize_t(ix)...); }
|
2017-03-19 04:14:23 +00:00
|
|
|
};
|
|
|
|
|
2017-03-26 15:43:22 +00:00
|
|
|
template <typename T, ssize_t Dim>
|
2017-03-19 04:14:23 +00:00
|
|
|
struct type_caster<unchecked_reference<T, Dim>> {
|
2017-03-20 20:48:38 +00:00
|
|
|
static_assert(Dim == 0 && Dim > 0 /* always fail */, "unchecked array proxy object is not castable");
|
2017-03-19 04:14:23 +00:00
|
|
|
};
|
2017-03-26 15:43:22 +00:00
|
|
|
template <typename T, ssize_t Dim>
|
2017-03-19 04:14:23 +00:00
|
|
|
struct type_caster<unchecked_mutable_reference<T, Dim>> : type_caster<unchecked_reference<T, Dim>> {};
|
|
|
|
|
2016-11-22 10:29:55 +00:00
|
|
|
NAMESPACE_END(detail)
|
2016-08-29 01:41:05 +00:00
|
|
|
|
2016-07-23 20:55:37 +00:00
|
|
|
class dtype : public object {
|
2016-07-19 23:54:57 +00:00
|
|
|
public:
|
2016-07-23 20:55:37 +00:00
|
|
|
PYBIND11_OBJECT_DEFAULT(dtype, object, detail::npy_api::get().PyArrayDescr_Check_);
|
2015-07-26 14:33:49 +00:00
|
|
|
|
2016-10-16 20:27:42 +00:00
|
|
|
explicit dtype(const buffer_info &info) {
|
2016-08-13 11:42:02 +00:00
|
|
|
dtype descr(_dtype_from_pep3118()(PYBIND11_STR_TYPE(info.format)));
|
2016-11-22 14:56:52 +00:00
|
|
|
// If info.itemsize == 0, use the value calculated from the format string
|
|
|
|
m_ptr = descr.strip_padding(info.itemsize ? info.itemsize : descr.itemsize()).release().ptr();
|
2016-07-23 20:55:37 +00:00
|
|
|
}
|
2016-05-05 08:00:00 +00:00
|
|
|
|
2016-10-22 09:50:39 +00:00
|
|
|
explicit dtype(const std::string &format) {
|
2016-07-23 20:55:37 +00:00
|
|
|
m_ptr = from_args(pybind11::str(format)).release().ptr();
|
2015-07-26 14:33:49 +00:00
|
|
|
}
|
|
|
|
|
2016-10-22 09:51:19 +00:00
|
|
|
dtype(const char *format) : dtype(std::string(format)) { }
|
2016-07-24 23:58:17 +00:00
|
|
|
|
2017-04-14 20:33:44 +00:00
|
|
|
dtype(list names, list formats, list offsets, ssize_t itemsize) {
|
2016-07-24 16:51:35 +00:00
|
|
|
dict args;
|
|
|
|
args["names"] = names;
|
|
|
|
args["formats"] = formats;
|
|
|
|
args["offsets"] = offsets;
|
2016-08-25 00:16:47 +00:00
|
|
|
args["itemsize"] = pybind11::int_(itemsize);
|
2016-07-24 16:51:35 +00:00
|
|
|
m_ptr = from_args(args).release().ptr();
|
|
|
|
}
|
|
|
|
|
2016-10-22 09:51:04 +00:00
|
|
|
/// This is essentially the same as calling numpy.dtype(args) in Python.
|
2016-07-23 20:55:37 +00:00
|
|
|
static dtype from_args(object args) {
|
|
|
|
PyObject *ptr = nullptr;
|
2017-09-20 01:12:46 +00:00
|
|
|
if (!detail::npy_api::get().PyArray_DescrConverter_(args.ptr(), &ptr) || !ptr)
|
2016-10-22 09:52:05 +00:00
|
|
|
throw error_already_set();
|
2016-10-28 01:08:15 +00:00
|
|
|
return reinterpret_steal<dtype>(ptr);
|
2016-07-23 20:55:37 +00:00
|
|
|
}
|
2016-07-05 23:28:12 +00:00
|
|
|
|
2016-10-22 09:51:04 +00:00
|
|
|
/// Return dtype associated with a C++ type.
|
2016-07-23 20:55:37 +00:00
|
|
|
template <typename T> static dtype of() {
|
2016-08-15 00:24:28 +00:00
|
|
|
return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::dtype();
|
2016-07-23 20:55:37 +00:00
|
|
|
}
|
2016-07-05 23:28:12 +00:00
|
|
|
|
2016-10-22 09:51:04 +00:00
|
|
|
/// Size of the data type in bytes.
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t itemsize() const {
|
|
|
|
return detail::array_descriptor_proxy(m_ptr)->elsize;
|
2015-07-26 14:33:49 +00:00
|
|
|
}
|
|
|
|
|
2016-10-22 09:51:04 +00:00
|
|
|
/// Returns true for structured data types.
|
2016-07-23 20:55:37 +00:00
|
|
|
bool has_fields() const {
|
2016-11-22 10:29:55 +00:00
|
|
|
return detail::array_descriptor_proxy(m_ptr)->names != nullptr;
|
2016-07-23 20:55:37 +00:00
|
|
|
}
|
|
|
|
|
2016-10-22 09:51:04 +00:00
|
|
|
/// Single-character type code.
|
2016-08-29 01:41:05 +00:00
|
|
|
char kind() const {
|
2016-11-22 10:29:55 +00:00
|
|
|
return detail::array_descriptor_proxy(m_ptr)->kind;
|
2016-07-23 20:55:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2016-07-24 16:34:53 +00:00
|
|
|
static object _dtype_from_pep3118() {
|
|
|
|
static PyObject *obj = module::import("numpy.core._internal")
|
|
|
|
.attr("_dtype_from_pep3118").cast<object>().release().ptr();
|
2016-10-28 01:08:15 +00:00
|
|
|
return reinterpret_borrow<object>(obj);
|
2016-07-23 20:55:37 +00:00
|
|
|
}
|
2016-07-05 23:28:12 +00:00
|
|
|
|
2017-04-14 20:33:44 +00:00
|
|
|
dtype strip_padding(ssize_t itemsize) {
|
2016-07-05 23:28:12 +00:00
|
|
|
// Recursively strip all void fields with empty names that are generated for
|
|
|
|
// padding fields (as of NumPy v1.11).
|
2016-08-29 01:41:05 +00:00
|
|
|
if (!has_fields())
|
2016-07-23 20:55:37 +00:00
|
|
|
return *this;
|
2016-07-05 23:28:12 +00:00
|
|
|
|
2016-08-25 00:16:47 +00:00
|
|
|
struct field_descr { PYBIND11_STR_TYPE name; object format; pybind11::int_ offset; };
|
2016-07-05 23:28:12 +00:00
|
|
|
std::vector<field_descr> field_descriptors;
|
|
|
|
|
2016-09-08 15:02:04 +00:00
|
|
|
for (auto field : attr("fields").attr("items")()) {
|
2016-10-28 01:08:15 +00:00
|
|
|
auto spec = field.cast<tuple>();
|
2016-07-05 23:28:12 +00:00
|
|
|
auto name = spec[0].cast<pybind11::str>();
|
2016-07-23 20:55:37 +00:00
|
|
|
auto format = spec[1].cast<tuple>()[0].cast<dtype>();
|
2016-08-25 00:16:47 +00:00
|
|
|
auto offset = spec[1].cast<tuple>()[1].cast<pybind11::int_>();
|
2016-08-29 01:41:05 +00:00
|
|
|
if (!len(name) && format.kind() == 'V')
|
2016-07-18 21:37:42 +00:00
|
|
|
continue;
|
2016-11-22 14:56:52 +00:00
|
|
|
field_descriptors.push_back({(PYBIND11_STR_TYPE) name, format.strip_padding(format.itemsize()), offset});
|
2016-07-05 23:28:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
std::sort(field_descriptors.begin(), field_descriptors.end(),
|
|
|
|
[](const field_descr& a, const field_descr& b) {
|
2016-08-25 20:52:52 +00:00
|
|
|
return a.offset.cast<int>() < b.offset.cast<int>();
|
2016-07-05 23:28:12 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
list names, formats, offsets;
|
|
|
|
for (auto& descr : field_descriptors) {
|
2016-07-24 16:51:35 +00:00
|
|
|
names.append(descr.name);
|
|
|
|
formats.append(descr.format);
|
|
|
|
offsets.append(descr.offset);
|
2016-07-05 23:28:12 +00:00
|
|
|
}
|
2016-11-22 14:56:52 +00:00
|
|
|
return dtype(names, formats, offsets, itemsize);
|
2016-07-23 20:55:37 +00:00
|
|
|
}
|
|
|
|
};
|
2016-07-05 23:28:12 +00:00
|
|
|
|
2016-07-23 20:55:37 +00:00
|
|
|
class array : public buffer {
|
|
|
|
public:
|
2016-11-16 00:35:22 +00:00
|
|
|
PYBIND11_OBJECT_CVT(array, buffer, detail::npy_api::get().PyArray_Check_, raw_array)
|
2016-07-23 20:55:37 +00:00
|
|
|
|
|
|
|
enum {
|
2017-01-17 01:15:42 +00:00
|
|
|
c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,
|
|
|
|
f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,
|
2016-07-23 20:55:37 +00:00
|
|
|
forcecast = detail::npy_api::NPY_ARRAY_FORCECAST_
|
|
|
|
};
|
|
|
|
|
2017-04-28 15:06:16 +00:00
|
|
|
array() : array({{0}}, static_cast<const double *>(nullptr)) {}
|
2016-11-16 00:35:22 +00:00
|
|
|
|
2017-05-20 15:21:19 +00:00
|
|
|
using ShapeContainer = detail::any_container<ssize_t>;
|
|
|
|
using StridesContainer = detail::any_container<ssize_t>;
|
2017-04-07 19:49:54 +00:00
|
|
|
|
|
|
|
// Constructs an array taking shape/strides from arbitrary container types
|
|
|
|
array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides,
|
|
|
|
const void *ptr = nullptr, handle base = handle()) {
|
|
|
|
|
|
|
|
if (strides->empty())
|
2017-03-27 14:03:16 +00:00
|
|
|
*strides = c_strides(*shape, dt.itemsize());
|
2017-04-07 19:49:54 +00:00
|
|
|
|
|
|
|
auto ndim = shape->size();
|
|
|
|
if (ndim != strides->size())
|
2016-07-24 17:35:14 +00:00
|
|
|
pybind11_fail("NumPy: shape ndim doesn't match strides ndim");
|
|
|
|
auto descr = dt;
|
2016-10-12 22:57:42 +00:00
|
|
|
|
|
|
|
int flags = 0;
|
|
|
|
if (base && ptr) {
|
2016-10-23 12:50:08 +00:00
|
|
|
if (isinstance<array>(base))
|
2017-02-06 23:06:04 +00:00
|
|
|
/* Copy flags from base (except ownership bit) */
|
2016-10-28 01:08:15 +00:00
|
|
|
flags = reinterpret_borrow<array>(base).flags() & ~detail::npy_api::NPY_ARRAY_OWNDATA_;
|
2016-10-12 22:57:42 +00:00
|
|
|
else
|
|
|
|
/* Writable by default, easy to downgrade later on if needed */
|
|
|
|
flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
|
|
|
|
}
|
|
|
|
|
2017-04-07 19:49:54 +00:00
|
|
|
auto &api = detail::npy_api::get();
|
2016-10-28 01:08:15 +00:00
|
|
|
auto tmp = reinterpret_steal<object>(api.PyArray_NewFromDescr_(
|
2017-04-07 19:49:54 +00:00
|
|
|
api.PyArray_Type_, descr.release().ptr(), (int) ndim, shape->data(), strides->data(),
|
2017-02-08 22:43:08 +00:00
|
|
|
const_cast<void *>(ptr), flags, nullptr));
|
2016-07-23 20:55:37 +00:00
|
|
|
if (!tmp)
|
2017-04-14 20:33:44 +00:00
|
|
|
throw error_already_set();
|
2016-10-12 22:57:42 +00:00
|
|
|
if (ptr) {
|
|
|
|
if (base) {
|
2017-01-17 01:22:00 +00:00
|
|
|
api.PyArray_SetBaseObject_(tmp.ptr(), base.inc_ref().ptr());
|
2016-10-12 22:57:42 +00:00
|
|
|
} else {
|
2016-10-28 01:08:15 +00:00
|
|
|
tmp = reinterpret_steal<object>(api.PyArray_NewCopy_(tmp.ptr(), -1 /* any order */));
|
2016-10-12 22:57:42 +00:00
|
|
|
}
|
|
|
|
}
|
2016-07-23 20:55:37 +00:00
|
|
|
m_ptr = tmp.release().ptr();
|
|
|
|
}
|
|
|
|
|
2017-04-07 19:49:54 +00:00
|
|
|
array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr = nullptr, handle base = handle())
|
|
|
|
: array(dt, std::move(shape), {}, ptr, base) { }
|
2016-07-24 17:35:14 +00:00
|
|
|
|
2017-04-28 15:06:16 +00:00
|
|
|
template <typename T, typename = detail::enable_if_t<std::is_integral<T>::value && !std::is_same<bool, T>::value>>
|
|
|
|
array(const pybind11::dtype &dt, T count, const void *ptr = nullptr, handle base = handle())
|
|
|
|
: array(dt, {{count}}, ptr, base) { }
|
2016-07-24 17:35:14 +00:00
|
|
|
|
2017-04-07 19:49:54 +00:00
|
|
|
template <typename T>
|
|
|
|
array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base = handle())
|
|
|
|
: array(pybind11::dtype::of<T>(), std::move(shape), std::move(strides), ptr, base) { }
|
2016-07-24 17:35:14 +00:00
|
|
|
|
2016-10-12 22:57:42 +00:00
|
|
|
template <typename T>
|
2017-04-07 19:49:54 +00:00
|
|
|
array(ShapeContainer shape, const T *ptr, handle base = handle())
|
|
|
|
: array(std::move(shape), {}, ptr, base) { }
|
2016-07-24 17:35:14 +00:00
|
|
|
|
2017-04-28 15:06:16 +00:00
|
|
|
template <typename T>
|
2017-04-14 20:33:44 +00:00
|
|
|
explicit array(ssize_t count, const T *ptr, handle base = handle()) : array({count}, {}, ptr, base) { }
|
2017-04-28 15:06:16 +00:00
|
|
|
|
2016-10-16 20:27:42 +00:00
|
|
|
explicit array(const buffer_info &info)
|
2016-07-24 23:46:39 +00:00
|
|
|
: array(pybind11::dtype(info), info.shape, info.strides, info.ptr) { }
|
2016-07-23 20:55:37 +00:00
|
|
|
|
2016-08-29 01:41:05 +00:00
|
|
|
/// Array descriptor (dtype)
|
|
|
|
pybind11::dtype dtype() const {
|
2016-11-22 10:29:55 +00:00
|
|
|
return reinterpret_borrow<pybind11::dtype>(detail::array_proxy(m_ptr)->descr);
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Total number of elements
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t size() const {
|
|
|
|
return std::accumulate(shape(), shape() + ndim(), (ssize_t) 1, std::multiplies<ssize_t>());
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Byte size of a single element
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t itemsize() const {
|
|
|
|
return detail::array_descriptor_proxy(detail::array_proxy(m_ptr)->descr)->elsize;
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Total number of bytes
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t nbytes() const {
|
2016-08-29 01:41:05 +00:00
|
|
|
return size() * itemsize();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Number of dimensions
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t ndim() const {
|
|
|
|
return detail::array_proxy(m_ptr)->nd;
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
2016-10-12 22:57:42 +00:00
|
|
|
/// Base object
|
|
|
|
object base() const {
|
2016-11-22 10:29:55 +00:00
|
|
|
return reinterpret_borrow<object>(detail::array_proxy(m_ptr)->base);
|
2016-10-12 22:57:42 +00:00
|
|
|
}
|
|
|
|
|
2016-08-29 01:41:05 +00:00
|
|
|
/// Dimensions of the array
|
2017-04-14 20:33:44 +00:00
|
|
|
const ssize_t* shape() const {
|
|
|
|
return detail::array_proxy(m_ptr)->dimensions;
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Dimension along a given axis
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t shape(ssize_t dim) const {
|
2016-08-29 01:41:05 +00:00
|
|
|
if (dim >= ndim())
|
2016-09-08 20:48:14 +00:00
|
|
|
fail_dim_check(dim, "invalid axis");
|
2016-08-29 01:41:05 +00:00
|
|
|
return shape()[dim];
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Strides of the array
|
2017-04-05 22:13:04 +00:00
|
|
|
const ssize_t* strides() const {
|
2017-04-14 20:33:44 +00:00
|
|
|
return detail::array_proxy(m_ptr)->strides;
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Stride along a given axis
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t strides(ssize_t dim) const {
|
2016-08-29 01:41:05 +00:00
|
|
|
if (dim >= ndim())
|
2016-09-08 20:48:14 +00:00
|
|
|
fail_dim_check(dim, "invalid axis");
|
2016-08-29 01:41:05 +00:00
|
|
|
return strides()[dim];
|
|
|
|
}
|
|
|
|
|
2016-10-12 22:57:42 +00:00
|
|
|
/// Return the NumPy array flags
|
|
|
|
int flags() const {
|
2016-11-22 10:29:55 +00:00
|
|
|
return detail::array_proxy(m_ptr)->flags;
|
2016-10-12 22:57:42 +00:00
|
|
|
}
|
|
|
|
|
2016-08-29 01:41:05 +00:00
|
|
|
/// If set, the array is writeable (otherwise the buffer is read-only)
|
|
|
|
bool writeable() const {
|
2016-11-22 10:29:55 +00:00
|
|
|
return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_WRITEABLE_);
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// If set, the array owns the data (will be freed when the array is deleted)
|
|
|
|
bool owndata() const {
|
2016-11-22 10:29:55 +00:00
|
|
|
return detail::check_flags(m_ptr, detail::npy_api::NPY_ARRAY_OWNDATA_);
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
2016-09-08 20:48:14 +00:00
|
|
|
/// Pointer to the contained data. If index is not provided, points to the
|
|
|
|
/// beginning of the buffer. May throw if the index would lead to out of bounds access.
|
2016-11-16 16:53:37 +00:00
|
|
|
template<typename... Ix> const void* data(Ix... index) const {
|
2016-11-22 10:29:55 +00:00
|
|
|
return static_cast<const void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
2016-09-08 20:48:14 +00:00
|
|
|
/// Mutable pointer to the contained data. If index is not provided, points to the
|
|
|
|
/// beginning of the buffer. May throw if the index would lead to out of bounds access.
|
|
|
|
/// May throw if the array is not writeable.
|
2016-11-16 16:53:37 +00:00
|
|
|
template<typename... Ix> void* mutable_data(Ix... index) {
|
2016-09-08 20:48:14 +00:00
|
|
|
check_writeable();
|
2016-11-22 10:29:55 +00:00
|
|
|
return static_cast<void *>(detail::array_proxy(m_ptr)->data + offset_at(index...));
|
2016-09-08 20:48:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Byte offset from beginning of the array to a given index (full or partial).
|
|
|
|
/// May throw if the index would lead to out of bounds access.
|
2017-04-06 17:34:39 +00:00
|
|
|
template<typename... Ix> ssize_t offset_at(Ix... index) const {
|
2017-04-14 20:33:44 +00:00
|
|
|
if ((ssize_t) sizeof...(index) > ndim())
|
2016-09-08 20:48:14 +00:00
|
|
|
fail_dim_check(sizeof...(index), "too many indices for an array");
|
2017-04-14 20:33:44 +00:00
|
|
|
return byte_offset(ssize_t(index)...);
|
2016-09-08 20:48:14 +00:00
|
|
|
}
|
|
|
|
|
2017-04-06 17:34:39 +00:00
|
|
|
ssize_t offset_at() const { return 0; }
|
2016-09-08 20:48:14 +00:00
|
|
|
|
|
|
|
/// Item count from beginning of the array to a given index (full or partial).
|
|
|
|
/// May throw if the index would lead to out of bounds access.
|
2017-04-06 17:34:39 +00:00
|
|
|
template<typename... Ix> ssize_t index_at(Ix... index) const {
|
2017-04-14 20:33:44 +00:00
|
|
|
return offset_at(index...) / itemsize();
|
2016-07-23 20:55:37 +00:00
|
|
|
}
|
|
|
|
|
2017-05-22 16:06:16 +00:00
|
|
|
/**
|
|
|
|
* Returns a proxy object that provides access to the array's data without bounds or
|
2017-03-19 04:14:23 +00:00
|
|
|
* dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
|
|
|
|
* care: the array must not be destroyed or reshaped for the duration of the returned object,
|
|
|
|
* and the caller must take care not to access invalid dimensions or dimension indices.
|
|
|
|
*/
|
2017-07-25 20:22:45 +00:00
|
|
|
template <typename T, ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
|
2017-04-14 20:33:44 +00:00
|
|
|
if (Dims >= 0 && ndim() != Dims)
|
2017-03-19 04:14:23 +00:00
|
|
|
throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
|
|
|
|
"; expected " + std::to_string(Dims));
|
2017-03-20 20:48:38 +00:00
|
|
|
return detail::unchecked_mutable_reference<T, Dims>(mutable_data(), shape(), strides(), ndim());
|
2017-03-19 04:14:23 +00:00
|
|
|
}
|
|
|
|
|
2017-05-22 16:06:16 +00:00
|
|
|
/**
|
|
|
|
* Returns a proxy object that provides const access to the array's data without bounds or
|
2017-03-19 04:14:23 +00:00
|
|
|
* dimensionality checking. Unlike `mutable_unchecked()`, this does not require that the
|
|
|
|
* underlying array have the `writable` flag. Use with care: the array must not be destroyed or
|
|
|
|
* reshaped for the duration of the returned object, and the caller must take care not to access
|
|
|
|
* invalid dimensions or dimension indices.
|
|
|
|
*/
|
2017-07-25 20:22:45 +00:00
|
|
|
template <typename T, ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
|
2017-04-14 20:33:44 +00:00
|
|
|
if (Dims >= 0 && ndim() != Dims)
|
2017-03-19 04:14:23 +00:00
|
|
|
throw std::domain_error("array has incorrect number of dimensions: " + std::to_string(ndim()) +
|
|
|
|
"; expected " + std::to_string(Dims));
|
2017-03-20 20:48:38 +00:00
|
|
|
return detail::unchecked_reference<T, Dims>(data(), shape(), strides(), ndim());
|
2017-03-19 04:14:23 +00:00
|
|
|
}
|
|
|
|
|
2016-10-07 09:19:25 +00:00
|
|
|
/// Return a new view with all of the dimensions of length 1 removed
|
|
|
|
array squeeze() {
|
|
|
|
auto& api = detail::npy_api::get();
|
2016-10-28 01:08:15 +00:00
|
|
|
return reinterpret_steal<array>(api.PyArray_Squeeze_(m_ptr));
|
2016-10-07 09:19:25 +00:00
|
|
|
}
|
|
|
|
|
2017-04-13 16:41:55 +00:00
|
|
|
/// Resize array to given shape
|
|
|
|
/// If refcheck is true and more that one reference exist to this array
|
|
|
|
/// then resize will succeed only if it makes a reshape, i.e. original size doesn't change
|
|
|
|
void resize(ShapeContainer new_shape, bool refcheck = true) {
|
|
|
|
detail::npy_api::PyArray_Dims d = {
|
|
|
|
new_shape->data(), int(new_shape->size())
|
|
|
|
};
|
|
|
|
// try to resize, set ordering param to -1 cause it's not used anyway
|
|
|
|
object new_array = reinterpret_steal<object>(
|
|
|
|
detail::npy_api::get().PyArray_Resize_(m_ptr, &d, int(refcheck), -1)
|
|
|
|
);
|
|
|
|
if (!new_array) throw error_already_set();
|
|
|
|
if (isinstance<array>(new_array)) { *this = std::move(new_array); }
|
|
|
|
}
|
|
|
|
|
2016-10-13 23:08:03 +00:00
|
|
|
/// Ensure that the argument is a NumPy array
|
2016-11-16 00:35:22 +00:00
|
|
|
/// In case of an error, nullptr is returned and the Python error is cleared.
|
|
|
|
static array ensure(handle h, int ExtraFlags = 0) {
|
|
|
|
auto result = reinterpret_steal<array>(raw_array(h.ptr(), ExtraFlags));
|
|
|
|
if (!result)
|
|
|
|
PyErr_Clear();
|
|
|
|
return result;
|
2016-10-13 23:08:03 +00:00
|
|
|
}
|
|
|
|
|
2016-07-23 20:55:37 +00:00
|
|
|
protected:
|
2016-09-08 20:48:14 +00:00
|
|
|
template<typename, typename> friend struct detail::npy_format_descriptor;
|
|
|
|
|
2017-04-14 20:33:44 +00:00
|
|
|
void fail_dim_check(ssize_t dim, const std::string& msg) const {
|
2016-09-08 20:48:14 +00:00
|
|
|
throw index_error(msg + ": " + std::to_string(dim) +
|
|
|
|
" (ndim = " + std::to_string(ndim()) + ")");
|
|
|
|
}
|
|
|
|
|
2017-04-06 17:34:39 +00:00
|
|
|
template<typename... Ix> ssize_t byte_offset(Ix... index) const {
|
2016-11-16 16:53:37 +00:00
|
|
|
check_dimensions(index...);
|
2017-04-14 20:33:44 +00:00
|
|
|
return detail::byte_offset_unsafe(strides(), ssize_t(index)...);
|
2016-11-16 16:53:37 +00:00
|
|
|
}
|
|
|
|
|
2016-09-08 20:48:14 +00:00
|
|
|
void check_writeable() const {
|
|
|
|
if (!writeable())
|
2017-01-20 18:50:07 +00:00
|
|
|
throw std::domain_error("array is not writeable");
|
2016-09-08 20:48:14 +00:00
|
|
|
}
|
2016-07-24 17:35:14 +00:00
|
|
|
|
2017-03-27 14:03:16 +00:00
|
|
|
// Default, C-style strides
|
|
|
|
static std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
|
2016-07-24 17:35:14 +00:00
|
|
|
auto ndim = shape.size();
|
2017-03-27 14:03:16 +00:00
|
|
|
std::vector<ssize_t> strides(ndim, itemsize);
|
2018-05-06 13:59:25 +00:00
|
|
|
if (ndim > 0)
|
|
|
|
for (size_t i = ndim - 1; i > 0; --i)
|
|
|
|
strides[i - 1] = strides[i] * shape[i];
|
2017-03-27 14:03:16 +00:00
|
|
|
return strides;
|
|
|
|
}
|
|
|
|
|
|
|
|
// F-style strides; default when constructing an array_t with `ExtraFlags & f_style`
|
|
|
|
static std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
|
|
|
|
auto ndim = shape.size();
|
|
|
|
std::vector<ssize_t> strides(ndim, itemsize);
|
|
|
|
for (size_t i = 1; i < ndim; ++i)
|
|
|
|
strides[i] = strides[i - 1] * shape[i - 1];
|
2016-07-24 17:35:14 +00:00
|
|
|
return strides;
|
|
|
|
}
|
2016-11-16 16:53:37 +00:00
|
|
|
|
|
|
|
template<typename... Ix> void check_dimensions(Ix... index) const {
|
2017-04-14 20:33:44 +00:00
|
|
|
check_dimensions_impl(ssize_t(0), shape(), ssize_t(index)...);
|
2016-11-16 16:53:37 +00:00
|
|
|
}
|
|
|
|
|
2017-04-14 20:33:44 +00:00
|
|
|
void check_dimensions_impl(ssize_t, const ssize_t*) const { }
|
2016-11-16 16:53:37 +00:00
|
|
|
|
2017-04-14 20:33:44 +00:00
|
|
|
template<typename... Ix> void check_dimensions_impl(ssize_t axis, const ssize_t* shape, ssize_t i, Ix... index) const {
|
2016-11-16 16:53:37 +00:00
|
|
|
if (i >= *shape) {
|
|
|
|
throw index_error(std::string("index ") + std::to_string(i) +
|
|
|
|
" is out of bounds for axis " + std::to_string(axis) +
|
|
|
|
" with size " + std::to_string(*shape));
|
|
|
|
}
|
|
|
|
check_dimensions_impl(axis + 1, shape + 1, index...);
|
|
|
|
}
|
2016-11-16 00:35:22 +00:00
|
|
|
|
|
|
|
/// Create array from any object -- always returns a new reference
|
|
|
|
static PyObject *raw_array(PyObject *ptr, int ExtraFlags = 0) {
|
2017-04-10 15:05:26 +00:00
|
|
|
if (ptr == nullptr) {
|
|
|
|
PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array from a nullptr");
|
2016-11-16 00:35:22 +00:00
|
|
|
return nullptr;
|
2017-04-10 15:05:26 +00:00
|
|
|
}
|
2016-11-16 00:35:22 +00:00
|
|
|
return detail::npy_api::get().PyArray_FromAny_(
|
2017-01-17 01:15:42 +00:00
|
|
|
ptr, nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
|
2016-11-16 00:35:22 +00:00
|
|
|
}
|
2015-07-26 14:33:49 +00:00
|
|
|
};
|
|
|
|
|
2016-05-19 14:02:09 +00:00
|
|
|
template <typename T, int ExtraFlags = array::forcecast> class array_t : public array {
|
2017-03-27 14:03:16 +00:00
|
|
|
private:
|
|
|
|
struct private_ctor {};
|
|
|
|
// Delegating constructor needed when both moving and accessing in the same constructor
|
|
|
|
array_t(private_ctor, ShapeContainer &&shape, StridesContainer &&strides, const T *ptr, handle base)
|
|
|
|
: array(std::move(shape), std::move(strides), ptr, base) {}
|
2015-07-26 14:33:49 +00:00
|
|
|
public:
|
2017-05-10 08:21:01 +00:00
|
|
|
static_assert(!detail::array_info<T>::is_array, "Array types cannot be used with array_t");
|
|
|
|
|
2017-03-13 18:17:18 +00:00
|
|
|
using value_type = T;
|
|
|
|
|
2016-11-16 00:35:22 +00:00
|
|
|
array_t() : array(0, static_cast<const T *>(nullptr)) {}
|
2017-03-28 22:23:37 +00:00
|
|
|
array_t(handle h, borrowed_t) : array(h, borrowed_t{}) { }
|
|
|
|
array_t(handle h, stolen_t) : array(h, stolen_t{}) { }
|
2016-07-24 17:54:53 +00:00
|
|
|
|
2016-11-16 00:35:22 +00:00
|
|
|
PYBIND11_DEPRECATED("Use array_t<T>::ensure() instead")
|
2017-03-28 22:23:37 +00:00
|
|
|
array_t(handle h, bool is_borrowed) : array(raw_array_t(h.ptr()), stolen_t{}) {
|
2016-11-16 00:35:22 +00:00
|
|
|
if (!m_ptr) PyErr_Clear();
|
|
|
|
if (!is_borrowed) Py_XDECREF(h.ptr());
|
|
|
|
}
|
2016-10-25 20:12:39 +00:00
|
|
|
|
2017-03-28 22:23:37 +00:00
|
|
|
array_t(const object &o) : array(raw_array_t(o.ptr()), stolen_t{}) {
|
2016-11-16 00:35:22 +00:00
|
|
|
if (!m_ptr) throw error_already_set();
|
|
|
|
}
|
2016-10-25 20:12:39 +00:00
|
|
|
|
2016-10-16 20:27:42 +00:00
|
|
|
explicit array_t(const buffer_info& info) : array(info) { }
|
2016-07-24 17:54:53 +00:00
|
|
|
|
2017-04-07 19:49:54 +00:00
|
|
|
array_t(ShapeContainer shape, StridesContainer strides, const T *ptr = nullptr, handle base = handle())
|
|
|
|
: array(std::move(shape), std::move(strides), ptr, base) { }
|
2016-07-24 17:54:53 +00:00
|
|
|
|
2017-04-07 19:49:54 +00:00
|
|
|
explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
|
2017-03-27 14:03:16 +00:00
|
|
|
: array_t(private_ctor{}, std::move(shape),
|
|
|
|
ExtraFlags & f_style ? f_strides(*shape, itemsize()) : c_strides(*shape, itemsize()),
|
|
|
|
ptr, base) { }
|
2016-07-24 17:54:53 +00:00
|
|
|
|
2017-04-28 15:06:16 +00:00
|
|
|
explicit array_t(size_t count, const T *ptr = nullptr, handle base = handle())
|
|
|
|
: array({count}, {}, ptr, base) { }
|
|
|
|
|
2017-04-14 20:33:44 +00:00
|
|
|
constexpr ssize_t itemsize() const {
|
2016-09-08 20:48:14 +00:00
|
|
|
return sizeof(T);
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
|
|
|
|
2017-04-06 17:34:39 +00:00
|
|
|
template<typename... Ix> ssize_t index_at(Ix... index) const {
|
2017-04-14 20:33:44 +00:00
|
|
|
return offset_at(index...) / itemsize();
|
2016-09-08 20:48:14 +00:00
|
|
|
}
|
|
|
|
|
2016-11-16 16:53:37 +00:00
|
|
|
template<typename... Ix> const T* data(Ix... index) const {
|
2016-09-08 20:48:14 +00:00
|
|
|
return static_cast<const T*>(array::data(index...));
|
|
|
|
}
|
|
|
|
|
2016-11-16 16:53:37 +00:00
|
|
|
template<typename... Ix> T* mutable_data(Ix... index) {
|
2016-09-08 20:48:14 +00:00
|
|
|
return static_cast<T*>(array::mutable_data(index...));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reference to element at a given index
|
2016-11-16 16:53:37 +00:00
|
|
|
template<typename... Ix> const T& at(Ix... index) const {
|
2019-04-07 08:38:10 +00:00
|
|
|
if ((ssize_t) sizeof...(index) != ndim())
|
2016-09-08 20:48:14 +00:00
|
|
|
fail_dim_check(sizeof...(index), "index dimension mismatch");
|
2017-04-14 20:33:44 +00:00
|
|
|
return *(static_cast<const T*>(array::data()) + byte_offset(ssize_t(index)...) / itemsize());
|
2016-09-08 20:48:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Mutable reference to element at a given index
|
2016-11-16 16:53:37 +00:00
|
|
|
template<typename... Ix> T& mutable_at(Ix... index) {
|
2019-04-07 08:38:10 +00:00
|
|
|
if ((ssize_t) sizeof...(index) != ndim())
|
2016-09-08 20:48:14 +00:00
|
|
|
fail_dim_check(sizeof...(index), "index dimension mismatch");
|
2017-04-14 20:33:44 +00:00
|
|
|
return *(static_cast<T*>(array::mutable_data()) + byte_offset(ssize_t(index)...) / itemsize());
|
2016-08-29 01:41:05 +00:00
|
|
|
}
|
2016-07-24 17:54:53 +00:00
|
|
|
|
2017-05-22 16:06:16 +00:00
|
|
|
/**
|
|
|
|
* Returns a proxy object that provides access to the array's data without bounds or
|
2017-03-19 04:14:23 +00:00
|
|
|
* dimensionality checking. Will throw if the array is missing the `writeable` flag. Use with
|
|
|
|
* care: the array must not be destroyed or reshaped for the duration of the returned object,
|
|
|
|
* and the caller must take care not to access invalid dimensions or dimension indices.
|
|
|
|
*/
|
2017-07-25 20:22:45 +00:00
|
|
|
template <ssize_t Dims = -1> detail::unchecked_mutable_reference<T, Dims> mutable_unchecked() & {
|
2017-03-19 04:14:23 +00:00
|
|
|
return array::mutable_unchecked<T, Dims>();
|
|
|
|
}
|
|
|
|
|
2017-05-22 16:06:16 +00:00
|
|
|
/**
|
|
|
|
* Returns a proxy object that provides const access to the array's data without bounds or
|
2017-03-19 04:14:23 +00:00
|
|
|
* dimensionality checking. Unlike `unchecked()`, this does not require that the underlying
|
|
|
|
* array have the `writable` flag. Use with care: the array must not be destroyed or reshaped
|
|
|
|
* for the duration of the returned object, and the caller must take care not to access invalid
|
|
|
|
* dimensions or dimension indices.
|
|
|
|
*/
|
2017-07-25 20:22:45 +00:00
|
|
|
template <ssize_t Dims = -1> detail::unchecked_reference<T, Dims> unchecked() const & {
|
2017-03-19 04:14:23 +00:00
|
|
|
return array::unchecked<T, Dims>();
|
|
|
|
}
|
|
|
|
|
2017-01-17 01:22:00 +00:00
|
|
|
/// Ensure that the argument is a NumPy array of the correct dtype (and if not, try to convert
|
|
|
|
/// it). In case of an error, nullptr is returned and the Python error is cleared.
|
2016-11-16 00:35:22 +00:00
|
|
|
static array_t ensure(handle h) {
|
|
|
|
auto result = reinterpret_steal<array_t>(raw_array_t(h.ptr()));
|
2016-05-19 14:02:09 +00:00
|
|
|
if (!result)
|
|
|
|
PyErr_Clear();
|
2016-01-17 21:36:41 +00:00
|
|
|
return result;
|
2015-07-26 14:33:49 +00:00
|
|
|
}
|
2016-11-16 00:35:22 +00:00
|
|
|
|
2017-02-06 23:06:04 +00:00
|
|
|
static bool check_(handle h) {
|
2016-11-16 00:35:22 +00:00
|
|
|
const auto &api = detail::npy_api::get();
|
|
|
|
return api.PyArray_Check_(h.ptr())
|
2016-11-22 10:29:55 +00:00
|
|
|
&& api.PyArray_EquivTypes_(detail::array_proxy(h.ptr())->descr, dtype::of<T>().ptr());
|
2016-11-16 00:35:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
protected:
|
|
|
|
/// Create array from any object -- always returns a new reference
|
|
|
|
static PyObject *raw_array_t(PyObject *ptr) {
|
2017-04-10 15:05:26 +00:00
|
|
|
if (ptr == nullptr) {
|
|
|
|
PyErr_SetString(PyExc_ValueError, "cannot create a pybind11::array_t from a nullptr");
|
2016-11-16 00:35:22 +00:00
|
|
|
return nullptr;
|
2017-04-10 15:05:26 +00:00
|
|
|
}
|
2016-11-16 00:35:22 +00:00
|
|
|
return detail::npy_api::get().PyArray_FromAny_(
|
|
|
|
ptr, dtype::of<T>().release().ptr(), 0, 0,
|
2017-01-17 01:15:42 +00:00
|
|
|
detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags, nullptr);
|
2016-11-16 00:35:22 +00:00
|
|
|
}
|
2015-07-26 14:33:49 +00:00
|
|
|
};
|
|
|
|
|
2016-06-26 15:46:40 +00:00
|
|
|
template <typename T>
|
2016-09-12 15:36:43 +00:00
|
|
|
struct format_descriptor<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
|
2016-08-15 00:24:28 +00:00
|
|
|
static std::string format() {
|
|
|
|
return detail::npy_format_descriptor<typename std::remove_cv<T>::type>::format();
|
|
|
|
}
|
2016-07-19 23:19:24 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
template <size_t N> struct format_descriptor<char[N]> {
|
2016-08-14 12:45:49 +00:00
|
|
|
static std::string format() { return std::to_string(N) + "s"; }
|
2016-07-19 23:19:24 +00:00
|
|
|
};
|
|
|
|
template <size_t N> struct format_descriptor<std::array<char, N>> {
|
2016-08-14 12:45:49 +00:00
|
|
|
static std::string format() { return std::to_string(N) + "s"; }
|
2016-06-19 14:48:55 +00:00
|
|
|
};
|
|
|
|
|
2016-10-20 11:28:08 +00:00
|
|
|
template <typename T>
|
|
|
|
struct format_descriptor<T, detail::enable_if_t<std::is_enum<T>::value>> {
|
|
|
|
static std::string format() {
|
|
|
|
return format_descriptor<
|
|
|
|
typename std::remove_cv<typename std::underlying_type<T>::type>::type>::format();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2017-05-10 08:21:01 +00:00
|
|
|
template <typename T>
|
|
|
|
struct format_descriptor<T, detail::enable_if_t<detail::array_info<T>::is_array>> {
|
|
|
|
static std::string format() {
|
2018-01-12 16:37:54 +00:00
|
|
|
using namespace detail;
|
|
|
|
static constexpr auto extents = _("(") + array_info<T>::extents + _(")");
|
|
|
|
return extents.text + format_descriptor<remove_all_extents_t<T>>::format();
|
2017-05-10 08:21:01 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-05-05 18:33:54 +00:00
|
|
|
NAMESPACE_BEGIN(detail)
|
2016-10-23 12:50:08 +00:00
|
|
|
template <typename T, int ExtraFlags>
|
|
|
|
struct pyobject_caster<array_t<T, ExtraFlags>> {
|
|
|
|
using type = array_t<T, ExtraFlags>;
|
|
|
|
|
2017-02-26 23:03:00 +00:00
|
|
|
bool load(handle src, bool convert) {
|
|
|
|
if (!convert && !type::check_(src))
|
|
|
|
return false;
|
2016-11-16 00:35:22 +00:00
|
|
|
value = type::ensure(src);
|
2016-10-23 12:50:08 +00:00
|
|
|
return static_cast<bool>(value);
|
|
|
|
}
|
|
|
|
|
|
|
|
static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
|
|
|
|
return src.inc_ref();
|
|
|
|
}
|
2017-07-02 09:48:56 +00:00
|
|
|
PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
|
2016-10-23 12:50:08 +00:00
|
|
|
};
|
|
|
|
|
2016-11-21 17:40:43 +00:00
|
|
|
template <typename T>
|
|
|
|
struct compare_buffer_info<T, detail::enable_if_t<detail::is_pod_struct<T>::value>> {
|
|
|
|
static bool compare(const buffer_info& b) {
|
|
|
|
return npy_api::get().PyArray_EquivTypes_(dtype::of<T>().ptr(), dtype(b).ptr());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2017-07-02 09:48:56 +00:00
|
|
|
template <typename T, typename = void>
|
|
|
|
struct npy_format_descriptor_name;
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
struct npy_format_descriptor_name<T, enable_if_t<std::is_integral<T>::value>> {
|
|
|
|
static constexpr auto name = _<std::is_same<T, bool>::value>(
|
|
|
|
_("bool"), _<std::is_signed<T>::value>("int", "uint") + _<sizeof(T)*8>()
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
struct npy_format_descriptor_name<T, enable_if_t<std::is_floating_point<T>::value>> {
|
|
|
|
static constexpr auto name = _<std::is_same<T, float>::value || std::is_same<T, double>::value>(
|
|
|
|
_("float") + _<sizeof(T)*8>(), _("longdouble")
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
struct npy_format_descriptor_name<T, enable_if_t<is_complex<T>::value>> {
|
|
|
|
static constexpr auto name = _<std::is_same<typename T::value_type, float>::value
|
|
|
|
|| std::is_same<typename T::value_type, double>::value>(
|
|
|
|
_("complex") + _<sizeof(typename T::value_type)*16>(), _("longcomplex")
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
struct npy_format_descriptor<T, enable_if_t<satisfies_any_of<T, std::is_arithmetic, is_complex>::value>>
|
|
|
|
: npy_format_descriptor_name<T> {
|
2016-05-04 20:22:48 +00:00
|
|
|
private:
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
// NB: the order here must match the one in common.h
|
|
|
|
constexpr static const int values[15] = {
|
|
|
|
npy_api::NPY_BOOL_,
|
2018-12-01 12:31:44 +00:00
|
|
|
npy_api::NPY_BYTE_, npy_api::NPY_UBYTE_, npy_api::NPY_INT16_, npy_api::NPY_UINT16_,
|
|
|
|
npy_api::NPY_INT32_, npy_api::NPY_UINT32_, npy_api::NPY_INT64_, npy_api::NPY_UINT64_,
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
npy_api::NPY_FLOAT_, npy_api::NPY_DOUBLE_, npy_api::NPY_LONGDOUBLE_,
|
|
|
|
npy_api::NPY_CFLOAT_, npy_api::NPY_CDOUBLE_, npy_api::NPY_CLONGDOUBLE_
|
|
|
|
};
|
|
|
|
|
2016-05-04 20:22:48 +00:00
|
|
|
public:
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
static constexpr int value = values[detail::is_fmt_numeric<T>::index];
|
|
|
|
|
2016-07-23 20:55:37 +00:00
|
|
|
static pybind11::dtype dtype() {
|
2016-07-19 23:54:57 +00:00
|
|
|
if (auto ptr = npy_api::get().PyArray_DescrFromType_(value))
|
2016-10-28 01:08:15 +00:00
|
|
|
return reinterpret_borrow<pybind11::dtype>(ptr);
|
2016-06-26 15:19:18 +00:00
|
|
|
pybind11_fail("Unsupported buffer format!");
|
2016-06-19 13:53:20 +00:00
|
|
|
}
|
2016-05-04 20:22:48 +00:00
|
|
|
};
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
|
|
|
|
#define PYBIND11_DECL_CHAR_FMT \
|
2017-07-02 09:48:56 +00:00
|
|
|
static constexpr auto name = _("S") + _<N>(); \
|
2016-10-16 20:27:42 +00:00
|
|
|
static pybind11::dtype dtype() { return pybind11::dtype(std::string("S") + std::to_string(N)); }
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
template <size_t N> struct npy_format_descriptor<char[N]> { PYBIND11_DECL_CHAR_FMT };
|
|
|
|
template <size_t N> struct npy_format_descriptor<std::array<char, N>> { PYBIND11_DECL_CHAR_FMT };
|
|
|
|
#undef PYBIND11_DECL_CHAR_FMT
|
2016-07-19 23:19:24 +00:00
|
|
|
|
2017-05-10 08:21:01 +00:00
|
|
|
template<typename T> struct npy_format_descriptor<T, enable_if_t<array_info<T>::is_array>> {
|
|
|
|
private:
|
|
|
|
using base_descr = npy_format_descriptor<typename array_info<T>::type>;
|
|
|
|
public:
|
|
|
|
static_assert(!array_info<T>::is_empty, "Zero-sized arrays are not supported");
|
|
|
|
|
2017-07-02 09:48:56 +00:00
|
|
|
static constexpr auto name = _("(") + array_info<T>::extents + _(")") + base_descr::name;
|
2017-05-10 08:21:01 +00:00
|
|
|
static pybind11::dtype dtype() {
|
|
|
|
list shape;
|
|
|
|
array_info<T>::append_extents(shape);
|
|
|
|
return pybind11::dtype::from_args(pybind11::make_tuple(base_descr::dtype(), shape));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-10-20 11:28:08 +00:00
|
|
|
template<typename T> struct npy_format_descriptor<T, enable_if_t<std::is_enum<T>::value>> {
|
|
|
|
private:
|
|
|
|
using base_descr = npy_format_descriptor<typename std::underlying_type<T>::type>;
|
|
|
|
public:
|
2017-07-02 09:48:56 +00:00
|
|
|
static constexpr auto name = base_descr::name;
|
2016-10-20 11:28:08 +00:00
|
|
|
static pybind11::dtype dtype() { return base_descr::dtype(); }
|
|
|
|
};
|
|
|
|
|
2016-06-19 14:48:55 +00:00
|
|
|
struct field_descriptor {
|
|
|
|
const char *name;
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t offset;
|
|
|
|
ssize_t size;
|
2016-08-14 12:45:49 +00:00
|
|
|
std::string format;
|
2016-07-23 20:55:37 +00:00
|
|
|
dtype descr;
|
2016-06-19 14:48:55 +00:00
|
|
|
};
|
|
|
|
|
2016-10-31 16:16:47 +00:00
|
|
|
inline PYBIND11_NOINLINE void register_structured_dtype(
|
2017-12-27 15:00:27 +00:00
|
|
|
any_container<field_descriptor> fields,
|
2017-04-14 20:33:44 +00:00
|
|
|
const std::type_info& tinfo, ssize_t itemsize,
|
2016-11-08 09:53:30 +00:00
|
|
|
bool (*direct_converter)(PyObject *, void *&)) {
|
|
|
|
|
2016-10-31 16:16:47 +00:00
|
|
|
auto& numpy_internals = get_numpy_internals();
|
|
|
|
if (numpy_internals.get_type_info(tinfo, false))
|
|
|
|
pybind11_fail("NumPy: dtype is already registered");
|
|
|
|
|
2019-07-15 11:31:03 +00:00
|
|
|
// Use ordered fields because order matters as of NumPy 1.14:
|
|
|
|
// https://docs.scipy.org/doc/numpy/release.html#multiple-field-indexing-assignment-of-structured-arrays
|
|
|
|
std::vector<field_descriptor> ordered_fields(std::move(fields));
|
|
|
|
std::sort(ordered_fields.begin(), ordered_fields.end(),
|
|
|
|
[](const field_descriptor &a, const field_descriptor &b) { return a.offset < b.offset; });
|
|
|
|
|
2016-10-31 16:16:47 +00:00
|
|
|
list names, formats, offsets;
|
2019-07-15 11:31:03 +00:00
|
|
|
for (auto& field : ordered_fields) {
|
2016-10-31 16:16:47 +00:00
|
|
|
if (!field.descr)
|
|
|
|
pybind11_fail(std::string("NumPy: unsupported field dtype: `") +
|
|
|
|
field.name + "` @ " + tinfo.name());
|
|
|
|
names.append(PYBIND11_STR_TYPE(field.name));
|
|
|
|
formats.append(field.descr);
|
|
|
|
offsets.append(pybind11::int_(field.offset));
|
|
|
|
}
|
|
|
|
auto dtype_ptr = pybind11::dtype(names, formats, offsets, itemsize).release().ptr();
|
|
|
|
|
|
|
|
// There is an existing bug in NumPy (as of v1.11): trailing bytes are
|
|
|
|
// not encoded explicitly into the format string. This will supposedly
|
|
|
|
// get fixed in v1.12; for further details, see these:
|
|
|
|
// - https://github.com/numpy/numpy/issues/7797
|
|
|
|
// - https://github.com/numpy/numpy/pull/7798
|
|
|
|
// Because of this, we won't use numpy's logic to generate buffer format
|
|
|
|
// strings and will just do it ourselves.
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t offset = 0;
|
2016-10-31 16:16:47 +00:00
|
|
|
std::ostringstream oss;
|
2017-05-10 09:36:24 +00:00
|
|
|
// mark the structure as unaligned with '^', because numpy and C++ don't
|
|
|
|
// always agree about alignment (particularly for complex), and we're
|
|
|
|
// explicitly listing all our padding. This depends on none of the fields
|
|
|
|
// overriding the endianness. Putting the ^ in front of individual fields
|
|
|
|
// isn't guaranteed to work due to https://github.com/numpy/numpy/issues/9049
|
|
|
|
oss << "^T{";
|
2016-10-31 16:16:47 +00:00
|
|
|
for (auto& field : ordered_fields) {
|
|
|
|
if (field.offset > offset)
|
|
|
|
oss << (field.offset - offset) << 'x';
|
2016-11-22 11:17:07 +00:00
|
|
|
oss << field.format << ':' << field.name << ':';
|
2016-10-31 16:16:47 +00:00
|
|
|
offset = field.offset + field.size;
|
|
|
|
}
|
|
|
|
if (itemsize > offset)
|
|
|
|
oss << (itemsize - offset) << 'x';
|
|
|
|
oss << '}';
|
|
|
|
auto format_str = oss.str();
|
|
|
|
|
|
|
|
// Sanity check: verify that NumPy properly parses our buffer format string
|
|
|
|
auto& api = npy_api::get();
|
|
|
|
auto arr = array(buffer_info(nullptr, itemsize, format_str, 1));
|
|
|
|
if (!api.PyArray_EquivTypes_(dtype_ptr, arr.dtype().ptr()))
|
|
|
|
pybind11_fail("NumPy: invalid buffer descriptor!");
|
|
|
|
|
|
|
|
auto tindex = std::type_index(tinfo);
|
|
|
|
numpy_internals.registered_dtypes[tindex] = { dtype_ptr, format_str };
|
|
|
|
get_internals().direct_conversions[tindex].push_back(direct_converter);
|
|
|
|
}
|
|
|
|
|
Numpy: better compilation errors, long double support (#619)
* Clarify PYBIND11_NUMPY_DTYPE documentation
The current documentation and example reads as though
PYBIND11_NUMPY_DTYPE is a declarative macro along the same lines as
PYBIND11_DECLARE_HOLDER_TYPE, but it isn't. The changes the
documentation and docs example to make it clear that you need to "call"
the macro.
* Add satisfies_{all,any,none}_of<T, Preds>
`satisfies_all_of<T, Pred1, Pred2, Pred3>` is a nice legibility-enhanced
shortcut for `is_all<Pred1<T>, Pred2<T>, Pred3<T>>`.
* Give better error message for non-POD dtype attempts
If you try to use a non-POD data type, you get difficult-to-interpret
compilation errors (about ::name() not being a member of an internal
pybind11 struct, among others), for which isn't at all obvious what the
problem is.
This adds a static_assert for such cases.
It also changes the base case from an empty struct to the is_pod_struct
case by no longer using `enable_if<is_pod_struct>` but instead using a
static_assert: thus specializations avoid the base class, POD types
work, and non-POD types (and unimplemented POD types like std::array)
get a more informative static_assert failure.
* Prefix macros with PYBIND11_
numpy.h uses unprefixed macros, which seems undesirable. This prefixes
them with PYBIND11_ to match all the other macros in numpy.h (and
elsewhere).
* Add long double support
This adds long double and std::complex<long double> support for numpy
arrays.
This allows some simplification of the code used to generate format
descriptors; the new code uses fewer macros, instead putting the code as
different templated options; the template conditions end up simpler with
this because we are now supporting all basic C++ arithmetic types (and
so can use is_arithmetic instead of is_integral + multiple
different specializations).
In addition to testing that it is indeed working in the test script, it
also adds various offset and size calculations there, which
fixes the test failures under x86 compilations.
2017-01-31 16:00:15 +00:00
|
|
|
template <typename T, typename SFINAE> struct npy_format_descriptor {
|
|
|
|
static_assert(is_pod_struct<T>::value, "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
|
|
|
|
|
2017-07-02 09:48:56 +00:00
|
|
|
static constexpr auto name = make_caster<T>::name;
|
2016-06-19 14:48:55 +00:00
|
|
|
|
2016-07-23 20:55:37 +00:00
|
|
|
static pybind11::dtype dtype() {
|
2016-10-28 01:08:15 +00:00
|
|
|
return reinterpret_borrow<pybind11::dtype>(dtype_ptr());
|
2016-06-19 14:48:55 +00:00
|
|
|
}
|
|
|
|
|
2016-08-14 12:45:49 +00:00
|
|
|
static std::string format() {
|
2016-10-31 13:52:32 +00:00
|
|
|
static auto format_str = get_numpy_internals().get_type_info<T>(true)->format_str;
|
2016-08-14 12:45:49 +00:00
|
|
|
return format_str;
|
2016-06-19 14:48:55 +00:00
|
|
|
}
|
|
|
|
|
2017-12-27 15:00:27 +00:00
|
|
|
static void register_dtype(any_container<field_descriptor> fields) {
|
|
|
|
register_structured_dtype(std::move(fields), typeid(typename std::remove_cv<T>::type),
|
2016-10-31 16:16:47 +00:00
|
|
|
sizeof(T), &direct_converter);
|
2016-06-19 14:48:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2016-10-31 13:52:32 +00:00
|
|
|
static PyObject* dtype_ptr() {
|
|
|
|
static PyObject* ptr = get_numpy_internals().get_type_info<T>(true)->dtype_ptr;
|
|
|
|
return ptr;
|
|
|
|
}
|
2016-10-20 15:11:08 +00:00
|
|
|
|
2016-10-23 14:27:13 +00:00
|
|
|
static bool direct_converter(PyObject *obj, void*& value) {
|
|
|
|
auto& api = npy_api::get();
|
|
|
|
if (!PyObject_TypeCheck(obj, api.PyVoidArrType_Type_))
|
2016-10-20 15:11:08 +00:00
|
|
|
return false;
|
2016-10-28 01:08:15 +00:00
|
|
|
if (auto descr = reinterpret_steal<object>(api.PyArray_DescrFromScalar_(obj))) {
|
2016-10-31 13:52:32 +00:00
|
|
|
if (api.PyArray_EquivTypes_(dtype_ptr(), descr.ptr())) {
|
2016-10-23 14:27:13 +00:00
|
|
|
value = ((PyVoidScalarObject_Proxy *) obj)->obval;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
2016-06-19 14:48:55 +00:00
|
|
|
};
|
|
|
|
|
2017-05-31 14:44:41 +00:00
|
|
|
#ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
|
|
|
|
# define PYBIND11_NUMPY_DTYPE(Type, ...) ((void)0)
|
|
|
|
# define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void)0)
|
|
|
|
#else
|
|
|
|
|
2016-11-01 13:27:35 +00:00
|
|
|
#define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
|
|
|
|
::pybind11::detail::field_descriptor { \
|
|
|
|
Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
|
|
|
|
::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
|
|
|
|
::pybind11::detail::npy_format_descriptor<decltype(std::declval<T>().Field)>::dtype() \
|
2016-06-21 23:42:10 +00:00
|
|
|
}
|
2016-06-19 14:48:55 +00:00
|
|
|
|
2016-11-01 13:27:35 +00:00
|
|
|
// Extract name, offset and format descriptor for a struct field
|
|
|
|
#define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
|
|
|
|
|
2016-06-19 14:48:55 +00:00
|
|
|
// The main idea of this macro is borrowed from https://github.com/swansontec/map-macro
|
|
|
|
// (C) William Swanson, Paul Fultz
|
2016-06-27 22:02:21 +00:00
|
|
|
#define PYBIND11_EVAL0(...) __VA_ARGS__
|
|
|
|
#define PYBIND11_EVAL1(...) PYBIND11_EVAL0 (PYBIND11_EVAL0 (PYBIND11_EVAL0 (__VA_ARGS__)))
|
|
|
|
#define PYBIND11_EVAL2(...) PYBIND11_EVAL1 (PYBIND11_EVAL1 (PYBIND11_EVAL1 (__VA_ARGS__)))
|
|
|
|
#define PYBIND11_EVAL3(...) PYBIND11_EVAL2 (PYBIND11_EVAL2 (PYBIND11_EVAL2 (__VA_ARGS__)))
|
|
|
|
#define PYBIND11_EVAL4(...) PYBIND11_EVAL3 (PYBIND11_EVAL3 (PYBIND11_EVAL3 (__VA_ARGS__)))
|
|
|
|
#define PYBIND11_EVAL(...) PYBIND11_EVAL4 (PYBIND11_EVAL4 (PYBIND11_EVAL4 (__VA_ARGS__)))
|
|
|
|
#define PYBIND11_MAP_END(...)
|
|
|
|
#define PYBIND11_MAP_OUT
|
|
|
|
#define PYBIND11_MAP_COMMA ,
|
|
|
|
#define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
|
|
|
|
#define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
|
|
|
|
#define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0 (test, next, 0)
|
|
|
|
#define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1 (PYBIND11_MAP_GET_END test, next)
|
2016-06-29 14:21:51 +00:00
|
|
|
#ifdef _MSC_VER // MSVC is not as eager to expand macros, hence this workaround
|
2016-06-27 22:02:21 +00:00
|
|
|
#define PYBIND11_MAP_LIST_NEXT1(test, next) \
|
|
|
|
PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
|
2016-06-27 16:01:22 +00:00
|
|
|
#else
|
2016-06-27 22:02:21 +00:00
|
|
|
#define PYBIND11_MAP_LIST_NEXT1(test, next) \
|
|
|
|
PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
|
2016-06-27 16:01:22 +00:00
|
|
|
#endif
|
2016-06-27 22:02:21 +00:00
|
|
|
#define PYBIND11_MAP_LIST_NEXT(test, next) \
|
|
|
|
PYBIND11_MAP_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
|
|
|
|
#define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
|
|
|
|
f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST1) (f, t, peek, __VA_ARGS__)
|
|
|
|
#define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
|
|
|
|
f(t, x) PYBIND11_MAP_LIST_NEXT (peek, PYBIND11_MAP_LIST0) (f, t, peek, __VA_ARGS__)
|
2016-06-29 14:21:51 +00:00
|
|
|
// PYBIND11_MAP_LIST(f, t, a1, a2, ...) expands to f(t, a1), f(t, a2), ...
|
2016-06-27 22:02:21 +00:00
|
|
|
#define PYBIND11_MAP_LIST(f, t, ...) \
|
|
|
|
PYBIND11_EVAL (PYBIND11_MAP_LIST1 (f, t, __VA_ARGS__, (), 0))
|
2016-06-19 14:48:55 +00:00
|
|
|
|
2016-07-02 15:18:42 +00:00
|
|
|
#define PYBIND11_NUMPY_DTYPE(Type, ...) \
|
2016-06-21 23:48:36 +00:00
|
|
|
::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
|
2017-12-27 15:00:27 +00:00
|
|
|
(::std::vector<::pybind11::detail::field_descriptor> \
|
|
|
|
{PYBIND11_MAP_LIST (PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
|
2016-06-19 14:48:55 +00:00
|
|
|
|
2016-11-01 13:27:35 +00:00
|
|
|
#ifdef _MSC_VER
|
|
|
|
#define PYBIND11_MAP2_LIST_NEXT1(test, next) \
|
|
|
|
PYBIND11_EVAL0 (PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0))
|
|
|
|
#else
|
|
|
|
#define PYBIND11_MAP2_LIST_NEXT1(test, next) \
|
|
|
|
PYBIND11_MAP_NEXT0 (test, PYBIND11_MAP_COMMA next, 0)
|
|
|
|
#endif
|
|
|
|
#define PYBIND11_MAP2_LIST_NEXT(test, next) \
|
|
|
|
PYBIND11_MAP2_LIST_NEXT1 (PYBIND11_MAP_GET_END test, next)
|
|
|
|
#define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
|
|
|
|
f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST1) (f, t, peek, __VA_ARGS__)
|
|
|
|
#define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
|
|
|
|
f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT (peek, PYBIND11_MAP2_LIST0) (f, t, peek, __VA_ARGS__)
|
|
|
|
// PYBIND11_MAP2_LIST(f, t, a1, a2, ...) expands to f(t, a1, a2), f(t, a3, a4), ...
|
|
|
|
#define PYBIND11_MAP2_LIST(f, t, ...) \
|
|
|
|
PYBIND11_EVAL (PYBIND11_MAP2_LIST1 (f, t, __VA_ARGS__, (), 0))
|
|
|
|
|
|
|
|
#define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
|
|
|
|
::pybind11::detail::npy_format_descriptor<Type>::register_dtype \
|
2017-12-27 15:00:27 +00:00
|
|
|
(::std::vector<::pybind11::detail::field_descriptor> \
|
|
|
|
{PYBIND11_MAP2_LIST (PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
|
2016-11-01 13:27:35 +00:00
|
|
|
|
2017-05-31 14:44:41 +00:00
|
|
|
#endif // __CLION_IDE__
|
|
|
|
|
2016-02-11 09:47:11 +00:00
|
|
|
template <class T>
|
|
|
|
using array_iterator = typename std::add_pointer<T>::type;
|
|
|
|
|
|
|
|
template <class T>
|
|
|
|
array_iterator<T> array_begin(const buffer_info& buffer) {
|
|
|
|
return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr));
|
|
|
|
}
|
|
|
|
|
|
|
|
template <class T>
|
|
|
|
array_iterator<T> array_end(const buffer_info& buffer) {
|
|
|
|
return array_iterator<T>(reinterpret_cast<T*>(buffer.ptr) + buffer.size);
|
|
|
|
}
|
|
|
|
|
|
|
|
class common_iterator {
|
|
|
|
public:
|
2017-04-05 22:13:04 +00:00
|
|
|
using container_type = std::vector<ssize_t>;
|
2016-02-11 09:47:11 +00:00
|
|
|
using value_type = container_type::value_type;
|
|
|
|
using size_type = container_type::size_type;
|
|
|
|
|
|
|
|
common_iterator() : p_ptr(0), m_strides() {}
|
2016-02-20 11:17:17 +00:00
|
|
|
|
2017-04-14 20:33:44 +00:00
|
|
|
common_iterator(void* ptr, const container_type& strides, const container_type& shape)
|
2016-02-11 09:47:11 +00:00
|
|
|
: p_ptr(reinterpret_cast<char*>(ptr)), m_strides(strides.size()) {
|
|
|
|
m_strides.back() = static_cast<value_type>(strides.back());
|
|
|
|
for (size_type i = m_strides.size() - 1; i != 0; --i) {
|
|
|
|
size_type j = i - 1;
|
|
|
|
value_type s = static_cast<value_type>(shape[i]);
|
|
|
|
m_strides[j] = strides[j] + m_strides[i] - strides[i] * s;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void increment(size_type dim) {
|
|
|
|
p_ptr += m_strides[dim];
|
|
|
|
}
|
|
|
|
|
|
|
|
void* data() const {
|
|
|
|
return p_ptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
char* p_ptr;
|
|
|
|
container_type m_strides;
|
|
|
|
};
|
|
|
|
|
2016-02-20 11:17:17 +00:00
|
|
|
template <size_t N> class multi_array_iterator {
|
2016-02-11 09:47:11 +00:00
|
|
|
public:
|
2017-04-14 20:33:44 +00:00
|
|
|
using container_type = std::vector<ssize_t>;
|
2016-02-11 09:47:11 +00:00
|
|
|
|
2016-02-20 11:17:17 +00:00
|
|
|
multi_array_iterator(const std::array<buffer_info, N> &buffers,
|
2017-04-14 20:33:44 +00:00
|
|
|
const container_type &shape)
|
2016-02-20 11:17:17 +00:00
|
|
|
: m_shape(shape.size()), m_index(shape.size(), 0),
|
|
|
|
m_common_iterator() {
|
|
|
|
|
2016-02-11 09:47:11 +00:00
|
|
|
// Manual copy to avoid conversion warning if using std::copy
|
2016-02-20 11:17:17 +00:00
|
|
|
for (size_t i = 0; i < shape.size(); ++i)
|
2017-04-14 20:33:44 +00:00
|
|
|
m_shape[i] = shape[i];
|
2016-02-11 09:47:11 +00:00
|
|
|
|
2017-04-14 20:33:44 +00:00
|
|
|
container_type strides(shape.size());
|
2016-02-20 11:17:17 +00:00
|
|
|
for (size_t i = 0; i < N; ++i)
|
2016-02-11 09:47:11 +00:00
|
|
|
init_common_iterator(buffers[i], shape, m_common_iterator[i], strides);
|
|
|
|
}
|
|
|
|
|
|
|
|
multi_array_iterator& operator++() {
|
|
|
|
for (size_t j = m_index.size(); j != 0; --j) {
|
|
|
|
size_t i = j - 1;
|
|
|
|
if (++m_index[i] != m_shape[i]) {
|
|
|
|
increment_common_iterator(i);
|
|
|
|
break;
|
2016-02-20 11:17:17 +00:00
|
|
|
} else {
|
2016-02-11 09:47:11 +00:00
|
|
|
m_index[i] = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
template <size_t K, class T = void> T* data() const {
|
|
|
|
return reinterpret_cast<T*>(m_common_iterator[K].data());
|
2016-02-11 09:47:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
|
|
|
using common_iter = common_iterator;
|
|
|
|
|
2016-02-20 11:17:17 +00:00
|
|
|
void init_common_iterator(const buffer_info &buffer,
|
2017-04-14 20:33:44 +00:00
|
|
|
const container_type &shape,
|
|
|
|
common_iter &iterator,
|
|
|
|
container_type &strides) {
|
2016-02-11 09:47:11 +00:00
|
|
|
auto buffer_shape_iter = buffer.shape.rbegin();
|
|
|
|
auto buffer_strides_iter = buffer.strides.rbegin();
|
|
|
|
auto shape_iter = shape.rbegin();
|
|
|
|
auto strides_iter = strides.rbegin();
|
|
|
|
|
|
|
|
while (buffer_shape_iter != buffer.shape.rend()) {
|
|
|
|
if (*shape_iter == *buffer_shape_iter)
|
2017-04-05 22:13:04 +00:00
|
|
|
*strides_iter = *buffer_strides_iter;
|
2016-02-11 09:47:11 +00:00
|
|
|
else
|
|
|
|
*strides_iter = 0;
|
|
|
|
|
|
|
|
++buffer_shape_iter;
|
|
|
|
++buffer_strides_iter;
|
|
|
|
++shape_iter;
|
|
|
|
++strides_iter;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::fill(strides_iter, strides.rend(), 0);
|
|
|
|
iterator = common_iter(buffer.ptr, strides, shape);
|
|
|
|
}
|
|
|
|
|
|
|
|
void increment_common_iterator(size_t dim) {
|
2016-02-20 11:17:17 +00:00
|
|
|
for (auto &iter : m_common_iterator)
|
2016-02-11 09:47:11 +00:00
|
|
|
iter.increment(dim);
|
|
|
|
}
|
|
|
|
|
|
|
|
container_type m_shape;
|
|
|
|
container_type m_index;
|
|
|
|
std::array<common_iter, N> m_common_iterator;
|
|
|
|
};
|
|
|
|
|
2017-03-19 00:11:59 +00:00
|
|
|
enum class broadcast_trivial { non_trivial, c_trivial, f_trivial };
|
|
|
|
|
|
|
|
// Populates the shape and number of dimensions for the set of buffers. Returns a broadcast_trivial
|
|
|
|
// enum value indicating whether the broadcast is "trivial"--that is, has each buffer being either a
|
|
|
|
// singleton or a full-size, C-contiguous (`c_trivial`) or Fortran-contiguous (`f_trivial`) storage
|
|
|
|
// buffer; returns `non_trivial` otherwise.
|
2016-02-11 09:47:11 +00:00
|
|
|
template <size_t N>
|
2017-04-14 20:33:44 +00:00
|
|
|
broadcast_trivial broadcast(const std::array<buffer_info, N> &buffers, ssize_t &ndim, std::vector<ssize_t> &shape) {
|
2017-03-26 03:51:40 +00:00
|
|
|
ndim = std::accumulate(buffers.begin(), buffers.end(), ssize_t(0), [](ssize_t res, const buffer_info &buf) {
|
2016-02-11 09:47:11 +00:00
|
|
|
return std::max(res, buf.ndim);
|
|
|
|
});
|
|
|
|
|
Stop forcing c-contiguous in py::vectorize
The only part of the vectorize code that actually needs c-contiguous is
the "trivial" broadcast; for non-trivial arguments, the code already
uses strides properly (and so handles C-style, F-style, neither, slices,
etc.)
This commit rewrites `broadcast` to additionally check for C-contiguous
storage, then takes off the `c_style` flag for the arguments, which
will keep the functionality more or less the same, except for no longer
requiring an array copy for non-c-contiguous input arrays.
Additionally, if we're given a singleton slice (e.g. a[0::4, 0::4] for a
4x4 or smaller array), we no longer fail triviality because the trivial
code path never actually uses the strides on a singleton.
2017-03-15 03:57:56 +00:00
|
|
|
shape.clear();
|
2017-04-14 20:33:44 +00:00
|
|
|
shape.resize((size_t) ndim, 1);
|
Stop forcing c-contiguous in py::vectorize
The only part of the vectorize code that actually needs c-contiguous is
the "trivial" broadcast; for non-trivial arguments, the code already
uses strides properly (and so handles C-style, F-style, neither, slices,
etc.)
This commit rewrites `broadcast` to additionally check for C-contiguous
storage, then takes off the `c_style` flag for the arguments, which
will keep the functionality more or less the same, except for no longer
requiring an array copy for non-c-contiguous input arrays.
Additionally, if we're given a singleton slice (e.g. a[0::4, 0::4] for a
4x4 or smaller array), we no longer fail triviality because the trivial
code path never actually uses the strides on a singleton.
2017-03-15 03:57:56 +00:00
|
|
|
|
2017-03-19 00:11:59 +00:00
|
|
|
// Figure out the output size, and make sure all input arrays conform (i.e. are either size 1 or
|
|
|
|
// the full size).
|
2016-02-11 09:47:11 +00:00
|
|
|
for (size_t i = 0; i < N; ++i) {
|
|
|
|
auto res_iter = shape.rbegin();
|
2017-03-19 00:11:59 +00:00
|
|
|
auto end = buffers[i].shape.rend();
|
|
|
|
for (auto shape_iter = buffers[i].shape.rbegin(); shape_iter != end; ++shape_iter, ++res_iter) {
|
Stop forcing c-contiguous in py::vectorize
The only part of the vectorize code that actually needs c-contiguous is
the "trivial" broadcast; for non-trivial arguments, the code already
uses strides properly (and so handles C-style, F-style, neither, slices,
etc.)
This commit rewrites `broadcast` to additionally check for C-contiguous
storage, then takes off the `c_style` flag for the arguments, which
will keep the functionality more or less the same, except for no longer
requiring an array copy for non-c-contiguous input arrays.
Additionally, if we're given a singleton slice (e.g. a[0::4, 0::4] for a
4x4 or smaller array), we no longer fail triviality because the trivial
code path never actually uses the strides on a singleton.
2017-03-15 03:57:56 +00:00
|
|
|
const auto &dim_size_in = *shape_iter;
|
|
|
|
auto &dim_size_out = *res_iter;
|
|
|
|
|
|
|
|
// Each input dimension can either be 1 or `n`, but `n` values must match across buffers
|
|
|
|
if (dim_size_out == 1)
|
|
|
|
dim_size_out = dim_size_in;
|
|
|
|
else if (dim_size_in != 1 && dim_size_in != dim_size_out)
|
2016-02-11 09:47:11 +00:00
|
|
|
pybind11_fail("pybind11::vectorize: incompatible size/dimension of inputs!");
|
2017-03-19 00:11:59 +00:00
|
|
|
}
|
|
|
|
}
|
2016-02-20 11:17:17 +00:00
|
|
|
|
2017-03-19 00:11:59 +00:00
|
|
|
bool trivial_broadcast_c = true;
|
|
|
|
bool trivial_broadcast_f = true;
|
|
|
|
for (size_t i = 0; i < N && (trivial_broadcast_c || trivial_broadcast_f); ++i) {
|
|
|
|
if (buffers[i].size == 1)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// Require the same number of dimensions:
|
|
|
|
if (buffers[i].ndim != ndim)
|
|
|
|
return broadcast_trivial::non_trivial;
|
|
|
|
|
|
|
|
// Require all dimensions be full-size:
|
|
|
|
if (!std::equal(buffers[i].shape.cbegin(), buffers[i].shape.cend(), shape.cbegin()))
|
|
|
|
return broadcast_trivial::non_trivial;
|
|
|
|
|
|
|
|
// Check for C contiguity (but only if previous inputs were also C contiguous)
|
|
|
|
if (trivial_broadcast_c) {
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t expect_stride = buffers[i].itemsize;
|
2017-03-19 00:11:59 +00:00
|
|
|
auto end = buffers[i].shape.crend();
|
2017-04-14 20:33:44 +00:00
|
|
|
for (auto shape_iter = buffers[i].shape.crbegin(), stride_iter = buffers[i].strides.crbegin();
|
|
|
|
trivial_broadcast_c && shape_iter != end; ++shape_iter, ++stride_iter) {
|
2017-03-19 00:11:59 +00:00
|
|
|
if (expect_stride == *stride_iter)
|
|
|
|
expect_stride *= *shape_iter;
|
|
|
|
else
|
|
|
|
trivial_broadcast_c = false;
|
Stop forcing c-contiguous in py::vectorize
The only part of the vectorize code that actually needs c-contiguous is
the "trivial" broadcast; for non-trivial arguments, the code already
uses strides properly (and so handles C-style, F-style, neither, slices,
etc.)
This commit rewrites `broadcast` to additionally check for C-contiguous
storage, then takes off the `c_style` flag for the arguments, which
will keep the functionality more or less the same, except for no longer
requiring an array copy for non-c-contiguous input arrays.
Additionally, if we're given a singleton slice (e.g. a[0::4, 0::4] for a
4x4 or smaller array), we no longer fail triviality because the trivial
code path never actually uses the strides on a singleton.
2017-03-15 03:57:56 +00:00
|
|
|
}
|
2017-03-19 00:11:59 +00:00
|
|
|
}
|
Stop forcing c-contiguous in py::vectorize
The only part of the vectorize code that actually needs c-contiguous is
the "trivial" broadcast; for non-trivial arguments, the code already
uses strides properly (and so handles C-style, F-style, neither, slices,
etc.)
This commit rewrites `broadcast` to additionally check for C-contiguous
storage, then takes off the `c_style` flag for the arguments, which
will keep the functionality more or less the same, except for no longer
requiring an array copy for non-c-contiguous input arrays.
Additionally, if we're given a singleton slice (e.g. a[0::4, 0::4] for a
4x4 or smaller array), we no longer fail triviality because the trivial
code path never actually uses the strides on a singleton.
2017-03-15 03:57:56 +00:00
|
|
|
|
2017-03-19 00:11:59 +00:00
|
|
|
// Check for Fortran contiguity (if previous inputs were also F contiguous)
|
|
|
|
if (trivial_broadcast_f) {
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t expect_stride = buffers[i].itemsize;
|
2017-03-19 00:11:59 +00:00
|
|
|
auto end = buffers[i].shape.cend();
|
2017-04-14 20:33:44 +00:00
|
|
|
for (auto shape_iter = buffers[i].shape.cbegin(), stride_iter = buffers[i].strides.cbegin();
|
|
|
|
trivial_broadcast_f && shape_iter != end; ++shape_iter, ++stride_iter) {
|
2017-03-19 00:11:59 +00:00
|
|
|
if (expect_stride == *stride_iter)
|
|
|
|
expect_stride *= *shape_iter;
|
|
|
|
else
|
|
|
|
trivial_broadcast_f = false;
|
|
|
|
}
|
2016-02-11 09:47:11 +00:00
|
|
|
}
|
|
|
|
}
|
2017-03-19 00:11:59 +00:00
|
|
|
|
|
|
|
return
|
|
|
|
trivial_broadcast_c ? broadcast_trivial::c_trivial :
|
|
|
|
trivial_broadcast_f ? broadcast_trivial::f_trivial :
|
|
|
|
broadcast_trivial::non_trivial;
|
2016-02-11 09:47:11 +00:00
|
|
|
}
|
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
template <typename T>
|
|
|
|
struct vectorize_arg {
|
|
|
|
static_assert(!std::is_rvalue_reference<T>::value, "Functions with rvalue reference arguments cannot be vectorized");
|
|
|
|
// The wrapped function gets called with this type:
|
|
|
|
using call_type = remove_reference_t<T>;
|
|
|
|
// Is this a vectorized argument?
|
|
|
|
static constexpr bool vectorize =
|
|
|
|
satisfies_any_of<call_type, std::is_arithmetic, is_complex, std::is_pod>::value &&
|
|
|
|
satisfies_none_of<call_type, std::is_pointer, std::is_array, is_std_array, std::is_enum>::value &&
|
|
|
|
(!std::is_reference<T>::value ||
|
|
|
|
(std::is_lvalue_reference<T>::value && std::is_const<call_type>::value));
|
|
|
|
// Accept this type: an array for vectorized types, otherwise the type as-is:
|
|
|
|
using type = conditional_t<vectorize, array_t<remove_cv_t<call_type>, array::forcecast>, T>;
|
|
|
|
};
|
|
|
|
|
2015-07-29 15:51:54 +00:00
|
|
|
template <typename Func, typename Return, typename... Args>
|
|
|
|
struct vectorize_helper {
|
2017-03-26 03:51:40 +00:00
|
|
|
private:
|
Stop forcing c-contiguous in py::vectorize
The only part of the vectorize code that actually needs c-contiguous is
the "trivial" broadcast; for non-trivial arguments, the code already
uses strides properly (and so handles C-style, F-style, neither, slices,
etc.)
This commit rewrites `broadcast` to additionally check for C-contiguous
storage, then takes off the `c_style` flag for the arguments, which
will keep the functionality more or less the same, except for no longer
requiring an array copy for non-c-contiguous input arrays.
Additionally, if we're given a singleton slice (e.g. a[0::4, 0::4] for a
4x4 or smaller array), we no longer fail triviality because the trivial
code path never actually uses the strides on a singleton.
2017-03-15 03:57:56 +00:00
|
|
|
static constexpr size_t N = sizeof...(Args);
|
2017-03-26 03:51:40 +00:00
|
|
|
static constexpr size_t NVectorized = constexpr_sum(vectorize_arg<Args>::vectorize...);
|
|
|
|
static_assert(NVectorized >= 1,
|
|
|
|
"pybind11::vectorize(...) requires a function with at least one vectorizable argument");
|
2015-07-29 15:51:54 +00:00
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
public:
|
2015-07-30 13:29:00 +00:00
|
|
|
template <typename T>
|
2017-03-26 03:51:40 +00:00
|
|
|
explicit vectorize_helper(T &&f) : f(std::forward<T>(f)) { }
|
2015-07-28 14:12:20 +00:00
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
object operator()(typename vectorize_arg<Args>::type... args) {
|
|
|
|
return run(args...,
|
|
|
|
make_index_sequence<N>(),
|
|
|
|
select_indices<vectorize_arg<Args>::vectorize...>(),
|
|
|
|
make_index_sequence<NVectorized>());
|
2015-07-29 15:51:54 +00:00
|
|
|
}
|
2015-07-26 14:33:49 +00:00
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
private:
|
|
|
|
remove_reference_t<Func> f;
|
|
|
|
|
2019-01-03 11:02:39 +00:00
|
|
|
// Internal compiler error in MSVC 19.16.27025.1 (Visual Studio 2017 15.9.4), when compiling with "/permissive-" flag
|
|
|
|
// when arg_call_types is manually inlined.
|
|
|
|
using arg_call_types = std::tuple<typename vectorize_arg<Args>::call_type...>;
|
|
|
|
template <size_t Index> using param_n_t = typename std::tuple_element<Index, arg_call_types>::type;
|
2017-03-26 03:51:40 +00:00
|
|
|
|
|
|
|
// Runs a vectorized function given arguments tuple and three index sequences:
|
|
|
|
// - Index is the full set of 0 ... (N-1) argument indices;
|
|
|
|
// - VIndex is the subset of argument indices with vectorized parameters, letting us access
|
|
|
|
// vectorized arguments (anything not in this sequence is passed through)
|
|
|
|
// - BIndex is a incremental sequence (beginning at 0) of the same size as VIndex, so that
|
|
|
|
// we can store vectorized buffer_infos in an array (argument VIndex has its buffer at
|
|
|
|
// index BIndex in the array).
|
|
|
|
template <size_t... Index, size_t... VIndex, size_t... BIndex> object run(
|
|
|
|
typename vectorize_arg<Args>::type &...args,
|
|
|
|
index_sequence<Index...> i_seq, index_sequence<VIndex...> vi_seq, index_sequence<BIndex...> bi_seq) {
|
|
|
|
|
|
|
|
// Pointers to values the function was called with; the vectorized ones set here will start
|
|
|
|
// out as array_t<T> pointers, but they will be changed them to T pointers before we make
|
|
|
|
// call the wrapped function. Non-vectorized pointers are left as-is.
|
|
|
|
std::array<void *, N> params{{ &args... }};
|
|
|
|
|
|
|
|
// The array of `buffer_info`s of vectorized arguments:
|
|
|
|
std::array<buffer_info, NVectorized> buffers{{ reinterpret_cast<array *>(params[VIndex])->request()... }};
|
2015-07-26 14:33:49 +00:00
|
|
|
|
|
|
|
/* Determine dimensions parameters of output array */
|
2017-04-14 20:33:44 +00:00
|
|
|
ssize_t nd = 0;
|
|
|
|
std::vector<ssize_t> shape(0);
|
|
|
|
auto trivial = broadcast(buffers, nd, shape);
|
|
|
|
size_t ndim = (size_t) nd;
|
2016-05-19 14:02:09 +00:00
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
size_t size = std::accumulate(shape.begin(), shape.end(), (size_t) 1, std::multiplies<size_t>());
|
|
|
|
|
|
|
|
// If all arguments are 0-dimension arrays (i.e. single values) return a plain value (i.e.
|
|
|
|
// not wrapped in an array).
|
|
|
|
if (size == 1 && ndim == 0) {
|
|
|
|
PYBIND11_EXPAND_SIDE_EFFECTS(params[VIndex] = buffers[BIndex].ptr);
|
|
|
|
return cast(f(*reinterpret_cast<param_n_t<Index> *>(params[Index])...));
|
2015-07-26 14:33:49 +00:00
|
|
|
}
|
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
array_t<Return> result;
|
|
|
|
if (trivial == broadcast_trivial::f_trivial) result = array_t<Return, array::f_style>(shape);
|
|
|
|
else result = array_t<Return>(shape);
|
2015-07-26 14:33:49 +00:00
|
|
|
|
2019-04-06 17:09:39 +00:00
|
|
|
if (size == 0) return std::move(result);
|
2016-01-17 21:36:39 +00:00
|
|
|
|
2017-03-19 00:11:59 +00:00
|
|
|
/* Call the function */
|
2017-03-26 03:51:40 +00:00
|
|
|
if (trivial == broadcast_trivial::non_trivial)
|
|
|
|
apply_broadcast(buffers, params, result, i_seq, vi_seq, bi_seq);
|
|
|
|
else
|
|
|
|
apply_trivial(buffers, params, result.mutable_data(), size, i_seq, vi_seq, bi_seq);
|
2016-01-17 21:36:39 +00:00
|
|
|
|
2019-04-06 17:09:39 +00:00
|
|
|
return std::move(result);
|
2015-07-29 15:51:54 +00:00
|
|
|
}
|
2016-02-11 09:47:11 +00:00
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
template <size_t... Index, size_t... VIndex, size_t... BIndex>
|
|
|
|
void apply_trivial(std::array<buffer_info, NVectorized> &buffers,
|
|
|
|
std::array<void *, N> ¶ms,
|
|
|
|
Return *out,
|
|
|
|
size_t size,
|
|
|
|
index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) {
|
|
|
|
|
|
|
|
// Initialize an array of mutable byte references and sizes with references set to the
|
|
|
|
// appropriate pointer in `params`; as we iterate, we'll increment each pointer by its size
|
|
|
|
// (except for singletons, which get an increment of 0).
|
|
|
|
std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{{
|
|
|
|
std::pair<unsigned char *&, const size_t>(
|
|
|
|
reinterpret_cast<unsigned char *&>(params[VIndex] = buffers[BIndex].ptr),
|
|
|
|
buffers[BIndex].size == 1 ? 0 : sizeof(param_n_t<VIndex>)
|
|
|
|
)...
|
|
|
|
}};
|
|
|
|
|
|
|
|
for (size_t i = 0; i < size; ++i) {
|
|
|
|
out[i] = f(*reinterpret_cast<param_n_t<Index> *>(params[Index])...);
|
|
|
|
for (auto &x : vecparams) x.first += x.second;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
template <size_t... Index, size_t... VIndex, size_t... BIndex>
|
|
|
|
void apply_broadcast(std::array<buffer_info, NVectorized> &buffers,
|
|
|
|
std::array<void *, N> ¶ms,
|
|
|
|
array_t<Return> &output_array,
|
|
|
|
index_sequence<Index...>, index_sequence<VIndex...>, index_sequence<BIndex...>) {
|
2016-02-11 09:47:11 +00:00
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
buffer_info output = output_array.request();
|
|
|
|
multi_array_iterator<NVectorized> input_iter(buffers, output.shape);
|
2016-02-11 09:47:11 +00:00
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
for (array_iterator<Return> iter = array_begin<Return>(output), end = array_end<Return>(output);
|
|
|
|
iter != end;
|
|
|
|
++iter, ++input_iter) {
|
|
|
|
PYBIND11_EXPAND_SIDE_EFFECTS((
|
|
|
|
params[VIndex] = input_iter.template data<BIndex>()
|
|
|
|
));
|
|
|
|
*iter = f(*reinterpret_cast<param_n_t<Index> *>(std::get<Index>(params))...);
|
2016-02-11 09:47:11 +00:00
|
|
|
}
|
|
|
|
}
|
2015-07-29 15:51:54 +00:00
|
|
|
};
|
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
template <typename Func, typename Return, typename... Args>
|
|
|
|
vectorize_helper<Func, Return, Args...>
|
|
|
|
vectorize_extractor(const Func &f, Return (*) (Args ...)) {
|
|
|
|
return detail::vectorize_helper<Func, Return, Args...>(f);
|
|
|
|
}
|
|
|
|
|
2016-05-19 14:02:09 +00:00
|
|
|
template <typename T, int Flags> struct handle_type_name<array_t<T, Flags>> {
|
2017-07-02 09:48:56 +00:00
|
|
|
static constexpr auto name = _("numpy.ndarray[") + npy_format_descriptor<T>::name + _("]");
|
2016-02-20 11:17:17 +00:00
|
|
|
};
|
|
|
|
|
2015-07-29 15:51:54 +00:00
|
|
|
NAMESPACE_END(detail)
|
2015-07-26 14:33:49 +00:00
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
// Vanilla pointer vectorizer:
|
2017-02-17 11:56:41 +00:00
|
|
|
template <typename Return, typename... Args>
|
2017-03-26 03:51:40 +00:00
|
|
|
detail::vectorize_helper<Return (*)(Args...), Return, Args...>
|
2017-02-17 11:56:41 +00:00
|
|
|
vectorize(Return (*f) (Args ...)) {
|
2017-03-26 03:51:40 +00:00
|
|
|
return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(f);
|
2015-07-26 14:33:49 +00:00
|
|
|
}
|
|
|
|
|
2017-03-26 03:51:40 +00:00
|
|
|
// lambda vectorizer:
|
2017-05-10 05:51:08 +00:00
|
|
|
template <typename Func, detail::enable_if_t<detail::is_lambda<Func>::value, int> = 0>
|
2016-09-22 21:44:11 +00:00
|
|
|
auto vectorize(Func &&f) -> decltype(
|
2017-05-10 05:51:08 +00:00
|
|
|
detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr)) {
|
|
|
|
return detail::vectorize_extractor(std::forward<Func>(f), (detail::function_signature_t<Func> *) nullptr);
|
2017-03-26 03:51:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Vectorize a class method (non-const):
|
|
|
|
template <typename Return, typename Class, typename... Args,
|
|
|
|
typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())), Return, Class *, Args...>>
|
|
|
|
Helper vectorize(Return (Class::*f)(Args...)) {
|
|
|
|
return Helper(std::mem_fn(f));
|
|
|
|
}
|
|
|
|
|
2018-08-15 15:13:36 +00:00
|
|
|
// Vectorize a class method (const):
|
2017-03-26 03:51:40 +00:00
|
|
|
template <typename Return, typename Class, typename... Args,
|
|
|
|
typename Helper = detail::vectorize_helper<decltype(std::mem_fn(std::declval<Return (Class::*)(Args...) const>())), Return, const Class *, Args...>>
|
|
|
|
Helper vectorize(Return (Class::*f)(Args...) const) {
|
|
|
|
return Helper(std::mem_fn(f));
|
2015-07-26 14:33:49 +00:00
|
|
|
}
|
|
|
|
|
2017-08-10 16:03:29 +00:00
|
|
|
NAMESPACE_END(PYBIND11_NAMESPACE)
|
2015-07-26 14:33:49 +00:00
|
|
|
|
|
|
|
#if defined(_MSC_VER)
|
|
|
|
#pragma warning(pop)
|
|
|
|
#endif
|