Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return numpy.array from boost::python?

I would like to return some data from c++ code as a numpy.array object. I had a look at boost::python::numeric, but its documentation is very terse. Can I get an example of e.g. returning a (not very large) vector<double> to python? I don't mind doing copies of data.

like image 829
eudoxos Avatar asked May 22 '12 11:05

eudoxos


People also ask

How do I export an array in NumPy?

You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format.

How do I reverse a NumPy vector?

The numpy. flipr() function always accepts a given array as a parameter and returns the same array and flip in the left-right direction. It reverses the order of elements on the given axis as 1 (left/right).

What does NumPy array return?

NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.

What is boost NumPy?

The Boost. Numpy library exposes quite a few methods to create ndarrays. ndarrays can be created in a variety of ways, include empty arrays and zero filled arrays. ndarrays can also be created from arbitrary python sequences as well as from data and dtypes.


1 Answers

UPDATE: the library described in my original answer (https://github.com/ndarray/Boost.NumPy) has been integrated directly into Boost.Python as of Boost 1.63, and hence the standalone version is now deprecated. The text below now corresponds to the new, integrated version (only the namespace has changed).

Boost.Python now includes a moderately complete wrapper of the NumPy C-API into a Boost.Python interface. It's pretty low-level, and mostly focused on how to address the more difficult problem of how to pass C++ data to and from NumPy without copying, but here's how you'd do a copied std::vector return with that:

#include "boost/python/numpy.hpp"  namespace bp = boost::python; namespace bn = boost::python::numpy;  std::vector<double> myfunc(...);  bn::ndarray mywrapper(...) {     std::vector<double> v = myfunc(...);     Py_intptr_t shape[1] = { v.size() };     bn::ndarray result = bn::zeros(1, shape, bn::dtype::get_builtin<double>());     std::copy(v.begin(), v.end(), reinterpret_cast<double*>(result.get_data()));     return result; }  BOOST_PYTHON_MODULE(example) {     bn::initialize();     bp::def("myfunc", mywrapper); } 
like image 107
jbosch Avatar answered Sep 21 '22 03:09

jbosch