1 // Copyright Jim Bosch 2011-2012.
2 // Distributed under the Boost Software License, Version 1.0.
3 // (See accompanying file LICENSE_1_0.txt or copy at
4 // http://www.boost.org/LICENSE_1_0.txt)
5
6 /**
7 * A simple example showing how to wrap a couple of C++ functions that
8 * operate on 2-d arrays into Python functions that take NumPy arrays
9 * as arguments.
10 *
11 * If you find have a lot of such functions to wrap, you may want to
12 * create a C++ array type (or use one of the many existing C++ array
13 * libraries) that maps well to NumPy arrays and create Boost.Python
14 * converters. There's more work up front than the approach here,
15 * but much less boilerplate per function. See the "Gaussian" example
16 * included with Boost.NumPy for an example of custom converters, or
17 * take a look at the "ndarray" project on GitHub for a more complete,
18 * high-level solution.
19 *
20 * Note that we're using embedded Python here only to make a convenient
21 * self-contained example; you could just as easily put the wrappers
22 * in a regular C++-compiled module and imported them in regular
23 * Python. Again, see the Gaussian demo for an example.
24 */
25
26 #include <boost/python/numpy.hpp>
27 #include <boost/scoped_array.hpp>
28 #include <iostream>
29
30 namespace p = boost::python;
31 namespace np = boost::python::numpy;
32
33 // This is roughly the most efficient way to write a C/C++ function that operates
34 // on a 2-d NumPy array - operate directly on the array by incrementing a pointer
35 // with the strides.
fill1(double * array,int rows,int cols,int row_stride,int col_stride)36 void fill1(double * array, int rows, int cols, int row_stride, int col_stride) {
37 double * row_iter = array;
38 double n = 0.0; // just a counter we'll fill the array with.
39 for (int i = 0; i < rows; ++i, row_iter += row_stride) {
40 double * col_iter = row_iter;
41 for (int j = 0; j < cols; ++j, col_iter += col_stride) {
42 *col_iter = ++n;
43 }
44 }
45 }
46
47 // Here's a simple wrapper function for fill1. It requires that the passed
48 // NumPy array be exactly what we're looking for - no conversion from nested
49 // sequences or arrays with other data types, because we want to modify it
50 // in-place.
wrap_fill1(np::ndarray const & array)51 void wrap_fill1(np::ndarray const & array) {
52 if (array.get_dtype() != np::dtype::get_builtin<double>()) {
53 PyErr_SetString(PyExc_TypeError, "Incorrect array data type");
54 p::throw_error_already_set();
55 }
56 if (array.get_nd() != 2) {
57 PyErr_SetString(PyExc_TypeError, "Incorrect number of dimensions");
58 p::throw_error_already_set();
59 }
60 fill1(reinterpret_cast<double*>(array.get_data()),
61 array.shape(0), array.shape(1),
62 array.strides(0) / sizeof(double), array.strides(1) / sizeof(double));
63 }
64
65 // Another fill function that takes a double**. This is less efficient, because
66 // it's not the native NumPy data layout, but it's common enough in C/C++ that
67 // it's worth its own example. This time we don't pass the strides, and instead
68 // in wrap_fill2 we'll require the C_CONTIGUOUS bitflag, which guarantees that
69 // the column stride is 1 and the row stride is the number of columns. That
70 // restricts the arrays that can be passed to fill2 (it won't work on most
71 // subarray views or transposes, for instance).
fill2(double ** array,int rows,int cols)72 void fill2(double ** array, int rows, int cols) {
73 double n = 0.0; // just a counter we'll fill the array with.
74 for (int i = 0; i < rows; ++i) {
75 for (int j = 0; j < cols; ++j) {
76 array[i][j] = ++n;
77 }
78 }
79 }
80 // Here's the wrapper for fill2; it's a little more complicated because we need
81 // to check the flags and create the array of pointers.
wrap_fill2(np::ndarray const & array)82 void wrap_fill2(np::ndarray const & array) {
83 if (array.get_dtype() != np::dtype::get_builtin<double>()) {
84 PyErr_SetString(PyExc_TypeError, "Incorrect array data type");
85 p::throw_error_already_set();
86 }
87 if (array.get_nd() != 2) {
88 PyErr_SetString(PyExc_TypeError, "Incorrect number of dimensions");
89 p::throw_error_already_set();
90 }
91 if (!(array.get_flags() & np::ndarray::C_CONTIGUOUS)) {
92 PyErr_SetString(PyExc_TypeError, "Array must be row-major contiguous");
93 p::throw_error_already_set();
94 }
95 double * iter = reinterpret_cast<double*>(array.get_data());
96 int rows = array.shape(0);
97 int cols = array.shape(1);
98 boost::scoped_array<double*> ptrs(new double*[rows]);
99 for (int i = 0; i < rows; ++i, iter += cols) {
100 ptrs[i] = iter;
101 }
102 fill2(ptrs.get(), array.shape(0), array.shape(1));
103 }
104
BOOST_PYTHON_MODULE(example)105 BOOST_PYTHON_MODULE(example) {
106 np::initialize(); // have to put this in any module that uses Boost.NumPy
107 p::def("fill1", wrap_fill1);
108 p::def("fill2", wrap_fill2);
109 }
110
main(int argc,char ** argv)111 int main(int argc, char **argv)
112 {
113 // This line makes our module available to the embedded Python intepreter.
114 # if PY_VERSION_HEX >= 0x03000000
115 PyImport_AppendInittab("example", &PyInit_example);
116 # else
117 PyImport_AppendInittab("example", &initexample);
118 # endif
119 // Initialize the Python runtime.
120 Py_Initialize();
121
122 PyRun_SimpleString(
123 "import example\n"
124 "import numpy\n"
125 "z1 = numpy.zeros((5,6), dtype=float)\n"
126 "z2 = numpy.zeros((4,3), dtype=float)\n"
127 "example.fill1(z1)\n"
128 "example.fill2(z2)\n"
129 "print z1\n"
130 "print z2\n"
131 );
132 Py_Finalize();
133 }
134
135
136