numpy.h 82 KB

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