test_numpy_array.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. tests/test_numpy_array.cpp -- test core array functionality
  3. Copyright (c) 2016 Ivan Smirnov <[email protected]>
  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. using arr = py::array;
  12. using arr_t = py::array_t<uint16_t, 0>;
  13. static_assert(std::is_same<arr_t::value_type, uint16_t>::value, "");
  14. template<typename... Ix> arr data(const arr& a, Ix... index) {
  15. return arr(a.nbytes() - a.offset_at(index...), (const uint8_t *) a.data(index...));
  16. }
  17. template<typename... Ix> arr data_t(const arr_t& a, Ix... index) {
  18. return arr(a.size() - a.index_at(index...), a.data(index...));
  19. }
  20. template<typename... Ix> arr& mutate_data(arr& a, Ix... index) {
  21. auto ptr = (uint8_t *) a.mutable_data(index...);
  22. for (ssize_t i = 0; i < a.nbytes() - a.offset_at(index...); i++)
  23. ptr[i] = (uint8_t) (ptr[i] * 2);
  24. return a;
  25. }
  26. template<typename... Ix> arr_t& mutate_data_t(arr_t& a, Ix... index) {
  27. auto ptr = a.mutable_data(index...);
  28. for (ssize_t i = 0; i < a.size() - a.index_at(index...); i++)
  29. ptr[i]++;
  30. return a;
  31. }
  32. template<typename... Ix> ssize_t index_at(const arr& a, Ix... idx) { return a.index_at(idx...); }
  33. template<typename... Ix> ssize_t index_at_t(const arr_t& a, Ix... idx) { return a.index_at(idx...); }
  34. template<typename... Ix> ssize_t offset_at(const arr& a, Ix... idx) { return a.offset_at(idx...); }
  35. template<typename... Ix> ssize_t offset_at_t(const arr_t& a, Ix... idx) { return a.offset_at(idx...); }
  36. template<typename... Ix> ssize_t at_t(const arr_t& a, Ix... idx) { return a.at(idx...); }
  37. template<typename... Ix> arr_t& mutate_at_t(arr_t& a, Ix... idx) { a.mutable_at(idx...)++; return a; }
  38. #define def_index_fn(name, type) \
  39. sm.def(#name, [](type a) { return name(a); }); \
  40. sm.def(#name, [](type a, int i) { return name(a, i); }); \
  41. sm.def(#name, [](type a, int i, int j) { return name(a, i, j); }); \
  42. sm.def(#name, [](type a, int i, int j, int k) { return name(a, i, j, k); });
  43. template <typename T, typename T2> py::handle auxiliaries(T &&r, T2 &&r2) {
  44. if (r.ndim() != 2) throw std::domain_error("error: ndim != 2");
  45. py::list l;
  46. l.append(*r.data(0, 0));
  47. l.append(*r2.mutable_data(0, 0));
  48. l.append(r.data(0, 1) == r2.mutable_data(0, 1));
  49. l.append(r.ndim());
  50. l.append(r.itemsize());
  51. l.append(r.shape(0));
  52. l.append(r.shape(1));
  53. l.append(r.size());
  54. l.append(r.nbytes());
  55. return l.release();
  56. }
  57. TEST_SUBMODULE(numpy_array, sm) {
  58. try { py::module::import("numpy"); }
  59. catch (...) { return; }
  60. // test_array_attributes
  61. sm.def("ndim", [](const arr& a) { return a.ndim(); });
  62. sm.def("shape", [](const arr& a) { return arr(a.ndim(), a.shape()); });
  63. sm.def("shape", [](const arr& a, ssize_t dim) { return a.shape(dim); });
  64. sm.def("strides", [](const arr& a) { return arr(a.ndim(), a.strides()); });
  65. sm.def("strides", [](const arr& a, ssize_t dim) { return a.strides(dim); });
  66. sm.def("writeable", [](const arr& a) { return a.writeable(); });
  67. sm.def("size", [](const arr& a) { return a.size(); });
  68. sm.def("itemsize", [](const arr& a) { return a.itemsize(); });
  69. sm.def("nbytes", [](const arr& a) { return a.nbytes(); });
  70. sm.def("owndata", [](const arr& a) { return a.owndata(); });
  71. // test_index_offset
  72. def_index_fn(index_at, const arr&);
  73. def_index_fn(index_at_t, const arr_t&);
  74. def_index_fn(offset_at, const arr&);
  75. def_index_fn(offset_at_t, const arr_t&);
  76. // test_data
  77. def_index_fn(data, const arr&);
  78. def_index_fn(data_t, const arr_t&);
  79. // test_mutate_data, test_mutate_readonly
  80. def_index_fn(mutate_data, arr&);
  81. def_index_fn(mutate_data_t, arr_t&);
  82. def_index_fn(at_t, const arr_t&);
  83. def_index_fn(mutate_at_t, arr_t&);
  84. // test_make_c_f_array
  85. sm.def("make_f_array", [] { return py::array_t<float>({ 2, 2 }, { 4, 8 }); });
  86. sm.def("make_c_array", [] { return py::array_t<float>({ 2, 2 }, { 8, 4 }); });
  87. // test_empty_shaped_array
  88. sm.def("make_empty_shaped_array", [] { return py::array(py::dtype("f"), {}, {}); });
  89. // test_wrap
  90. sm.def("wrap", [](py::array a) {
  91. return py::array(
  92. a.dtype(),
  93. {a.shape(), a.shape() + a.ndim()},
  94. {a.strides(), a.strides() + a.ndim()},
  95. a.data(),
  96. a
  97. );
  98. });
  99. // test_numpy_view
  100. struct ArrayClass {
  101. int data[2] = { 1, 2 };
  102. ArrayClass() { py::print("ArrayClass()"); }
  103. ~ArrayClass() { py::print("~ArrayClass()"); }
  104. };
  105. py::class_<ArrayClass>(sm, "ArrayClass")
  106. .def(py::init<>())
  107. .def("numpy_view", [](py::object &obj) {
  108. py::print("ArrayClass::numpy_view()");
  109. ArrayClass &a = obj.cast<ArrayClass&>();
  110. return py::array_t<int>({2}, {4}, a.data, obj);
  111. }
  112. );
  113. // test_cast_numpy_int64_to_uint64
  114. sm.def("function_taking_uint64", [](uint64_t) { });
  115. // test_isinstance
  116. sm.def("isinstance_untyped", [](py::object yes, py::object no) {
  117. return py::isinstance<py::array>(yes) && !py::isinstance<py::array>(no);
  118. });
  119. sm.def("isinstance_typed", [](py::object o) {
  120. return py::isinstance<py::array_t<double>>(o) && !py::isinstance<py::array_t<int>>(o);
  121. });
  122. // test_constructors
  123. sm.def("default_constructors", []() {
  124. return py::dict(
  125. "array"_a=py::array(),
  126. "array_t<int32>"_a=py::array_t<std::int32_t>(),
  127. "array_t<double>"_a=py::array_t<double>()
  128. );
  129. });
  130. sm.def("converting_constructors", [](py::object o) {
  131. return py::dict(
  132. "array"_a=py::array(o),
  133. "array_t<int32>"_a=py::array_t<std::int32_t>(o),
  134. "array_t<double>"_a=py::array_t<double>(o)
  135. );
  136. });
  137. // test_overload_resolution
  138. sm.def("overloaded", [](py::array_t<double>) { return "double"; });
  139. sm.def("overloaded", [](py::array_t<float>) { return "float"; });
  140. sm.def("overloaded", [](py::array_t<int>) { return "int"; });
  141. sm.def("overloaded", [](py::array_t<unsigned short>) { return "unsigned short"; });
  142. sm.def("overloaded", [](py::array_t<long long>) { return "long long"; });
  143. sm.def("overloaded", [](py::array_t<std::complex<double>>) { return "double complex"; });
  144. sm.def("overloaded", [](py::array_t<std::complex<float>>) { return "float complex"; });
  145. sm.def("overloaded2", [](py::array_t<std::complex<double>>) { return "double complex"; });
  146. sm.def("overloaded2", [](py::array_t<double>) { return "double"; });
  147. sm.def("overloaded2", [](py::array_t<std::complex<float>>) { return "float complex"; });
  148. sm.def("overloaded2", [](py::array_t<float>) { return "float"; });
  149. // Only accept the exact types:
  150. sm.def("overloaded3", [](py::array_t<int>) { return "int"; }, py::arg().noconvert());
  151. sm.def("overloaded3", [](py::array_t<double>) { return "double"; }, py::arg().noconvert());
  152. // Make sure we don't do unsafe coercion (e.g. float to int) when not using forcecast, but
  153. // rather that float gets converted via the safe (conversion to double) overload:
  154. sm.def("overloaded4", [](py::array_t<long long, 0>) { return "long long"; });
  155. sm.def("overloaded4", [](py::array_t<double, 0>) { return "double"; });
  156. // But we do allow conversion to int if forcecast is enabled (but only if no overload matches
  157. // without conversion)
  158. sm.def("overloaded5", [](py::array_t<unsigned int>) { return "unsigned int"; });
  159. sm.def("overloaded5", [](py::array_t<double>) { return "double"; });
  160. // test_greedy_string_overload
  161. // Issue 685: ndarray shouldn't go to std::string overload
  162. sm.def("issue685", [](std::string) { return "string"; });
  163. sm.def("issue685", [](py::array) { return "array"; });
  164. sm.def("issue685", [](py::object) { return "other"; });
  165. // test_array_unchecked_fixed_dims
  166. sm.def("proxy_add2", [](py::array_t<double> a, double v) {
  167. auto r = a.mutable_unchecked<2>();
  168. for (ssize_t i = 0; i < r.shape(0); i++)
  169. for (ssize_t j = 0; j < r.shape(1); j++)
  170. r(i, j) += v;
  171. }, py::arg().noconvert(), py::arg());
  172. sm.def("proxy_init3", [](double start) {
  173. py::array_t<double, py::array::c_style> a({ 3, 3, 3 });
  174. auto r = a.mutable_unchecked<3>();
  175. for (ssize_t i = 0; i < r.shape(0); i++)
  176. for (ssize_t j = 0; j < r.shape(1); j++)
  177. for (ssize_t k = 0; k < r.shape(2); k++)
  178. r(i, j, k) = start++;
  179. return a;
  180. });
  181. sm.def("proxy_init3F", [](double start) {
  182. py::array_t<double, py::array::f_style> a({ 3, 3, 3 });
  183. auto r = a.mutable_unchecked<3>();
  184. for (ssize_t k = 0; k < r.shape(2); k++)
  185. for (ssize_t j = 0; j < r.shape(1); j++)
  186. for (ssize_t i = 0; i < r.shape(0); i++)
  187. r(i, j, k) = start++;
  188. return a;
  189. });
  190. sm.def("proxy_squared_L2_norm", [](py::array_t<double> a) {
  191. auto r = a.unchecked<1>();
  192. double sumsq = 0;
  193. for (ssize_t i = 0; i < r.shape(0); i++)
  194. sumsq += r[i] * r(i); // Either notation works for a 1D array
  195. return sumsq;
  196. });
  197. sm.def("proxy_auxiliaries2", [](py::array_t<double> a) {
  198. auto r = a.unchecked<2>();
  199. auto r2 = a.mutable_unchecked<2>();
  200. return auxiliaries(r, r2);
  201. });
  202. // test_array_unchecked_dyn_dims
  203. // Same as the above, but without a compile-time dimensions specification:
  204. sm.def("proxy_add2_dyn", [](py::array_t<double> a, double v) {
  205. auto r = a.mutable_unchecked();
  206. if (r.ndim() != 2) throw std::domain_error("error: ndim != 2");
  207. for (ssize_t i = 0; i < r.shape(0); i++)
  208. for (ssize_t j = 0; j < r.shape(1); j++)
  209. r(i, j) += v;
  210. }, py::arg().noconvert(), py::arg());
  211. sm.def("proxy_init3_dyn", [](double start) {
  212. py::array_t<double, py::array::c_style> a({ 3, 3, 3 });
  213. auto r = a.mutable_unchecked();
  214. if (r.ndim() != 3) throw std::domain_error("error: ndim != 3");
  215. for (ssize_t i = 0; i < r.shape(0); i++)
  216. for (ssize_t j = 0; j < r.shape(1); j++)
  217. for (ssize_t k = 0; k < r.shape(2); k++)
  218. r(i, j, k) = start++;
  219. return a;
  220. });
  221. sm.def("proxy_auxiliaries2_dyn", [](py::array_t<double> a) {
  222. return auxiliaries(a.unchecked(), a.mutable_unchecked());
  223. });
  224. sm.def("array_auxiliaries2", [](py::array_t<double> a) {
  225. return auxiliaries(a, a);
  226. });
  227. // test_array_failures
  228. // Issue #785: Uninformative "Unknown internal error" exception when constructing array from empty object:
  229. sm.def("array_fail_test", []() { return py::array(py::object()); });
  230. sm.def("array_t_fail_test", []() { return py::array_t<double>(py::object()); });
  231. // Make sure the error from numpy is being passed through:
  232. sm.def("array_fail_test_negative_size", []() { int c = 0; return py::array(-1, &c); });
  233. // test_initializer_list
  234. // Issue (unnumbered; reported in #788): regression: initializer lists can be ambiguous
  235. sm.def("array_initializer_list1", []() { return py::array_t<float>(1); }); // { 1 } also works, but clang warns about it
  236. sm.def("array_initializer_list2", []() { return py::array_t<float>({ 1, 2 }); });
  237. sm.def("array_initializer_list3", []() { return py::array_t<float>({ 1, 2, 3 }); });
  238. sm.def("array_initializer_list4", []() { return py::array_t<float>({ 1, 2, 3, 4 }); });
  239. // test_array_resize
  240. // reshape array to 2D without changing size
  241. sm.def("array_reshape2", [](py::array_t<double> a) {
  242. const ssize_t dim_sz = (ssize_t)std::sqrt(a.size());
  243. if (dim_sz * dim_sz != a.size())
  244. throw std::domain_error("array_reshape2: input array total size is not a squared integer");
  245. a.resize({dim_sz, dim_sz});
  246. });
  247. // resize to 3D array with each dimension = N
  248. sm.def("array_resize3", [](py::array_t<double> a, size_t N, bool refcheck) {
  249. a.resize({N, N, N}, refcheck);
  250. });
  251. // test_array_create_and_resize
  252. // return 2D array with Nrows = Ncols = N
  253. sm.def("create_and_resize", [](size_t N) {
  254. py::array_t<double> a;
  255. a.resize({N, N});
  256. std::fill(a.mutable_data(), a.mutable_data() + a.size(), 42.);
  257. return a;
  258. });
  259. }