numpy.h 90 KB

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