numpy.h 78 KB

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