Go to the documentation of this file.
27 #include <type_traits>
32 #if defined(PYBIND11_NUMPY_1_ONLY) && !defined(PYBIND11_INTERNAL_NUMPY_1_ONLY_DETECTED)
33 # error PYBIND11_NUMPY_1_ONLY must be defined before any pybind11 header is included.
41 static_assert(
sizeof(::
pybind11::ssize_t) ==
sizeof(Py_intptr_t),
"ssize_t != Py_intptr_t");
64 template <
typename type,
typename SFINAE =
void>
83 #ifndef PYBIND11_NUMPY_1_ONLY
149 return &(it->second);
151 if (throw_if_missing) {
152 pybind11_fail(std::string(
"NumPy type info missing for ") + tinfo.name());
157 template <
typename T>
164 ptr = &get_or_create_shared_data<numpy_internals>(
"_numpy_internals");
177 str version_string = numpy.attr(
"__version__");
180 object numpy_version = numpy_lib.attr(
"NumpyVersion")(version_string);
181 int major_version = numpy_version.attr(
"major").
cast<
int>();
183 #ifdef PYBIND11_NUMPY_1_ONLY
184 if (major_version >= 2) {
185 throw std::runtime_error(
186 "This extension was built with PYBIND11_NUMPY_1_ONLY defined, "
187 "but NumPy 2 is used in this process. For NumPy2 compatibility, "
188 "this extension needs to be rebuilt without the PYBIND11_NUMPY_1_ONLY define.");
193 std::string numpy_core_path = major_version >= 2 ?
"numpy._core" :
"numpy.core";
197 template <
typename T>
199 template <
typename U>
203 template <
typename Concrete>
209 template <
typename Concrete,
typename T,
typename... Ts,
typename... Ints>
211 return sizeof(Concrete) ==
sizeof(
T) ?
I :
platform_lookup<Concrete, Ts...>(Is...);
254 NPY_UINT32_ = platform_lookup<std::uint32_t, unsigned long, unsigned int, unsigned short>(
259 = platform_lookup<std::uint64_t, unsigned long, unsigned long long, unsigned int>(
283 PyObject *(*PyArray_DescrFromType_)(
int);
284 PyObject *(*PyArray_NewFromDescr_)(PyTypeObject *,
293 PyObject *(*PyArray_DescrNewFromType_)(
int);
295 PyObject *(*PyArray_NewCopy_)(PyObject *,
int);
299 PyObject *(*PyArray_DescrFromScalar_)(PyObject *);
300 PyObject *(*PyArray_FromAny_)(PyObject *, PyObject *,
int,
int,
int, PyObject *);
303 #ifdef PYBIND11_NUMPY_1_ONLY
304 int (*PyArray_GetArrayParamsFromObject_)(PyObject *,
313 PyObject *(*PyArray_Squeeze_)(PyObject *);
318 PyObject *(*PyArray_View_)(PyObject *, PyObject *, PyObject *);
340 #ifdef PYBIND11_NUMPY_1_ONLY
341 API_PyArray_GetArrayParamsFromObject = 278,
348 auto c =
m.attr(
"_ARRAY_API");
349 void **api_ptr = (
void **) PyCapsule_GetPointer(
c.ptr(),
nullptr);
350 if (api_ptr ==
nullptr) {
351 raise_from(PyExc_SystemError,
"FAILURE obtaining numpy _ARRAY_API pointer.");
355 #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func];
357 api.PyArray_RUNTIME_VERSION_ =
api.PyArray_GetNDArrayCFeatureVersion_();
358 if (
api.PyArray_RUNTIME_VERSION_ < 0x7) {
359 pybind11_fail(
"pybind11 numpy support requires numpy >= 1.7.0");
377 #ifdef PYBIND11_NUMPY_1_ONLY
413 template <
typename T>
415 template <
typename T,
size_t N>
417 template <
typename T>
419 template <
typename T>
422 template <
typename T>
433 template <
typename T>
435 template <
typename T,
size_t N>
440 static constexpr
size_t extent =
N;
448 static constexpr
auto extents = const_name<array_info<T>::is_array>(
457 template <
typename T,
size_t N>
459 template <
typename T>
462 template <
typename T>
466 #if defined(__GLIBCXX__) \
467 && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150426 || __GLIBCXX__ == 20150623 \
468 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)
471 std::is_trivially_destructible<T>,
474 std::is_trivially_copyable<T>,
485 template <
typename T>
488 template <s
size_t Dim = 0,
typename Str
ides>
492 template <
ssize_t Dim = 0,
typename Strides,
typename... Ix>
494 return i *
strides[Dim] + byte_offset_unsafe<Dim + 1>(
strides, index...);
502 template <
typename T, s
size_t Dims>
514 template <
bool Dyn = Dynamic>
526 template <
bool Dyn = Dynamic>
540 template <
typename... Ix>
543 "Invalid number of indices for unchecked array reference");
544 return *
reinterpret_cast<const T *
>(
data_
551 template <s
size_t D = Dims,
typename = enable_if_t<D == 1 || Dynamic>>
557 template <
typename... Ix>
573 template <
bool Dyn = Dynamic>
575 return std::accumulate(
578 template <
bool Dyn = Dynamic>
589 template <
typename T, s
size_t Dims>
593 using ConstBase::ConstBase;
598 using ConstBase::operator();
599 using ConstBase::operator[];
602 template <
typename... Ix>
605 "Invalid number of indices for unchecked array reference");
613 template <s
size_t D = Dims,
typename = enable_if_t<D == 1 || Dynamic>>
619 template <
typename... Ix>
625 template <
typename T, s
size_t Dim>
627 static_assert(Dim == 0 && Dim > 0 ,
628 "unchecked array proxy object is not castable");
630 template <
typename T, s
size_t Dim>
657 args[
"formats"] = std::move(formats);
659 args[
"itemsize"] = pybind11::int_(itemsize);
660 m_ptr = from_args(
args).release().ptr();
667 if (m_ptr ==
nullptr) {
674 PyObject *ptr =
nullptr;
678 return reinterpret_steal<dtype>(ptr);
682 template <
typename T>
688 #ifdef PYBIND11_NUMPY_1_ONLY
700 #ifdef PYBIND11_NUMPY_1_ONLY
708 if (
proxy->type_num < 0 ||
proxy->type_num >= 2056) {
711 return proxy->names !=
nullptr;
740 #ifdef PYBIND11_NUMPY_1_ONLY
752 #ifdef PYBIND11_NUMPY_1_ONLY
769 .attr(
"_dtype_from_pep3118");
788 auto field_dict = attr(
"fields").
cast<
dict>();
789 std::vector<field_descr> field_descriptors;
790 field_descriptors.reserve(field_dict.size());
792 for (
auto field : field_dict.attr(
"items")()) {
795 auto spec_fo = spec[1].cast<
tuple>();
797 auto offset = spec_fo[1].
cast<pybind11::int_>();
801 field_descriptors.emplace_back(
805 std::sort(field_descriptors.begin(),
806 field_descriptors.end(),
807 [](
const field_descr &
a,
const field_descr &
b) {
808 return a.offset.cast<int>() < b.offset.cast<int>();
812 for (
auto &
descr : field_descriptors) {
817 return dtype(std::move(
names), std::move(formats), std::move(
offsets), itemsize);
826 c_style = detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_,
827 f_style = detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_,
840 const void *
ptr =
nullptr,
849 pybind11_fail(
"NumPy: shape ndim doesn't match strides ndim");
855 if (isinstance<array>(
base)) {
857 flags = reinterpret_borrow<array>(
base).flags()
861 flags = detail::npy_api::NPY_ARRAY_WRITEABLE_;
866 auto tmp = reinterpret_steal<object>(
api.PyArray_NewFromDescr_(
868 descr.release().ptr(),
871 reinterpret_cast<Py_intptr_t *
>(
shape->data()),
872 reinterpret_cast<Py_intptr_t *
>(
strides->data()),
873 const_cast<void *
>(
ptr),
881 api.PyArray_SetBaseObject_(tmp.ptr(),
base.inc_ref().ptr());
883 tmp = reinterpret_steal<object>(
884 api.PyArray_NewCopy_(tmp.ptr(), -1 ));
887 m_ptr = tmp.release().ptr();
892 const void *
ptr =
nullptr,
896 template <
typename T,
902 template <
typename T>
906 template <
typename T>
910 template <
typename T>
976 template <
typename... Ix>
977 const void *
data(Ix... index)
const {
984 template <
typename... Ix>
992 template <
typename... Ix>
995 fail_dim_check(
sizeof...(index),
"too many indices for an array");
1004 template <
typename... Ix>
1018 throw std::domain_error(
"array has incorrect number of dimensions: "
1019 + std::to_string(
ndim()) +
"; expected "
1020 + std::to_string(
Dims));
1022 return detail::unchecked_mutable_reference<T, Dims>(
1036 throw std::domain_error(
"array has incorrect number of dimensions: "
1037 + std::to_string(
ndim()) +
"; expected "
1038 + std::to_string(
Dims));
1046 return reinterpret_steal<array>(
api.PyArray_Squeeze_(
m_ptr));
1053 detail::npy_api::PyArray_Dims
d
1055 reinterpret_cast<Py_intptr_t *
>(new_shape->data()),
1056 int(new_shape->size())};
1058 auto new_array = reinterpret_steal<object>(
1063 if (isinstance<array>(new_array)) {
1064 *
this = std::move(new_array);
1070 detail::npy_api::PyArray_Dims
d
1071 = {
reinterpret_cast<Py_intptr_t *
>(new_shape->data()),
int(new_shape->size())};
1087 auto new_view = reinterpret_steal<array>(
api.PyArray_View_(
1106 template <
typename,
typename>
1107 friend struct detail::npy_format_descriptor;
1110 throw index_error(
msg +
": " + std::to_string(dim) +
" (ndim = " + std::to_string(
ndim())
1114 template <
typename... Ix>
1122 throw std::domain_error(
"array is not writeable");
1126 template <
typename... Ix>
1133 template <
typename... Ix>
1136 throw index_error(std::string(
"index ") + std::to_string(
i)
1137 +
" is out of bounds for axis " + std::to_string(axis)
1138 +
" with size " + std::to_string(*
shape));
1145 if (
ptr ==
nullptr) {
1146 set_error(PyExc_ValueError,
"cannot create a pybind11::array from a nullptr");
1150 ptr,
nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags,
nullptr);
1154 template <
typename T,
int ExtraFlags = array::forcecast>
1167 static_assert(!detail::array_info<T>::is_array,
"Array types cannot be used with array_t");
1181 Py_XDECREF(
h.ptr());
1196 const T *
ptr =
nullptr,
1213 template <
typename... Ix>
1218 template <
typename... Ix>
1223 template <
typename... Ix>
1229 template <
typename... Ix>
1230 const T &
at(Ix... index)
const {
1239 template <
typename... Ix>
1256 return array::mutable_unchecked<T, Dims>();
1268 return array::unchecked<T, Dims>();
1283 return api.PyArray_Check_(
h.ptr())
1285 dtype::of<T>().ptr())
1292 if (
ptr ==
nullptr) {
1293 set_error(PyExc_ValueError,
"cannot create a pybind11::array_t from a nullptr");
1300 detail::npy_api::NPY_ARRAY_ENSUREARRAY_
1306 template <
typename T>
1315 static std::string
format() {
return std::to_string(
N) +
's'; }
1319 static std::string
format() {
return std::to_string(
N) +
's'; }
1322 template <
typename T>
1330 template <
typename T>
1340 template <
typename T,
int ExtraFlags>
1345 if (!
convert && !type::check_(src)) {
1348 value = type::ensure(src);
1349 return static_cast<bool>(
value);
1358 template <
typename T>
1365 template <
typename T,
typename =
void>
1368 template <
typename T>
1376 template <
typename T>
1382 > (
const_name(
"numpy.float") + const_name<sizeof(T) * 8>(),
1386 template <
typename T>
1393 + const_name<sizeof(typename T::value_type) * 16>(),
1397 template <
typename T>
1421 static constexpr
int value =
values[detail::is_fmt_numeric<T>::index];
1426 template <
typename T>
1435 #define PYBIND11_DECL_CHAR_FMT \
1436 static constexpr auto name = const_name("S") + const_name<N>(); \
1437 static pybind11::dtype dtype() { \
1438 return pybind11::dtype(std::string("S") + std::to_string(N)); \
1448 #undef PYBIND11_DECL_CHAR_FMT
1450 template <
typename T>
1458 static constexpr
auto name
1463 return pybind11::dtype::from_args(
1468 template <
typename T>
1487 const std::type_info &tinfo,
1489 bool (*direct_converter)(PyObject *,
void *&)) {
1498 std::vector<field_descriptor> ordered_fields(std::move(fields));
1500 ordered_fields.begin(),
1501 ordered_fields.end(),
1505 for (
auto &field : ordered_fields) {
1507 pybind11_fail(std::string(
"NumPy: unsupported field dtype: `") + field.name +
"` @ "
1511 formats.append(field.descr);
1512 offsets.append(pybind11::int_(field.offset));
1527 std::ostringstream oss;
1534 for (
auto &field : ordered_fields) {
1535 if (field.offset >
offset) {
1536 oss << (field.offset -
offset) <<
'x';
1538 oss << field.format <<
':' << field.name <<
':';
1539 offset = field.offset + field.size;
1542 oss << (itemsize -
offset) <<
'x';
1545 auto format_str = oss.str();
1550 if (!
api.PyArray_EquivTypes_(dtype_ptr,
arr.dtype().ptr())) {
1554 auto tindex = std::type_index(tinfo);
1561 template <
typename T,
typename SFINAE>
1564 "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1590 if (!PyObject_TypeCheck(obj,
api.PyVoidArrType_Type_)) {
1593 if (
auto descr = reinterpret_steal<object>(
api.PyArray_DescrFromScalar_(obj))) {
1594 if (
api.PyArray_EquivTypes_(dtype_ptr(),
descr.ptr())) {
1603 #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1604 # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)
1605 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)
1608 # define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
1609 ::pybind11::detail::field_descriptor { \
1610 Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
1611 ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
1612 ::pybind11::detail::npy_format_descriptor< \
1613 decltype(std::declval<T>().Field)>::dtype() \
1617 # define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
1621 # define PYBIND11_EVAL0(...) __VA_ARGS__
1622 # define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__)))
1623 # define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__)))
1624 # define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__)))
1625 # define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__)))
1626 # define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__)))
1627 # define PYBIND11_MAP_END(...)
1628 # define PYBIND11_MAP_OUT
1629 # define PYBIND11_MAP_COMMA ,
1630 # define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1631 # define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1632 # define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0)
1633 # define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next)
1634 # if defined(_MSC_VER) \
1635 && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
1636 # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1637 PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1639 # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1640 PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1642 # define PYBIND11_MAP_LIST_NEXT(test, next) \
1643 PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1644 # define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1645 f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__)
1646 # define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1647 f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__)
1649 # define PYBIND11_MAP_LIST(f, t, ...) \
1650 PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0))
1652 # define PYBIND11_NUMPY_DTYPE(Type, ...) \
1653 ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1654 ::std::vector<::pybind11::detail::field_descriptor>{ \
1655 PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1657 # if defined(_MSC_VER) && !defined(__clang__)
1658 # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1659 PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1661 # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1662 PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1664 # define PYBIND11_MAP2_LIST_NEXT(test, next) \
1665 PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1666 # define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1667 f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__)
1668 # define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1669 f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__)
1671 # define PYBIND11_MAP2_LIST(f, t, ...) \
1672 PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0))
1674 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1675 ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1676 ::std::vector<::pybind11::detail::field_descriptor>{ \
1677 PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1679 #endif // __CLION_IDE__
1690 : p_ptr(reinterpret_cast<char *>(ptr)), m_strides(
strides.
size()) {
1692 for (
size_type i = m_strides.size() - 1;
i != 0; --
i) {
1701 void *
data()
const {
return p_ptr; }
1704 char *p_ptr{
nullptr};
1714 : m_shape(shape.
size()), m_index(shape.
size(), 0), m_common_iterator() {
1717 for (
size_t i = 0;
i < shape.size(); ++
i) {
1718 m_shape[
i] = shape[
i];
1722 for (
size_t i = 0;
i <
N; ++
i) {
1723 init_common_iterator(buffers[
i], shape, m_common_iterator[
i],
strides);
1728 for (
size_t j = m_index.size();
j != 0; --
j) {
1730 if (++m_index[
i] != m_shape[
i]) {
1731 increment_common_iterator(
i);
1739 template <
size_t K,
class T =
void>
1741 return reinterpret_cast<T *
>(m_common_iterator[
K].data());
1751 auto buffer_shape_iter =
buffer.shape.rbegin();
1752 auto buffer_strides_iter =
buffer.strides.rbegin();
1753 auto shape_iter = shape.rbegin();
1754 auto strides_iter =
strides.rbegin();
1756 while (buffer_shape_iter !=
buffer.shape.rend()) {
1757 if (*shape_iter == *buffer_shape_iter) {
1758 *strides_iter = *buffer_strides_iter;
1763 ++buffer_shape_iter;
1764 ++buffer_strides_iter;
1769 std::fill(strides_iter,
strides.rend(), 0);
1774 for (
auto &
iter : m_common_iterator) {
1775 iter.increment(dim);
1792 broadcast(
const std::array<buffer_info, N> &buffers,
ssize_t &ndim, std::vector<ssize_t> &shape) {
1793 ndim = std::accumulate(
1799 shape.resize((
size_t) ndim, 1);
1803 for (
size_t i = 0;
i <
N; ++
i) {
1804 auto res_iter = shape.rbegin();
1805 auto end = buffers[
i].shape.rend();
1806 for (
auto shape_iter = buffers[
i].shape.rbegin(); shape_iter !=
end;
1807 ++shape_iter, ++res_iter) {
1808 const auto &dim_size_in = *shape_iter;
1809 auto &dim_size_out = *res_iter;
1813 if (dim_size_out == 1) {
1814 dim_size_out = dim_size_in;
1815 }
else if (dim_size_in != 1 && dim_size_in != dim_size_out) {
1816 pybind11_fail(
"pybind11::vectorize: incompatible size/dimension of inputs!");
1821 bool trivial_broadcast_c =
true;
1822 bool trivial_broadcast_f =
true;
1823 for (
size_t i = 0;
i <
N && (trivial_broadcast_c || trivial_broadcast_f); ++
i) {
1824 if (buffers[
i].
size == 1) {
1829 if (buffers[
i].ndim != ndim) {
1834 if (!
std::equal(buffers[
i].shape.cbegin(), buffers[
i].shape.cend(), shape.cbegin())) {
1839 if (trivial_broadcast_c) {
1840 ssize_t expect_stride = buffers[
i].itemsize;
1841 auto end = buffers[
i].shape.crend();
1842 for (
auto shape_iter = buffers[
i].shape.crbegin(),
1843 stride_iter = buffers[
i].strides.crbegin();
1844 trivial_broadcast_c && shape_iter !=
end;
1845 ++shape_iter, ++stride_iter) {
1846 if (expect_stride == *stride_iter) {
1847 expect_stride *= *shape_iter;
1849 trivial_broadcast_c =
false;
1855 if (trivial_broadcast_f) {
1856 ssize_t expect_stride = buffers[
i].itemsize;
1857 auto end = buffers[
i].shape.cend();
1858 for (
auto shape_iter = buffers[
i].shape.cbegin(),
1859 stride_iter = buffers[
i].strides.cbegin();
1860 trivial_broadcast_f && shape_iter !=
end;
1861 ++shape_iter, ++stride_iter) {
1862 if (expect_stride == *stride_iter) {
1863 expect_stride *= *shape_iter;
1865 trivial_broadcast_f =
false;
1876 template <
typename T>
1879 "Functions with rvalue reference arguments cannot be vectorized");
1897 template <
typename Func,
typename Return,
typename... Args>
1916 template <
typename Func,
typename... Args>
1932 template <
typename Func,
typename Return,
typename... Args>
1942 static constexpr
size_t N =
sizeof...(Args);
1946 "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
1949 template <
typename T,
1968 template <
size_t Index>
1980 template <
size_t...
Index,
size_t... VIndex,
size_t... BIndex>
1992 std::array<buffer_info, NVectorized> buffers{
1993 {
reinterpret_cast<array *
>(
params[VIndex])->request()...}};
1997 std::vector<ssize_t> shape(0);
1998 auto trivial =
broadcast(buffers, nd, shape);
2002 = std::accumulate(shape.begin(), shape.end(), (
size_t) 1, std::multiplies<size_t>());
2006 if (
size == 1 && ndim == 0) {
2014 PYBIND11_WARNING_PUSH
2015 #ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
2024 auto *mutable_data = returned_array::mutable_data(
result);
2026 apply_broadcast(buffers,
params, mutable_data,
size, shape, i_seq, vi_seq, bi_seq);
2028 apply_trivial(buffers,
params, mutable_data,
size, i_seq, vi_seq, bi_seq);
2035 template <
size_t...
Index,
size_t... VIndex,
size_t... BIndex>
2037 std::array<void *, N> &
params,
2047 std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{
2048 {std::pair<unsigned char *&, const size_t>(
2049 reinterpret_cast<unsigned char *&
>(
params[VIndex] = buffers[BIndex].ptr),
2052 for (
size_t i = 0;
i <
size; ++
i) {
2053 returned_array::call(
2055 for (
auto &
x : vecparams) {
2056 x.first +=
x.second;
2061 template <
size_t...
Index,
size_t... VIndex,
size_t... BIndex>
2063 std::array<void *, N> &
params,
2066 const std::vector<ssize_t> &output_shape,
2073 for (
size_t i = 0;
i <
size; ++
i, ++input_iter) {
2075 returned_array::call(
2081 template <
typename Func,
typename Return,
typename... Args>
2083 return detail::vectorize_helper<Func, Return, Args...>(
f);
2086 template <
typename T,
int Flags>
2088 static constexpr
auto name
2095 template <
typename Return,
typename... Args>
2096 detail::vectorize_helper<Return (*)(Args...), Return, Args...>
vectorize(Return (*
f)(Args...)) {
2097 return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(
f);
2104 (detail::function_signature_t<Func> *)
nullptr)) {
2106 (detail::function_signature_t<Func> *)
nullptr);
2110 template <
typename Return,
2113 typename Helper = detail::vectorize_helper<
2114 decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())),
2119 return Helper(std::mem_fn(
f));
2123 template <
typename Return,
2126 typename Helper = detail::vectorize_helper<
2127 decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)
const>())),
2131 Helper
vectorize(Return (Class::*
f)(Args...)
const) {
2132 return Helper(std::mem_fn(
f));
constexpr ssize_t itemsize() const
typename select_indices_impl< index_sequence<>, 0, Bs... >::type select_indices
std::vector< Eigen::Index > Dims
static module_ import(const char *name)
Import and return a module or throws error_already_set.
ADT create(const Signature &signature)
@ API_PyArray_DescrFromType
char byteorder() const
Single character for byteorder.
ssize_t alignment() const
Alignment of the data type.
std::is_same< bools< Ts::value..., true >, bools< true, Ts::value... > > all_of
static array_t ensure(handle h)
unsigned int PyArray_RUNTIME_VERSION_
#define PYBIND11_CONSTINIT
remove_reference_t< Func > f
ssize_t strides(ssize_t dim) const
Stride along a given axis.
Annotation for function names.
#define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN)
void fail_dim_check(ssize_t dim, const std::string &msg) const
conditional_t< Dynamic, const ssize_t *, std::array< ssize_t,(size_t) Dims > > shape_
Annotation indicating that a class derives from another given type.
detail::unchecked_reference< T, Dims > unchecked() const &
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
bool PyArray_Check_(PyObject *obj) const
array view(const std::string &dtype)
EIGEN_ALWAYS_INLINE DSizes< IndexType, NumDims > strides(const DSizes< IndexType, NumDims > &dimensions)
void check_dimensions(Ix... index) const
array(ShapeContainer shape, StridesContainer strides, const T *ptr, handle base=handle())
@ API_PyArray_DescrConverter
void * mutable_data(Ix... index)
constexpr descr< N - 1 > const_name(char const (&text)[N])
static const double d[K][N]
return_value_policy
Approach used to cast a previously unknown C++ instance into a Python object.
@ API_PyArray_NewFromDescr
ssize_t shape(ssize_t dim) const
Dimension along a given axis.
detail::any_container< ssize_t > ShapeContainer
T * mutable_data(Ix... index)
object run(typename vectorize_arg< Args >::type &...args, index_sequence< Index... > i_seq, index_sequence< VIndex... > vi_seq, index_sequence< BIndex... > bi_seq)
array(const pybind11::dtype &dt, ShapeContainer shape, StridesContainer strides, const void *ptr=nullptr, handle base=handle())
std::vector< ssize_t > f_strides(const std::vector< ssize_t > &shape, ssize_t itemsize)
constexpr size_t constexpr_sum()
Compile-time integer sum.
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
PyTypeObject * PyArray_Type_
array_t(handle h, stolen_t)
const T * data(Ix... index) const
const PyArrayDescr1_Proxy * array_descriptor1_proxy(const PyObject *ptr)
container_type::value_type value_type
PyObject_HEAD PyObject * typeobj
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy x
ssize_t ndim() const
Number of dimensions.
const handle & inc_ref() const &
ssize_t itemsize() const
Byte size of a single element.
static void * mutable_data(Type &)
bool PyArrayDescr_Check_(PyObject *obj) const
PYBIND11_WARNING_PUSH PYBIND11_WARNING_POP
dtype strip_padding(ssize_t itemsize)
static void append_extents(list &shape)
static Return * mutable_data(Type &array)
#define PYBIND11_NAMESPACE_END(name)
bool has_fields() const
Returns true for structured data types.
#define PYBIND11_NOINLINE
const unsigned char * data_
unsigned int(* PyArray_GetNDArrayCFeatureVersion_)()
@ NPY_ARRAY_F_CONTIGUOUS_
Eigen::Triplet< double > T
int(* PyArray_DescrConverter_)(PyObject *, PyObject **)
static bool compare(const buffer_info &b)
dtype(const pybind11::str &format)
broadcast_trivial broadcast(const std::array< buffer_info, N > &buffers, ssize_t &ndim, std::vector< ssize_t > &shape)
#define PYBIND11_NAMESPACE_BEGIN(name)
cout<< "Here is the matrix m:"<< endl<< m<< endl;Matrix< ptrdiff_t, 3, 1 > res
@ NPY_ARRAY_C_CONTIGUOUS_
ssize_t byte_offset_unsafe(const Strides &)
static bool check_(handle h)
array_t(ssize_t count, const T *ptr=nullptr, handle base=handle())
T * mutable_data(Ix... ix)
Mutable pointer access to the data at the given indices.
static const SmartProjectionParams params
static constexpr bool is_array
PYBIND11_DEPRECATED("Use reinterpret_borrow<object>() or reinterpret_steal<object>()") object(handle h
const ssize_t * shape() const
Dimensions of the array.
conditional_t< Dynamic, const ssize_t *, std::array< ssize_t,(size_t) Dims > > strides_
typename std::conditional< B, T, F >::type conditional_t
PyObject_VAR_HEAD char * obval
static constexpr bool Dynamic
all_of< std::is_standard_layout< T >, std::is_trivial< T > > is_pod
ssize_t offset_at() const
static void call(Return *out, size_t i, Func &f, Args &...args)
PyTypeObject * PyArrayDescr_Type_
conditional_t< vectorize, array_t< remove_cv_t< call_type >, array::forcecast >, T > type
static void call(void *, size_t, Func &f, Args &...args)
bool owndata() const
If set, the array owns the data (will be freed when the array is deleted)
void raise_from(PyObject *type, const char *message)
array_t(ShapeContainer shape, const T *ptr=nullptr, handle base=handle())
array(const buffer_info &info, handle base=handle())
detail::any_container< ssize_t > StridesContainer
remove_reference_t< T > call_type
int num() const
type number of dtype.
void increment_common_iterator(size_t dim)
int(* PyArray_SetBaseObject_)(PyObject *, PyObject *)
numpy_internals & get_numpy_internals()
std::tuple< typename vectorize_arg< Args >::call_type... > arg_call_types
static constexpr auto extents
std::vector< ssize_t > container_type
std::unordered_map< std::type_index, numpy_type_info > registered_dtypes
ssize_t nbytes() const
Total number of bytes.
numpy_type_info * get_type_info(bool throw_if_missing=true)
detail::vectorize_helper< Return(*)(Args...), Return, Args... > vectorize(Return(*f)(Args...))
PyObject_HEAD char * data
typename array_info< T >::type remove_all_extents_t
bool(* PyArray_EquivTypes_)(PyObject *, PyObject *)
array(ShapeContainer shape, const T *ptr, handle base=handle())
@ API_PyArray_DescrFromScalar
unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t< Dyn, ssize_t > dims)
detail::unchecked_mutable_reference< T, Dims > mutable_unchecked() &
A small structure to hold a non zero as a triplet (i,j,value).
static void append_extents(list &)
constexpr descr< 0 > concat()
T & operator()(Ix... index)
Mutable, unchecked access to data at the given indices.
static Return call(Func &f, Args &...args)
ssize_t shape(ssize_t dim) const
Returns the shape (i.e. size) of dimension dim
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
static Type create(broadcast_trivial trivial, const std::vector< ssize_t > &shape)
all_of< std::is_standard_layout< T >, std::is_trivially_copyable< T >, satisfies_none_of< T, std::is_reference, std::is_array, is_std_array, std::is_arithmetic, is_complex, std::is_enum > > is_pod_struct
common_iterator(void *ptr, const container_type &strides, const container_type &shape)
dtype(const std::string &format)
void set_error(const handle &type, const char *message)
std::ofstream out("Result.txt")
const T & at(Ix... index) const
multi_array_iterator & operator++()
bool check_flags(const void *ptr, int flag)
ssize_t ndim() const
Returns the number of dimensions of the array.
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set set pointsize set encoding default set nopolar set noparametric set set set set surface set nocontour set clabel set mapping cartesian set nohidden3d set cntrparam order set cntrparam linear set cntrparam levels auto set cntrparam points set size set set xzeroaxis lt lw set x2zeroaxis lt lw set yzeroaxis lt lw set y2zeroaxis lt lw set tics in set ticslevel set tics set mxtics default set mytics default set mx2tics default set my2tics default set xtics border mirror norotate autofreq set ytics border mirror norotate autofreq set ztics border nomirror norotate autofreq set nox2tics set noy2tics set timestamp bottom norotate offset
int(* PyArray_CopyInto_)(PyObject *, PyObject *)
container_type::size_type size_type
std::is_same< detail::remove_cvref_t< T >, U > is_same_ignoring_cvref
Example usage: is_same_ignoring_cvref<T, PyObject *>::value.
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
ssize_t size() const
Total number of elements.
#define PYBIND11_TYPE_CASTER(type, py_name)
detail::unchecked_mutable_reference< T, Dims > mutable_unchecked() &
void check_dimensions_impl(ssize_t, const ssize_t *) const
static dtype of()
Return dtype associated with a C++ type.
void check_writeable() const
array(const pybind11::dtype &dt, ShapeContainer shape, const void *ptr=nullptr, handle base=handle())
std::integral_constant< bool, B > bool_constant
Backports of std::bool_constant and std::negation to accommodate older compilers.
@ API_PyArray_GetNDArrayCFeatureVersion
std::uint64_t flags() const
Flags for the array descriptor.
T & operator[](ssize_t index)
constexpr static ssize_t itemsize()
Returns the item size, i.e. sizeof(T)
array(const pybind11::dtype &dt, T count, const void *ptr=nullptr, handle base=handle())
numpy_type_info * get_type_info(const std::type_info &tinfo, bool throw_if_missing=true)
std::array< common_iter, N > m_common_iterator
#define PYBIND11_OBJECT_DEFAULT(Name, Parent, CheckFun)
constexpr int platform_lookup()
array squeeze()
Return a new view with all of the dimensions of length 1 removed.
type_map< std::vector< bool(*)(PyObject *, void *&)> > direct_conversions
typename make_index_sequence_impl< N >::type make_index_sequence
PyObject * ptr() const
Return the underlying PyObject * pointer.
const void * data(Ix... index) const
multi_array_iterator(const std::array< buffer_info, N > &buffers, const container_type &shape)
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T & back()
static PyObject * raw_array(PyObject *ptr, int ExtraFlags=0)
Create array from any object – always returns a new reference.
Wrapper for Python extension modules.
auto with_internals(const F &cb) -> decltype(cb(get_internals()))
@ API_PyArray_SetBaseObject
PYBIND11_WARNING_PUSH PYBIND11_WARNING_DISABLE_MSVC(5054) PYBIND11_WARNING_POP static_assert(EIGEN_VERSION_AT_LEAST(3
pybind11::dtype dtype() const
Array descriptor (dtype)
handle()=default
The default constructor creates a handle with a nullptr-valued pointer.
detail::unchecked_reference< T, Dims > unchecked() const &
static PyObject * raw_array_t(PyObject *ptr)
Create array from any object – always returns a new reference.
ssize_t byte_offset(Ix... index) const
array reshape(ShapeContainer new_shape)
Optional order parameter omitted, to be added as needed.
iterator iter(handle obj)
static object & _dtype_from_pep3118()
#define DECL_NPY_API(Func)
void apply_broadcast(std::array< buffer_info, NVectorized > &buffers, std::array< void *, N > ¶ms, Return *out, size_t size, const std::vector< ssize_t > &output_shape, index_sequence< Index... >, index_sequence< VIndex... >, index_sequence< BIndex... >)
static array ensure(handle h, int ExtraFlags=0)
typename std::tuple_element< Index, arg_call_types >::type param_n_t
gil_safe_call_once_and_store & call_once_and_store_result(Callable &&fn)
array_t(ShapeContainer shape, StridesContainer strides, const T *ptr=nullptr, handle base=handle())
static Type create(broadcast_trivial, const std::vector< ssize_t > &)
Information record describing a Python buffer object.
array_t(const buffer_info &info, handle base=handle())
PyTypeObject * PyVoidArrType_Type_
const char * c_str(Args &&...args)
enable_if_t<!Dyn, ssize_t > size() const
array_t(handle h, borrowed_t)
void resize(ShapeContainer new_shape, bool refcheck=true)
PYBIND11_NOINLINE module_ import_numpy_core_submodule(const char *submodule_name)
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set offsets
void init_common_iterator(const buffer_info &buffer, const container_type &shape, common_iter &iterator, container_type &strides)
T & mutable_at(Ix... index)
const T * data(Ix... ix) const
Pointer access to the data at the given indices.
enable_if_t< Dyn, ssize_t > size() const
ssize_t index_at(Ix... index) const
static detail::void_type call(Func &f, Args &...args)
object base() const
Base object.
vectorize_helper< Func, Return, Args... > vectorize_extractor(const Func &f, Return(*)(Args...))
#define PYBIND11_DECL_CHAR_FMT
PyArrayDescr_Proxy * descr
unsigned __int64 uint64_t
size_t len(handle h)
Get the length of a Python object.
PYBIND11_NOINLINE void register_structured_dtype(any_container< field_descriptor > fields, const std::type_info &tinfo, ssize_t itemsize, bool(*direct_converter)(PyObject *, void *&))
const PyArrayDescr2_Proxy * array_descriptor2_proxy(const PyObject *ptr)
const T & operator[](ssize_t index) const
PyArrayDescr_Proxy * array_descriptor_proxy(PyObject *ptr)
static const EIGEN_DEPRECATED end_t end
PyObject_HEAD PyObject * typeobj
PYBIND11_NOINLINE void load_numpy_internals(numpy_internals *&ptr)
unchecked_reference(const void *data, const ssize_t *shape, const ssize_t *strides, enable_if_t<!Dyn, ssize_t >)
std::vector< ssize_t > c_strides(const std::vector< ssize_t > &shape, ssize_t itemsize)
array_t(private_ctor, ShapeContainer &&shape, StridesContainer &&strides, const T *ptr, handle base)
static constexpr bool is_empty
std::vector< ssize_t > container_type
void increment(size_type dim)
object operator()(typename vectorize_arg< Args >::type... args)
static BinaryMeasurement< Rot3 > convert(const BetweenFactor< Pose3 >::shared_ptr &f)
@ API_PyArray_DescrNewFromType
Container::iterator get(Container &c, Position position)
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
bool_constant< sizeof(T)==sizeof(U)> as
bool equal(const T &obj1, const T &obj2, double tol)
int flags() const
Return the NumPy array flags.
PyObject_HEAD PyObject * typeobj
bool writeable() const
If set, the array is writeable (otherwise the buffer is read-only)
ssize_t itemsize() const
Size of the data type in bytes.
static dtype from_args(const object &args)
This is essentially the same as calling numpy.dtype(args) in Python.
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
PyArray_Proxy * array_proxy(void *ptr)
ssize_t offset_at(Ix... index) const
const ssize_t * strides() const
Strides of the array.
const T & operator()(Ix... index) const
typename std::remove_reference< T >::type remove_reference_t
dtype(const char *format)
ssize_t index_at(Ix... index) const
void check_dimensions_impl(ssize_t axis, const ssize_t *shape, ssize_t i, Ix... index) const
array(ssize_t count, const T *ptr, handle base=handle())
dtype(list names, list formats, list offsets, ssize_t itemsize)
#define PYBIND11_WARNING_DISABLE_CLANG(name)
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
The Index type as used for the API.
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... >)
gtsam
Author(s):
autogenerated on Fri Nov 1 2024 03:33:52