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>
907 reinterpret_cast<const void *>(
ptr),
910 template <
typename T>
914 template <
typename T>
980 template <
typename... Ix>
981 const void *
data(Ix... index)
const {
988 template <
typename... Ix>
996 template <
typename... Ix>
999 fail_dim_check(
sizeof...(index),
"too many indices for an array");
1008 template <
typename... Ix>
1022 throw std::domain_error(
"array has incorrect number of dimensions: "
1023 + std::to_string(
ndim()) +
"; expected "
1024 + std::to_string(
Dims));
1026 return detail::unchecked_mutable_reference<T, Dims>(
1040 throw std::domain_error(
"array has incorrect number of dimensions: "
1041 + std::to_string(
ndim()) +
"; expected "
1042 + std::to_string(
Dims));
1050 return reinterpret_steal<array>(
api.PyArray_Squeeze_(
m_ptr));
1057 detail::npy_api::PyArray_Dims
d
1059 reinterpret_cast<Py_intptr_t *
>(new_shape->data()),
1060 int(new_shape->size())};
1062 auto new_array = reinterpret_steal<object>(
1067 if (isinstance<array>(new_array)) {
1068 *
this = std::move(new_array);
1074 detail::npy_api::PyArray_Dims
d
1075 = {
reinterpret_cast<Py_intptr_t *
>(new_shape->data()),
int(new_shape->size())};
1091 auto new_view = reinterpret_steal<array>(
api.PyArray_View_(
1110 template <
typename,
typename>
1111 friend struct detail::npy_format_descriptor;
1114 throw index_error(
msg +
": " + std::to_string(dim) +
" (ndim = " + std::to_string(
ndim())
1118 template <
typename... Ix>
1126 throw std::domain_error(
"array is not writeable");
1130 template <
typename... Ix>
1137 template <
typename... Ix>
1140 throw index_error(std::string(
"index ") + std::to_string(
i)
1141 +
" is out of bounds for axis " + std::to_string(axis)
1142 +
" with size " + std::to_string(*
shape));
1149 if (
ptr ==
nullptr) {
1150 set_error(PyExc_ValueError,
"cannot create a pybind11::array from a nullptr");
1154 ptr,
nullptr, 0, 0, detail::npy_api::NPY_ARRAY_ENSUREARRAY_ | ExtraFlags,
nullptr);
1158 template <
typename T,
int ExtraFlags = array::forcecast>
1171 static_assert(!detail::array_info<T>::is_array,
"Array types cannot be used with array_t");
1185 Py_XDECREF(
h.ptr());
1200 const T *
ptr =
nullptr,
1217 template <
typename... Ix>
1222 template <
typename... Ix>
1227 template <
typename... Ix>
1233 template <
typename... Ix>
1234 const T &
at(Ix... index)
const {
1243 template <
typename... Ix>
1260 return array::mutable_unchecked<T, Dims>();
1272 return array::unchecked<T, Dims>();
1287 return api.PyArray_Check_(
h.ptr())
1289 dtype::of<T>().ptr())
1296 if (
ptr ==
nullptr) {
1297 set_error(PyExc_ValueError,
"cannot create a pybind11::array_t from a nullptr");
1304 detail::npy_api::NPY_ARRAY_ENSUREARRAY_
1310 template <
typename T>
1319 static std::string
format() {
return std::to_string(
N) +
's'; }
1323 static std::string
format() {
return std::to_string(
N) +
's'; }
1326 template <
typename T>
1334 template <
typename T>
1344 template <
typename T,
int ExtraFlags>
1349 if (!
convert && !type::check_(src)) {
1352 value = type::ensure(src);
1353 return static_cast<bool>(
value);
1362 template <
typename T>
1369 template <
typename T,
typename =
void>
1372 template <
typename T>
1380 template <
typename T>
1386 > (
const_name(
"numpy.float") + const_name<sizeof(T) * 8>(),
1390 template <
typename T>
1397 + const_name<sizeof(typename T::value_type) * 16>(),
1401 template <
typename T>
1425 static constexpr
int value =
values[detail::is_fmt_numeric<T>::index];
1430 template <
typename T>
1439 #define PYBIND11_DECL_CHAR_FMT \
1440 static constexpr auto name = const_name("S") + const_name<N>(); \
1441 static pybind11::dtype dtype() { \
1442 return pybind11::dtype(std::string("S") + std::to_string(N)); \
1452 #undef PYBIND11_DECL_CHAR_FMT
1454 template <
typename T>
1462 static constexpr
auto name
1467 return pybind11::dtype::from_args(
1472 template <
typename T>
1491 const std::type_info &tinfo,
1493 bool (*direct_converter)(PyObject *,
void *&)) {
1502 std::vector<field_descriptor> ordered_fields(std::move(fields));
1504 ordered_fields.begin(),
1505 ordered_fields.end(),
1509 for (
auto &field : ordered_fields) {
1511 pybind11_fail(std::string(
"NumPy: unsupported field dtype: `") + field.name +
"` @ "
1515 formats.append(field.descr);
1516 offsets.append(pybind11::int_(field.offset));
1531 std::ostringstream oss;
1538 for (
auto &field : ordered_fields) {
1539 if (field.offset >
offset) {
1540 oss << (field.offset -
offset) <<
'x';
1542 oss << field.format <<
':' << field.name <<
':';
1543 offset = field.offset + field.size;
1546 oss << (itemsize -
offset) <<
'x';
1549 auto format_str = oss.str();
1554 if (!
api.PyArray_EquivTypes_(dtype_ptr,
arr.dtype().ptr())) {
1558 auto tindex = std::type_index(tinfo);
1565 template <
typename T,
typename SFINAE>
1568 "Attempt to use a non-POD or unimplemented POD type as a numpy dtype");
1594 if (!PyObject_TypeCheck(obj,
api.PyVoidArrType_Type_)) {
1597 if (
auto descr = reinterpret_steal<object>(
api.PyArray_DescrFromScalar_(obj))) {
1598 if (
api.PyArray_EquivTypes_(dtype_ptr(),
descr.ptr())) {
1607 #ifdef __CLION_IDE__ // replace heavy macro with dummy code for the IDE (doesn't affect code)
1608 # define PYBIND11_NUMPY_DTYPE(Type, ...) ((void) 0)
1609 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) ((void) 0)
1612 # define PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, Name) \
1613 ::pybind11::detail::field_descriptor { \
1614 Name, offsetof(T, Field), sizeof(decltype(std::declval<T>().Field)), \
1615 ::pybind11::format_descriptor<decltype(std::declval<T>().Field)>::format(), \
1616 ::pybind11::detail::npy_format_descriptor< \
1617 decltype(std::declval<T>().Field)>::dtype() \
1621 # define PYBIND11_FIELD_DESCRIPTOR(T, Field) PYBIND11_FIELD_DESCRIPTOR_EX(T, Field, #Field)
1625 # define PYBIND11_EVAL0(...) __VA_ARGS__
1626 # define PYBIND11_EVAL1(...) PYBIND11_EVAL0(PYBIND11_EVAL0(PYBIND11_EVAL0(__VA_ARGS__)))
1627 # define PYBIND11_EVAL2(...) PYBIND11_EVAL1(PYBIND11_EVAL1(PYBIND11_EVAL1(__VA_ARGS__)))
1628 # define PYBIND11_EVAL3(...) PYBIND11_EVAL2(PYBIND11_EVAL2(PYBIND11_EVAL2(__VA_ARGS__)))
1629 # define PYBIND11_EVAL4(...) PYBIND11_EVAL3(PYBIND11_EVAL3(PYBIND11_EVAL3(__VA_ARGS__)))
1630 # define PYBIND11_EVAL(...) PYBIND11_EVAL4(PYBIND11_EVAL4(PYBIND11_EVAL4(__VA_ARGS__)))
1631 # define PYBIND11_MAP_END(...)
1632 # define PYBIND11_MAP_OUT
1633 # define PYBIND11_MAP_COMMA ,
1634 # define PYBIND11_MAP_GET_END() 0, PYBIND11_MAP_END
1635 # define PYBIND11_MAP_NEXT0(test, next, ...) next PYBIND11_MAP_OUT
1636 # define PYBIND11_MAP_NEXT1(test, next) PYBIND11_MAP_NEXT0(test, next, 0)
1637 # define PYBIND11_MAP_NEXT(test, next) PYBIND11_MAP_NEXT1(PYBIND11_MAP_GET_END test, next)
1638 # if defined(_MSC_VER) \
1639 && !defined(__clang__) // MSVC is not as eager to expand macros, hence this workaround
1640 # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1641 PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1643 # define PYBIND11_MAP_LIST_NEXT1(test, next) \
1644 PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1646 # define PYBIND11_MAP_LIST_NEXT(test, next) \
1647 PYBIND11_MAP_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1648 # define PYBIND11_MAP_LIST0(f, t, x, peek, ...) \
1649 f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST1)(f, t, peek, __VA_ARGS__)
1650 # define PYBIND11_MAP_LIST1(f, t, x, peek, ...) \
1651 f(t, x) PYBIND11_MAP_LIST_NEXT(peek, PYBIND11_MAP_LIST0)(f, t, peek, __VA_ARGS__)
1653 # define PYBIND11_MAP_LIST(f, t, ...) \
1654 PYBIND11_EVAL(PYBIND11_MAP_LIST1(f, t, __VA_ARGS__, (), 0))
1656 # define PYBIND11_NUMPY_DTYPE(Type, ...) \
1657 ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1658 ::std::vector<::pybind11::detail::field_descriptor>{ \
1659 PYBIND11_MAP_LIST(PYBIND11_FIELD_DESCRIPTOR, Type, __VA_ARGS__)})
1661 # if defined(_MSC_VER) && !defined(__clang__)
1662 # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1663 PYBIND11_EVAL0(PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0))
1665 # define PYBIND11_MAP2_LIST_NEXT1(test, next) \
1666 PYBIND11_MAP_NEXT0(test, PYBIND11_MAP_COMMA next, 0)
1668 # define PYBIND11_MAP2_LIST_NEXT(test, next) \
1669 PYBIND11_MAP2_LIST_NEXT1(PYBIND11_MAP_GET_END test, next)
1670 # define PYBIND11_MAP2_LIST0(f, t, x1, x2, peek, ...) \
1671 f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST1)(f, t, peek, __VA_ARGS__)
1672 # define PYBIND11_MAP2_LIST1(f, t, x1, x2, peek, ...) \
1673 f(t, x1, x2) PYBIND11_MAP2_LIST_NEXT(peek, PYBIND11_MAP2_LIST0)(f, t, peek, __VA_ARGS__)
1675 # define PYBIND11_MAP2_LIST(f, t, ...) \
1676 PYBIND11_EVAL(PYBIND11_MAP2_LIST1(f, t, __VA_ARGS__, (), 0))
1678 # define PYBIND11_NUMPY_DTYPE_EX(Type, ...) \
1679 ::pybind11::detail::npy_format_descriptor<Type>::register_dtype( \
1680 ::std::vector<::pybind11::detail::field_descriptor>{ \
1681 PYBIND11_MAP2_LIST(PYBIND11_FIELD_DESCRIPTOR_EX, Type, __VA_ARGS__)})
1683 #endif // __CLION_IDE__
1694 : p_ptr(reinterpret_cast<char *>(ptr)), m_strides(
strides.
size()) {
1696 for (
size_type i = m_strides.size() - 1;
i != 0; --
i) {
1705 void *
data()
const {
return p_ptr; }
1708 char *p_ptr{
nullptr};
1718 : m_shape(shape.
size()), m_index(shape.
size(), 0), m_common_iterator() {
1721 for (
size_t i = 0;
i < shape.size(); ++
i) {
1722 m_shape[
i] = shape[
i];
1726 for (
size_t i = 0;
i <
N; ++
i) {
1727 init_common_iterator(buffers[
i], shape, m_common_iterator[
i],
strides);
1732 for (
size_t j = m_index.size();
j != 0; --
j) {
1734 if (++m_index[
i] != m_shape[
i]) {
1735 increment_common_iterator(
i);
1743 template <
size_t K,
class T =
void>
1745 return reinterpret_cast<T *
>(m_common_iterator[
K].data());
1755 auto buffer_shape_iter =
buffer.shape.rbegin();
1756 auto buffer_strides_iter =
buffer.strides.rbegin();
1757 auto shape_iter = shape.rbegin();
1758 auto strides_iter =
strides.rbegin();
1760 while (buffer_shape_iter !=
buffer.shape.rend()) {
1761 if (*shape_iter == *buffer_shape_iter) {
1762 *strides_iter = *buffer_strides_iter;
1767 ++buffer_shape_iter;
1768 ++buffer_strides_iter;
1773 std::fill(strides_iter,
strides.rend(), 0);
1778 for (
auto &
iter : m_common_iterator) {
1779 iter.increment(dim);
1796 broadcast(
const std::array<buffer_info, N> &buffers,
ssize_t &ndim, std::vector<ssize_t> &shape) {
1797 ndim = std::accumulate(
1803 shape.resize((
size_t) ndim, 1);
1807 for (
size_t i = 0;
i <
N; ++
i) {
1808 auto res_iter = shape.rbegin();
1809 auto end = buffers[
i].shape.rend();
1810 for (
auto shape_iter = buffers[
i].shape.rbegin(); shape_iter !=
end;
1811 ++shape_iter, ++res_iter) {
1812 const auto &dim_size_in = *shape_iter;
1813 auto &dim_size_out = *res_iter;
1817 if (dim_size_out == 1) {
1818 dim_size_out = dim_size_in;
1819 }
else if (dim_size_in != 1 && dim_size_in != dim_size_out) {
1820 pybind11_fail(
"pybind11::vectorize: incompatible size/dimension of inputs!");
1825 bool trivial_broadcast_c =
true;
1826 bool trivial_broadcast_f =
true;
1827 for (
size_t i = 0;
i <
N && (trivial_broadcast_c || trivial_broadcast_f); ++
i) {
1828 if (buffers[
i].
size == 1) {
1833 if (buffers[
i].ndim != ndim) {
1838 if (!
std::equal(buffers[
i].shape.cbegin(), buffers[
i].shape.cend(), shape.cbegin())) {
1843 if (trivial_broadcast_c) {
1844 ssize_t expect_stride = buffers[
i].itemsize;
1845 auto end = buffers[
i].shape.crend();
1846 for (
auto shape_iter = buffers[
i].shape.crbegin(),
1847 stride_iter = buffers[
i].strides.crbegin();
1848 trivial_broadcast_c && shape_iter !=
end;
1849 ++shape_iter, ++stride_iter) {
1850 if (expect_stride == *stride_iter) {
1851 expect_stride *= *shape_iter;
1853 trivial_broadcast_c =
false;
1859 if (trivial_broadcast_f) {
1860 ssize_t expect_stride = buffers[
i].itemsize;
1861 auto end = buffers[
i].shape.cend();
1862 for (
auto shape_iter = buffers[
i].shape.cbegin(),
1863 stride_iter = buffers[
i].strides.cbegin();
1864 trivial_broadcast_f && shape_iter !=
end;
1865 ++shape_iter, ++stride_iter) {
1866 if (expect_stride == *stride_iter) {
1867 expect_stride *= *shape_iter;
1869 trivial_broadcast_f =
false;
1880 template <
typename T>
1883 "Functions with rvalue reference arguments cannot be vectorized");
1901 template <
typename Func,
typename Return,
typename... Args>
1920 template <
typename Func,
typename... Args>
1936 template <
typename Func,
typename Return,
typename... Args>
1946 static constexpr
size_t N =
sizeof...(Args);
1950 "pybind11::vectorize(...) requires a function with at least one vectorizable argument");
1953 template <
typename T,
1972 template <
size_t Index>
1984 template <
size_t...
Index,
size_t... VIndex,
size_t... BIndex>
1993 std::array<void *, N>
params{{
reinterpret_cast<void *
>(&
args)...}};
1996 std::array<buffer_info, NVectorized> buffers{
1997 {
reinterpret_cast<array *
>(
params[VIndex])->request()...}};
2001 std::vector<ssize_t> shape(0);
2002 auto trivial =
broadcast(buffers, nd, shape);
2006 = std::accumulate(shape.begin(), shape.end(), (
size_t) 1, std::multiplies<size_t>());
2010 if (
size == 1 && ndim == 0) {
2018 PYBIND11_WARNING_PUSH
2019 #ifdef PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
2028 auto *mutable_data = returned_array::mutable_data(
result);
2030 apply_broadcast(buffers,
params, mutable_data,
size, shape, i_seq, vi_seq, bi_seq);
2032 apply_trivial(buffers,
params, mutable_data,
size, i_seq, vi_seq, bi_seq);
2039 template <
size_t...
Index,
size_t... VIndex,
size_t... BIndex>
2041 std::array<void *, N> &
params,
2051 std::array<std::pair<unsigned char *&, const size_t>, NVectorized> vecparams{
2052 {std::pair<unsigned char *&, const size_t>(
2053 reinterpret_cast<unsigned char *&
>(
params[VIndex] = buffers[BIndex].ptr),
2056 for (
size_t i = 0;
i <
size; ++
i) {
2057 returned_array::call(
2059 for (
auto &
x : vecparams) {
2060 x.first +=
x.second;
2065 template <
size_t...
Index,
size_t... VIndex,
size_t... BIndex>
2067 std::array<void *, N> &
params,
2070 const std::vector<ssize_t> &output_shape,
2077 for (
size_t i = 0;
i <
size; ++
i, ++input_iter) {
2079 returned_array::call(
2085 template <
typename Func,
typename Return,
typename... Args>
2087 return detail::vectorize_helper<Func, Return, Args...>(
f);
2090 template <
typename T,
int Flags>
2092 static constexpr
auto name
2099 template <
typename Return,
typename... Args>
2100 detail::vectorize_helper<Return (*)(Args...), Return, Args...>
vectorize(Return (*
f)(Args...)) {
2101 return detail::vectorize_helper<Return (*)(Args...), Return, Args...>(
f);
2108 (detail::function_signature_t<Func> *)
nullptr)) {
2110 (detail::function_signature_t<Func> *)
nullptr);
2114 template <
typename Return,
2117 typename Helper = detail::vectorize_helper<
2118 decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)>())),
2123 return Helper(std::mem_fn(
f));
2127 template <
typename Return,
2130 typename Helper = detail::vectorize_helper<
2131 decltype(std::mem_fn(std::declval<Return (Class::*)(Args...)
const>())),
2135 Helper
vectorize(Return (Class::*
f)(Args...)
const) {
2136 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 Wed Mar 19 2025 03:02:34