test_numpy_array.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /*
  2. tests/test_numpy_array.cpp -- test core array functionality
  3. Copyright (c) 2016 Ivan Smirnov <i.s.smirnov@gmail.com>
  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. #include "pybind11_tests.h"
  8. #include <pybind11/numpy.h>
  9. #include <pybind11/stl.h>
  10. #include <cstdint>
  11. // Size / dtype checks.
  12. struct DtypeCheck {
  13. py::dtype numpy{};
  14. py::dtype pybind11{};
  15. };
  16. template <typename T>
  17. DtypeCheck get_dtype_check(const char* name) {
  18. py::module_ np = py::module_::import("numpy");
  19. DtypeCheck check{};
  20. check.numpy = np.attr("dtype")(np.attr(name));
  21. check.pybind11 = py::dtype::of<T>();
  22. return check;
  23. }
  24. std::vector<DtypeCheck> get_concrete_dtype_checks() {
  25. return {
  26. // Normalization
  27. get_dtype_check<std::int8_t>("int8"),
  28. get_dtype_check<std::uint8_t>("uint8"),
  29. get_dtype_check<std::int16_t>("int16"),
  30. get_dtype_check<std::uint16_t>("uint16"),
  31. get_dtype_check<std::int32_t>("int32"),
  32. get_dtype_check<std::uint32_t>("uint32"),
  33. get_dtype_check<std::int64_t>("int64"),
  34. get_dtype_check<std::uint64_t>("uint64")
  35. };
  36. }
  37. struct DtypeSizeCheck {
  38. std::string name{};
  39. int size_cpp{};
  40. int size_numpy{};
  41. // For debugging.
  42. py::dtype dtype{};
  43. };
  44. template <typename T>
  45. DtypeSizeCheck get_dtype_size_check() {
  46. DtypeSizeCheck check{};
  47. check.name = py::type_id<T>();
  48. check.size_cpp = sizeof(T);
  49. check.dtype = py::dtype::of<T>();
  50. check.size_numpy = check.dtype.attr("itemsize").template cast<int>();
  51. return check;
  52. }
  53. std::vector<DtypeSizeCheck> get_platform_dtype_size_checks() {
  54. return {
  55. get_dtype_size_check<short>(),
  56. get_dtype_size_check<unsigned short>(),
  57. get_dtype_size_check<int>(),
  58. get_dtype_size_check<unsigned int>(),
  59. get_dtype_size_check<long>(),
  60. get_dtype_size_check<unsigned long>(),
  61. get_dtype_size_check<long long>(),
  62. get_dtype_size_check<unsigned long long>(),
  63. };
  64. }
  65. // Arrays.
  66. using arr = py::array;
  67. using arr_t = py::array_t<uint16_t, 0>;
  68. static_assert(std::is_same<arr_t::value_type, uint16_t>::value, "");
  69. template<typename... Ix> arr data(const arr& a, Ix... index) {
  70. return arr(a.nbytes() - a.offset_at(index...), (const uint8_t *) a.data(index...));
  71. }
  72. template<typename... Ix> arr data_t(const arr_t& a, Ix... index) {
  73. return arr(a.size() - a.index_at(index...), a.data(index...));
  74. }
  75. template<typename... Ix> arr& mutate_data(arr& a, Ix... index) {
  76. auto ptr = (uint8_t *) a.mutable_data(index...);
  77. for (py::ssize_t i = 0; i < a.nbytes() - a.offset_at(index...); i++)
  78. ptr[i] = (uint8_t) (ptr[i] * 2);
  79. return a;
  80. }
  81. template<typename... Ix> arr_t& mutate_data_t(arr_t& a, Ix... index) {
  82. auto ptr = a.mutable_data(index...);
  83. for (py::ssize_t i = 0; i < a.size() - a.index_at(index...); i++)
  84. ptr[i]++;
  85. return a;
  86. }
  87. template<typename... Ix> py::ssize_t index_at(const arr& a, Ix... idx) { return a.index_at(idx...); }
  88. template<typename... Ix> py::ssize_t index_at_t(const arr_t& a, Ix... idx) { return a.index_at(idx...); }
  89. template<typename... Ix> py::ssize_t offset_at(const arr& a, Ix... idx) { return a.offset_at(idx...); }
  90. template<typename... Ix> py::ssize_t offset_at_t(const arr_t& a, Ix... idx) { return a.offset_at(idx...); }
  91. template<typename... Ix> py::ssize_t at_t(const arr_t& a, Ix... idx) { return a.at(idx...); }
  92. template<typename... Ix> arr_t& mutate_at_t(arr_t& a, Ix... idx) { a.mutable_at(idx...)++; return a; }
  93. #define def_index_fn(name, type) \
  94. sm.def(#name, [](type a) { return name(a); }); \
  95. sm.def(#name, [](type a, int i) { return name(a, i); }); \
  96. sm.def(#name, [](type a, int i, int j) { return name(a, i, j); }); \
  97. sm.def(#name, [](type a, int i, int j, int k) { return name(a, i, j, k); });
  98. template <typename T, typename T2> py::handle auxiliaries(T &&r, T2 &&r2) {
  99. if (r.ndim() != 2) throw std::domain_error("error: ndim != 2");
  100. py::list l;
  101. l.append(*r.data(0, 0));
  102. l.append(*r2.mutable_data(0, 0));
  103. l.append(r.data(0, 1) == r2.mutable_data(0, 1));
  104. l.append(r.ndim());
  105. l.append(r.itemsize());
  106. l.append(r.shape(0));
  107. l.append(r.shape(1));
  108. l.append(r.size());
  109. l.append(r.nbytes());
  110. return l.release();
  111. }
  112. // note: declaration at local scope would create a dangling reference!
  113. static int data_i = 42;
  114. TEST_SUBMODULE(numpy_array, sm) {
  115. try { py::module_::import("numpy"); }
  116. catch (...) { return; }
  117. // test_dtypes
  118. py::class_<DtypeCheck>(sm, "DtypeCheck")
  119. .def_readonly("numpy", &DtypeCheck::numpy)
  120. .def_readonly("pybind11", &DtypeCheck::pybind11)
  121. .def("__repr__", [](const DtypeCheck& self) {
  122. return py::str("<DtypeCheck numpy={} pybind11={}>").format(
  123. self.numpy, self.pybind11);
  124. });
  125. sm.def("get_concrete_dtype_checks", &get_concrete_dtype_checks);
  126. py::class_<DtypeSizeCheck>(sm, "DtypeSizeCheck")
  127. .def_readonly("name", &DtypeSizeCheck::name)
  128. .def_readonly("size_cpp", &DtypeSizeCheck::size_cpp)
  129. .def_readonly("size_numpy", &DtypeSizeCheck::size_numpy)
  130. .def("__repr__", [](const DtypeSizeCheck& self) {
  131. return py::str("<DtypeSizeCheck name='{}' size_cpp={} size_numpy={} dtype={}>").format(
  132. self.name, self.size_cpp, self.size_numpy, self.dtype);
  133. });
  134. sm.def("get_platform_dtype_size_checks", &get_platform_dtype_size_checks);
  135. // test_array_attributes
  136. sm.def("ndim", [](const arr& a) { return a.ndim(); });
  137. sm.def("shape", [](const arr& a) { return arr(a.ndim(), a.shape()); });
  138. sm.def("shape", [](const arr& a, py::ssize_t dim) { return a.shape(dim); });
  139. sm.def("strides", [](const arr& a) { return arr(a.ndim(), a.strides()); });
  140. sm.def("strides", [](const arr& a, py::ssize_t dim) { return a.strides(dim); });
  141. sm.def("writeable", [](const arr& a) { return a.writeable(); });
  142. sm.def("size", [](const arr& a) { return a.size(); });
  143. sm.def("itemsize", [](const arr& a) { return a.itemsize(); });
  144. sm.def("nbytes", [](const arr& a) { return a.nbytes(); });
  145. sm.def("owndata", [](const arr& a) { return a.owndata(); });
  146. // test_index_offset
  147. def_index_fn(index_at, const arr&);
  148. def_index_fn(index_at_t, const arr_t&);
  149. def_index_fn(offset_at, const arr&);
  150. def_index_fn(offset_at_t, const arr_t&);
  151. // test_data
  152. def_index_fn(data, const arr&);
  153. def_index_fn(data_t, const arr_t&);
  154. // test_mutate_data, test_mutate_readonly
  155. def_index_fn(mutate_data, arr&);
  156. def_index_fn(mutate_data_t, arr_t&);
  157. def_index_fn(at_t, const arr_t&);
  158. def_index_fn(mutate_at_t, arr_t&);
  159. // test_make_c_f_array
  160. sm.def("make_f_array", [] { return py::array_t<float>({ 2, 2 }, { 4, 8 }); });
  161. sm.def("make_c_array", [] { return py::array_t<float>({ 2, 2 }, { 8, 4 }); });
  162. // test_empty_shaped_array
  163. sm.def("make_empty_shaped_array", [] { return py::array(py::dtype("f"), {}, {}); });
  164. // test numpy scalars (empty shape, ndim==0)
  165. sm.def("scalar_int", []() { return py::array(py::dtype("i"), {}, {}, &data_i); });
  166. // test_wrap
  167. sm.def("wrap", [](py::array a) {
  168. return py::array(
  169. a.dtype(),
  170. {a.shape(), a.shape() + a.ndim()},
  171. {a.strides(), a.strides() + a.ndim()},
  172. a.data(),
  173. a
  174. );
  175. });
  176. // test_numpy_view
  177. struct ArrayClass {
  178. int data[2] = { 1, 2 };
  179. ArrayClass() { py::print("ArrayClass()"); }
  180. ~ArrayClass() { py::print("~ArrayClass()"); }
  181. };
  182. py::class_<ArrayClass>(sm, "ArrayClass")
  183. .def(py::init<>())
  184. .def("numpy_view", [](py::object &obj) {
  185. py::print("ArrayClass::numpy_view()");
  186. auto &a = obj.cast<ArrayClass&>();
  187. return py::array_t<int>({2}, {4}, a.data, obj);
  188. }
  189. );
  190. // test_cast_numpy_int64_to_uint64
  191. sm.def("function_taking_uint64", [](uint64_t) { });
  192. // test_isinstance
  193. sm.def("isinstance_untyped", [](py::object yes, py::object no) {
  194. return py::isinstance<py::array>(yes) && !py::isinstance<py::array>(no);
  195. });
  196. sm.def("isinstance_typed", [](py::object o) {
  197. return py::isinstance<py::array_t<double>>(o) && !py::isinstance<py::array_t<int>>(o);
  198. });
  199. // test_constructors
  200. sm.def("default_constructors", []() {
  201. return py::dict(
  202. "array"_a=py::array(),
  203. "array_t<int32>"_a=py::array_t<std::int32_t>(),
  204. "array_t<double>"_a=py::array_t<double>()
  205. );
  206. });
  207. sm.def("converting_constructors", [](py::object o) {
  208. return py::dict(
  209. "array"_a=py::array(o),
  210. "array_t<int32>"_a=py::array_t<std::int32_t>(o),
  211. "array_t<double>"_a=py::array_t<double>(o)
  212. );
  213. });
  214. // test_overload_resolution
  215. sm.def("overloaded", [](py::array_t<double>) { return "double"; });
  216. sm.def("overloaded", [](py::array_t<float>) { return "float"; });
  217. sm.def("overloaded", [](py::array_t<int>) { return "int"; });
  218. sm.def("overloaded", [](py::array_t<unsigned short>) { return "unsigned short"; });
  219. sm.def("overloaded", [](py::array_t<long long>) { return "long long"; });
  220. sm.def("overloaded", [](py::array_t<std::complex<double>>) { return "double complex"; });
  221. sm.def("overloaded", [](py::array_t<std::complex<float>>) { return "float complex"; });
  222. sm.def("overloaded2", [](py::array_t<std::complex<double>>) { return "double complex"; });
  223. sm.def("overloaded2", [](py::array_t<double>) { return "double"; });
  224. sm.def("overloaded2", [](py::array_t<std::complex<float>>) { return "float complex"; });
  225. sm.def("overloaded2", [](py::array_t<float>) { return "float"; });
  226. // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
  227. // Only accept the exact types:
  228. sm.def("overloaded3", [](py::array_t<int>) { return "int"; }, py::arg{}.noconvert());
  229. sm.def("overloaded3", [](py::array_t<double>) { return "double"; }, py::arg{}.noconvert());
  230. // Make sure we don't do unsafe coercion (e.g. float to int) when not using forcecast, but
  231. // rather that float gets converted via the safe (conversion to double) overload:
  232. sm.def("overloaded4", [](py::array_t<long long, 0>) { return "long long"; });
  233. sm.def("overloaded4", [](py::array_t<double, 0>) { return "double"; });
  234. // But we do allow conversion to int if forcecast is enabled (but only if no overload matches
  235. // without conversion)
  236. sm.def("overloaded5", [](py::array_t<unsigned int>) { return "unsigned int"; });
  237. sm.def("overloaded5", [](py::array_t<double>) { return "double"; });
  238. // test_greedy_string_overload
  239. // Issue 685: ndarray shouldn't go to std::string overload
  240. sm.def("issue685", [](std::string) { return "string"; });
  241. sm.def("issue685", [](py::array) { return "array"; });
  242. sm.def("issue685", [](py::object) { return "other"; });
  243. // test_array_unchecked_fixed_dims
  244. sm.def("proxy_add2", [](py::array_t<double> a, double v) {
  245. auto r = a.mutable_unchecked<2>();
  246. for (py::ssize_t i = 0; i < r.shape(0); i++)
  247. for (py::ssize_t j = 0; j < r.shape(1); j++)
  248. r(i, j) += v;
  249. }, py::arg{}.noconvert(), py::arg());
  250. sm.def("proxy_init3", [](double start) {
  251. py::array_t<double, py::array::c_style> a({ 3, 3, 3 });
  252. auto r = a.mutable_unchecked<3>();
  253. for (py::ssize_t i = 0; i < r.shape(0); i++)
  254. for (py::ssize_t j = 0; j < r.shape(1); j++)
  255. for (py::ssize_t k = 0; k < r.shape(2); k++)
  256. r(i, j, k) = start++;
  257. return a;
  258. });
  259. sm.def("proxy_init3F", [](double start) {
  260. py::array_t<double, py::array::f_style> a({ 3, 3, 3 });
  261. auto r = a.mutable_unchecked<3>();
  262. for (py::ssize_t k = 0; k < r.shape(2); k++)
  263. for (py::ssize_t j = 0; j < r.shape(1); j++)
  264. for (py::ssize_t i = 0; i < r.shape(0); i++)
  265. r(i, j, k) = start++;
  266. return a;
  267. });
  268. sm.def("proxy_squared_L2_norm", [](py::array_t<double> a) {
  269. auto r = a.unchecked<1>();
  270. double sumsq = 0;
  271. for (py::ssize_t i = 0; i < r.shape(0); i++)
  272. sumsq += r[i] * r(i); // Either notation works for a 1D array
  273. return sumsq;
  274. });
  275. sm.def("proxy_auxiliaries2", [](py::array_t<double> a) {
  276. auto r = a.unchecked<2>();
  277. auto r2 = a.mutable_unchecked<2>();
  278. return auxiliaries(r, r2);
  279. });
  280. sm.def("proxy_auxiliaries1_const_ref", [](py::array_t<double> a) {
  281. const auto &r = a.unchecked<1>();
  282. const auto &r2 = a.mutable_unchecked<1>();
  283. return r(0) == r2(0) && r[0] == r2[0];
  284. });
  285. sm.def("proxy_auxiliaries2_const_ref", [](py::array_t<double> a) {
  286. const auto &r = a.unchecked<2>();
  287. const auto &r2 = a.mutable_unchecked<2>();
  288. return r(0, 0) == r2(0, 0);
  289. });
  290. // test_array_unchecked_dyn_dims
  291. // Same as the above, but without a compile-time dimensions specification:
  292. sm.def("proxy_add2_dyn", [](py::array_t<double> a, double v) {
  293. auto r = a.mutable_unchecked();
  294. if (r.ndim() != 2) throw std::domain_error("error: ndim != 2");
  295. for (py::ssize_t i = 0; i < r.shape(0); i++)
  296. for (py::ssize_t j = 0; j < r.shape(1); j++)
  297. r(i, j) += v;
  298. }, py::arg{}.noconvert(), py::arg());
  299. sm.def("proxy_init3_dyn", [](double start) {
  300. py::array_t<double, py::array::c_style> a({ 3, 3, 3 });
  301. auto r = a.mutable_unchecked();
  302. if (r.ndim() != 3) throw std::domain_error("error: ndim != 3");
  303. for (py::ssize_t i = 0; i < r.shape(0); i++)
  304. for (py::ssize_t j = 0; j < r.shape(1); j++)
  305. for (py::ssize_t k = 0; k < r.shape(2); k++)
  306. r(i, j, k) = start++;
  307. return a;
  308. });
  309. sm.def("proxy_auxiliaries2_dyn", [](py::array_t<double> a) {
  310. return auxiliaries(a.unchecked(), a.mutable_unchecked());
  311. });
  312. sm.def("array_auxiliaries2", [](py::array_t<double> a) {
  313. return auxiliaries(a, a);
  314. });
  315. // test_array_failures
  316. // Issue #785: Uninformative "Unknown internal error" exception when constructing array from empty object:
  317. sm.def("array_fail_test", []() { return py::array(py::object()); });
  318. sm.def("array_t_fail_test", []() { return py::array_t<double>(py::object()); });
  319. // Make sure the error from numpy is being passed through:
  320. sm.def("array_fail_test_negative_size", []() { int c = 0; return py::array(-1, &c); });
  321. // test_initializer_list
  322. // Issue (unnumbered; reported in #788): regression: initializer lists can be ambiguous
  323. sm.def("array_initializer_list1", []() { return py::array_t<float>(1); }); // { 1 } also works, but clang warns about it
  324. sm.def("array_initializer_list2", []() { return py::array_t<float>({ 1, 2 }); });
  325. sm.def("array_initializer_list3", []() { return py::array_t<float>({ 1, 2, 3 }); });
  326. sm.def("array_initializer_list4", []() { return py::array_t<float>({ 1, 2, 3, 4 }); });
  327. // test_array_resize
  328. // reshape array to 2D without changing size
  329. sm.def("array_reshape2", [](py::array_t<double> a) {
  330. const auto dim_sz = (py::ssize_t)std::sqrt(a.size());
  331. if (dim_sz * dim_sz != a.size())
  332. throw std::domain_error("array_reshape2: input array total size is not a squared integer");
  333. a.resize({dim_sz, dim_sz});
  334. });
  335. // resize to 3D array with each dimension = N
  336. sm.def("array_resize3", [](py::array_t<double> a, size_t N, bool refcheck) {
  337. a.resize({N, N, N}, refcheck);
  338. });
  339. // test_array_create_and_resize
  340. // return 2D array with Nrows = Ncols = N
  341. sm.def("create_and_resize", [](size_t N) {
  342. py::array_t<double> a;
  343. a.resize({N, N});
  344. std::fill(a.mutable_data(), a.mutable_data() + a.size(), 42.);
  345. return a;
  346. });
  347. sm.def("index_using_ellipsis", [](py::array a) {
  348. return a[py::make_tuple(0, py::ellipsis(), 0)];
  349. });
  350. // test_argument_conversions
  351. sm.def("accept_double",
  352. [](py::array_t<double, 0>) {},
  353. py::arg("a"));
  354. sm.def("accept_double_forcecast",
  355. [](py::array_t<double, py::array::forcecast>) {},
  356. py::arg("a"));
  357. sm.def("accept_double_c_style",
  358. [](py::array_t<double, py::array::c_style>) {},
  359. py::arg("a"));
  360. sm.def("accept_double_c_style_forcecast",
  361. [](py::array_t<double, py::array::forcecast | py::array::c_style>) {},
  362. py::arg("a"));
  363. sm.def("accept_double_f_style",
  364. [](py::array_t<double, py::array::f_style>) {},
  365. py::arg("a"));
  366. sm.def("accept_double_f_style_forcecast",
  367. [](py::array_t<double, py::array::forcecast | py::array::f_style>) {},
  368. py::arg("a"));
  369. sm.def("accept_double_noconvert",
  370. [](py::array_t<double, 0>) {},
  371. "a"_a.noconvert());
  372. sm.def("accept_double_forcecast_noconvert",
  373. [](py::array_t<double, py::array::forcecast>) {},
  374. "a"_a.noconvert());
  375. sm.def("accept_double_c_style_noconvert",
  376. [](py::array_t<double, py::array::c_style>) {},
  377. "a"_a.noconvert());
  378. sm.def("accept_double_c_style_forcecast_noconvert",
  379. [](py::array_t<double, py::array::forcecast | py::array::c_style>) {},
  380. "a"_a.noconvert());
  381. sm.def("accept_double_f_style_noconvert",
  382. [](py::array_t<double, py::array::f_style>) {},
  383. "a"_a.noconvert());
  384. sm.def("accept_double_f_style_forcecast_noconvert",
  385. [](py::array_t<double, py::array::forcecast | py::array::f_style>) {},
  386. "a"_a.noconvert());
  387. }