You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

379 lines
14 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. .. _numpy:
  2. NumPy
  3. #####
  4. Buffer protocol
  5. ===============
  6. Python supports an extremely general and convenient approach for exchanging
  7. data between plugin libraries. Types can expose a buffer view [#f2]_, which
  8. provides fast direct access to the raw internal data representation. Suppose we
  9. want to bind the following simplistic Matrix class:
  10. .. code-block:: cpp
  11. class Matrix {
  12. public:
  13. Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) {
  14. m_data = new float[rows*cols];
  15. }
  16. float *data() { return m_data; }
  17. size_t rows() const { return m_rows; }
  18. size_t cols() const { return m_cols; }
  19. private:
  20. size_t m_rows, m_cols;
  21. float *m_data;
  22. };
  23. The following binding code exposes the ``Matrix`` contents as a buffer object,
  24. making it possible to cast Matrices into NumPy arrays. It is even possible to
  25. completely avoid copy operations with Python expressions like
  26. ``np.array(matrix_instance, copy = False)``.
  27. .. code-block:: cpp
  28. py::class_<Matrix>(m, "Matrix", py::buffer_protocol())
  29. .def_buffer([](Matrix &m) -> py::buffer_info {
  30. return py::buffer_info(
  31. m.data(), /* Pointer to buffer */
  32. sizeof(float), /* Size of one scalar */
  33. py::format_descriptor<float>::format(), /* Python struct-style format descriptor */
  34. 2, /* Number of dimensions */
  35. { m.rows(), m.cols() }, /* Buffer dimensions */
  36. { sizeof(float) * m.rows(), /* Strides (in bytes) for each index */
  37. sizeof(float) }
  38. );
  39. });
  40. Supporting the buffer protocol in a new type involves specifying the special
  41. ``py::buffer_protocol()`` tag in the ``py::class_`` constructor and calling the
  42. ``def_buffer()`` method with a lambda function that creates a
  43. ``py::buffer_info`` description record on demand describing a given matrix
  44. instance. The contents of ``py::buffer_info`` mirror the Python buffer protocol
  45. specification.
  46. .. code-block:: cpp
  47. struct buffer_info {
  48. void *ptr;
  49. size_t itemsize;
  50. std::string format;
  51. int ndim;
  52. std::vector<size_t> shape;
  53. std::vector<size_t> strides;
  54. };
  55. To create a C++ function that can take a Python buffer object as an argument,
  56. simply use the type ``py::buffer`` as one of its arguments. Buffers can exist
  57. in a great variety of configurations, hence some safety checks are usually
  58. necessary in the function body. Below, you can see an basic example on how to
  59. define a custom constructor for the Eigen double precision matrix
  60. (``Eigen::MatrixXd``) type, which supports initialization from compatible
  61. buffer objects (e.g. a NumPy matrix).
  62. .. code-block:: cpp
  63. /* Bind MatrixXd (or some other Eigen type) to Python */
  64. typedef Eigen::MatrixXd Matrix;
  65. typedef Matrix::Scalar Scalar;
  66. constexpr bool rowMajor = Matrix::Flags & Eigen::RowMajorBit;
  67. py::class_<Matrix>(m, "Matrix", py::buffer_protocol())
  68. .def("__init__", [](Matrix &m, py::buffer b) {
  69. typedef Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic> Strides;
  70. /* Request a buffer descriptor from Python */
  71. py::buffer_info info = b.request();
  72. /* Some sanity checks ... */
  73. if (info.format != py::format_descriptor<Scalar>::format())
  74. throw std::runtime_error("Incompatible format: expected a double array!");
  75. if (info.ndim != 2)
  76. throw std::runtime_error("Incompatible buffer dimension!");
  77. auto strides = Strides(
  78. info.strides[rowMajor ? 0 : 1] / sizeof(Scalar),
  79. info.strides[rowMajor ? 1 : 0] / sizeof(Scalar));
  80. auto map = Eigen::Map<Matrix, 0, Strides>(
  81. static_cat<Scalar *>(info.ptr), info.shape[0], info.shape[1], strides);
  82. new (&m) Matrix(map);
  83. });
  84. For reference, the ``def_buffer()`` call for this Eigen data type should look
  85. as follows:
  86. .. code-block:: cpp
  87. .def_buffer([](Matrix &m) -> py::buffer_info {
  88. return py::buffer_info(
  89. m.data(), /* Pointer to buffer */
  90. sizeof(Scalar), /* Size of one scalar */
  91. /* Python struct-style format descriptor */
  92. py::format_descriptor<Scalar>::format(),
  93. /* Number of dimensions */
  94. 2,
  95. /* Buffer dimensions */
  96. { (size_t) m.rows(),
  97. (size_t) m.cols() },
  98. /* Strides (in bytes) for each index */
  99. { sizeof(Scalar) * (rowMajor ? m.cols() : 1),
  100. sizeof(Scalar) * (rowMajor ? 1 : m.rows()) }
  101. );
  102. })
  103. For a much easier approach of binding Eigen types (although with some
  104. limitations), refer to the section on :doc:`/advanced/cast/eigen`.
  105. .. seealso::
  106. The file :file:`tests/test_buffers.cpp` contains a complete example
  107. that demonstrates using the buffer protocol with pybind11 in more detail.
  108. .. [#f2] http://docs.python.org/3/c-api/buffer.html
  109. Arrays
  110. ======
  111. By exchanging ``py::buffer`` with ``py::array`` in the above snippet, we can
  112. restrict the function so that it only accepts NumPy arrays (rather than any
  113. type of Python object satisfying the buffer protocol).
  114. In many situations, we want to define a function which only accepts a NumPy
  115. array of a certain data type. This is possible via the ``py::array_t<T>``
  116. template. For instance, the following function requires the argument to be a
  117. NumPy array containing double precision values.
  118. .. code-block:: cpp
  119. void f(py::array_t<double> array);
  120. When it is invoked with a different type (e.g. an integer or a list of
  121. integers), the binding code will attempt to cast the input into a NumPy array
  122. of the requested type. Note that this feature requires the
  123. :file:`pybind11/numpy.h` header to be included.
  124. Data in NumPy arrays is not guaranteed to packed in a dense manner;
  125. furthermore, entries can be separated by arbitrary column and row strides.
  126. Sometimes, it can be useful to require a function to only accept dense arrays
  127. using either the C (row-major) or Fortran (column-major) ordering. This can be
  128. accomplished via a second template argument with values ``py::array::c_style``
  129. or ``py::array::f_style``.
  130. .. code-block:: cpp
  131. void f(py::array_t<double, py::array::c_style | py::array::forcecast> array);
  132. The ``py::array::forcecast`` argument is the default value of the second
  133. template parameter, and it ensures that non-conforming arguments are converted
  134. into an array satisfying the specified requirements instead of trying the next
  135. function overload.
  136. Structured types
  137. ================
  138. In order for ``py::array_t`` to work with structured (record) types, we first
  139. need to register the memory layout of the type. This can be done via
  140. ``PYBIND11_NUMPY_DTYPE`` macro, called in the plugin definition code, which
  141. expects the type followed by field names:
  142. .. code-block:: cpp
  143. struct A {
  144. int x;
  145. double y;
  146. };
  147. struct B {
  148. int z;
  149. A a;
  150. };
  151. // ...
  152. PYBIND11_PLUGIN(test) {
  153. // ...
  154. PYBIND11_NUMPY_DTYPE(A, x, y);
  155. PYBIND11_NUMPY_DTYPE(B, z, a);
  156. /* now both A and B can be used as template arguments to py::array_t */
  157. }
  158. Vectorizing functions
  159. =====================
  160. Suppose we want to bind a function with the following signature to Python so
  161. that it can process arbitrary NumPy array arguments (vectors, matrices, general
  162. N-D arrays) in addition to its normal arguments:
  163. .. code-block:: cpp
  164. double my_func(int x, float y, double z);
  165. After including the ``pybind11/numpy.h`` header, this is extremely simple:
  166. .. code-block:: cpp
  167. m.def("vectorized_func", py::vectorize(my_func));
  168. Invoking the function like below causes 4 calls to be made to ``my_func`` with
  169. each of the array elements. The significant advantage of this compared to
  170. solutions like ``numpy.vectorize()`` is that the loop over the elements runs
  171. entirely on the C++ side and can be crunched down into a tight, optimized loop
  172. by the compiler. The result is returned as a NumPy array of type
  173. ``numpy.dtype.float64``.
  174. .. code-block:: pycon
  175. >>> x = np.array([[1, 3],[5, 7]])
  176. >>> y = np.array([[2, 4],[6, 8]])
  177. >>> z = 3
  178. >>> result = vectorized_func(x, y, z)
  179. The scalar argument ``z`` is transparently replicated 4 times. The input
  180. arrays ``x`` and ``y`` are automatically converted into the right types (they
  181. are of type ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and
  182. ``numpy.dtype.float32``, respectively)
  183. Sometimes we might want to explicitly exclude an argument from the vectorization
  184. because it makes little sense to wrap it in a NumPy array. For instance,
  185. suppose the function signature was
  186. .. code-block:: cpp
  187. double my_func(int x, float y, my_custom_type *z);
  188. This can be done with a stateful Lambda closure:
  189. .. code-block:: cpp
  190. // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization)
  191. m.def("vectorized_func",
  192. [](py::array_t<int> x, py::array_t<float> y, my_custom_type *z) {
  193. auto stateful_closure = [z](int x, float y) { return my_func(x, y, z); };
  194. return py::vectorize(stateful_closure)(x, y);
  195. }
  196. );
  197. In cases where the computation is too complicated to be reduced to
  198. ``vectorize``, it will be necessary to create and access the buffer contents
  199. manually. The following snippet contains a complete example that shows how this
  200. works (the code is somewhat contrived, since it could have been done more
  201. simply using ``vectorize``).
  202. .. code-block:: cpp
  203. #include <pybind11/pybind11.h>
  204. #include <pybind11/numpy.h>
  205. namespace py = pybind11;
  206. py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) {
  207. auto buf1 = input1.request(), buf2 = input2.request();
  208. if (buf1.ndim != 1 || buf2.ndim != 1)
  209. throw std::runtime_error("Number of dimensions must be one");
  210. if (buf1.size != buf2.size)
  211. throw std::runtime_error("Input shapes must match");
  212. /* No pointer is passed, so NumPy will allocate the buffer */
  213. auto result = py::array_t<double>(buf1.size);
  214. auto buf3 = result.request();
  215. double *ptr1 = (double *) buf1.ptr,
  216. *ptr2 = (double *) buf2.ptr,
  217. *ptr3 = (double *) buf3.ptr;
  218. for (size_t idx = 0; idx < buf1.shape[0]; idx++)
  219. ptr3[idx] = ptr1[idx] + ptr2[idx];
  220. return result;
  221. }
  222. PYBIND11_PLUGIN(test) {
  223. py::module m("test");
  224. m.def("add_arrays", &add_arrays, "Add two NumPy arrays");
  225. return m.ptr();
  226. }
  227. .. seealso::
  228. The file :file:`tests/test_numpy_vectorize.cpp` contains a complete
  229. example that demonstrates using :func:`vectorize` in more detail.
  230. Direct access
  231. =============
  232. For performance reasons, particularly when dealing with very large arrays, it
  233. is often desirable to directly access array elements without internal checking
  234. of dimensions and bounds on every access when indices are known to be already
  235. valid. To avoid such checks, the ``array`` class and ``array_t<T>`` template
  236. class offer an unchecked proxy object that can be used for this unchecked
  237. access through the ``unchecked<N>`` and ``mutable_unchecked<N>`` methods,
  238. where ``N`` gives the required dimensionality of the array:
  239. .. code-block:: cpp
  240. m.def("sum_3d", [](py::array_t<double> x) {
  241. auto r = x.unchecked<3>(); // x must have ndim = 3; can be non-writeable
  242. double sum = 0;
  243. for (size_t i = 0; i < r.shape(0); i++)
  244. for (size_t j = 0; j < r.shape(1); j++)
  245. for (size_t k = 0; k < r.shape(2); k++)
  246. sum += r(i, j, k);
  247. return sum;
  248. });
  249. m.def("increment_3d", [](py::array_t<double> x) {
  250. auto r = x.mutable_unchecked<3>(); // Will throw if ndim != 3 or flags.writeable is false
  251. for (size_t i = 0; i < r.shape(0); i++)
  252. for (size_t j = 0; j < r.shape(1); j++)
  253. for (size_t k = 0; k < r.shape(2); k++)
  254. r(i, j, k) += 1.0;
  255. }, py::arg().noconvert());
  256. To obtain the proxy from an ``array`` object, you must specify both the data
  257. type and number of dimensions as template arguments, such as ``auto r =
  258. myarray.mutable_unchecked<float, 2>()``.
  259. If the number of dimensions is not known at compile time, you can omit the
  260. dimensions template parameter (i.e. calling ``arr_t.unchecked()`` or
  261. ``arr.unchecked<T>()``. This will give you a proxy object that works in the
  262. same way, but results in less optimizable code and thus a small efficiency
  263. loss in tight loops.
  264. Note that the returned proxy object directly references the array's data, and
  265. only reads its shape, strides, and writeable flag when constructed. You must
  266. take care to ensure that the referenced array is not destroyed or reshaped for
  267. the duration of the returned object, typically by limiting the scope of the
  268. returned instance.
  269. The returned proxy object supports some of the same methods as ``py::array`` so
  270. that it can be used as a drop-in replacement for some existing, index-checked
  271. uses of ``py::array``:
  272. - ``r.ndim()`` returns the number of dimensions
  273. - ``r.data(1, 2, ...)`` and ``r.mutable_data(1, 2, ...)``` returns a pointer to
  274. the ``const T`` or ``T`` data, respectively, at the given indices. The
  275. latter is only available to proxies obtained via ``a.mutable_unchecked()``.
  276. - ``itemsize()`` returns the size of an item in bytes, i.e. ``sizeof(T)``.
  277. - ``ndim()`` returns the number of dimensions.
  278. - ``shape(n)`` returns the size of dimension ``n``
  279. - ``size()`` returns the total number of elements (i.e. the product of the shapes).
  280. - ``nbytes()`` returns the number of bytes used by the referenced elements
  281. (i.e. ``itemsize()`` times ``size()``).
  282. .. seealso::
  283. The file :file:`tests/test_numpy_array.cpp` contains additional examples
  284. demonstrating the use of this feature.