wrap.cpp 5.2 KB

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