Go to the documentation of this file.00001
00002
00003
00004
00005
00026 #include <boost/numpy.hpp>
00027 #include <boost/scoped_array.hpp>
00028 #include <iostream>
00029
00030 namespace p = boost::python;
00031 namespace np = boost::numpy;
00032
00033
00034
00035
00036 void fill1(double * array, int rows, int cols, int row_stride, int col_stride) {
00037 double * row_iter = array;
00038 double n = 0.0;
00039 for (int i = 0; i < rows; ++i, row_iter += row_stride) {
00040 double * col_iter = row_iter;
00041 for (int j = 0; j < cols; ++j, col_iter += col_stride) {
00042 *col_iter = ++n;
00043 }
00044 }
00045 }
00046
00047
00048
00049
00050
00051 void wrap_fill1(np::ndarray const & array) {
00052 if (array.get_dtype() != np::dtype::get_builtin<double>()) {
00053 PyErr_SetString(PyExc_TypeError, "Incorrect array data type");
00054 p::throw_error_already_set();
00055 }
00056 if (array.get_nd() != 2) {
00057 PyErr_SetString(PyExc_TypeError, "Incorrect number of dimensions");
00058 p::throw_error_already_set();
00059 }
00060 fill1(reinterpret_cast<double*>(array.get_data()),
00061 array.shape(0), array.shape(1),
00062 array.strides(0) / sizeof(double), array.strides(1) / sizeof(double));
00063 }
00064
00065
00066
00067
00068
00069
00070
00071
00072 void fill2(double ** array, int rows, int cols) {
00073 double n = 0.0;
00074 for (int i = 0; i < rows; ++i) {
00075 for (int j = 0; j < cols; ++j) {
00076 array[i][j] = ++n;
00077 }
00078 }
00079 }
00080
00081
00082 void wrap_fill2(np::ndarray const & array) {
00083 if (array.get_dtype() != np::dtype::get_builtin<double>()) {
00084 PyErr_SetString(PyExc_TypeError, "Incorrect array data type");
00085 p::throw_error_already_set();
00086 }
00087 if (array.get_nd() != 2) {
00088 PyErr_SetString(PyExc_TypeError, "Incorrect number of dimensions");
00089 p::throw_error_already_set();
00090 }
00091 if (!(array.get_flags() & np::ndarray::C_CONTIGUOUS)) {
00092 PyErr_SetString(PyExc_TypeError, "Array must be row-major contiguous");
00093 p::throw_error_already_set();
00094 }
00095 double * iter = reinterpret_cast<double*>(array.get_data());
00096 int rows = array.shape(0);
00097 int cols = array.shape(1);
00098 boost::scoped_array<double*> ptrs(new double*[rows]);
00099 for (int i = 0; i < rows; ++i, iter += cols) {
00100 ptrs[i] = iter;
00101 }
00102 fill2(ptrs.get(), array.shape(0), array.shape(1));
00103 }
00104
00105 BOOST_PYTHON_MODULE(example) {
00106 np::initialize();
00107 p::def("fill1", wrap_fill1);
00108 p::def("fill2", wrap_fill2);
00109 }
00110
00111 int main(int argc, char **argv)
00112 {
00113
00114 PyImport_AppendInittab("example", &initexample);
00115
00116
00117 Py_Initialize();
00118
00119 PyRun_SimpleString(
00120 "import example\n"
00121 "import numpy\n"
00122 "z1 = numpy.zeros((5,6), dtype=float)\n"
00123 "z2 = numpy.zeros((4,3), dtype=float)\n"
00124 "example.fill1(z1)\n"
00125 "example.fill2(z2)\n"
00126 "print z1\n"
00127 "print z2\n"
00128 );
00129 Py_Finalize();
00130 }
00131
00132