Sending a C++ array to Python and back (Extending C++ with Numpy)

前端 未结 4 1346
刺人心
刺人心 2020-12-04 10:38

I am going to send a c++ array to a python function as numpy array and get back another numpy array. After consulting with numpy

4条回答
  •  心在旅途
    2020-12-04 11:05

    Try out xtensor and the xtensor-python python bindings.

    xtensor is a C++ library meant for numerical analysis with multi-dimensional array expressions.

    xtensor provides

    • an extensible expression system enabling numpy-style broadcasting (see the numpy to xtensor cheat sheet).
    • an API following the idioms of the C++ standard library.
    • tools to manipulate array expressions and build upon xtensor.
    • bindings for Python, but also R and Julia.

    Example of usage

    Initialize a 2-D array and compute the sum of one of its rows and a 1-D array.

    #include 
    #include "xtensor/xarray.hpp"
    #include "xtensor/xio.hpp"
    
    xt::xarray arr1
      {{1.0, 2.0, 3.0},
       {2.0, 5.0, 7.0},
       {2.0, 5.0, 7.0}};
    
    xt::xarray arr2
      {5.0, 6.0, 7.0};
    
    xt::xarray res = xt::view(arr1, 1) + arr2;
    
    std::cout << res;
    

    Outputs

    {7, 11, 14}
    

    Creating a Numpy-style universal function in C++.

    #include "pybind11/pybind11.h"
    #include "xtensor-python/pyvectorize.hpp"
    #include 
    #include 
    
    namespace py = pybind11;
    
    double scalar_func(double i, double j)
    {
        return std::sin(i) - std::cos(j);
    }
    
    PYBIND11_PLUGIN(xtensor_python_test)
    {
        py::module m("xtensor_python_test", "Test module for xtensor python bindings");
    
        m.def("vectorized_func", xt::pyvectorize(scalar_func), "");
    
        return m.ptr();
    }
    

    Python code:

    import numpy as np
    import xtensor_python_test as xt
    
    x = np.arange(15).reshape(3, 5)
    y = [1, 2, 3, 4, 5]
    z = xt.vectorized_func(x, y)
    z
    

    Outputs

    [[-0.540302,  1.257618,  1.89929 ,  0.794764, -1.040465],
     [-1.499227,  0.136731,  1.646979,  1.643002,  0.128456],
     [-1.084323, -0.583843,  0.45342 ,  1.073811,  0.706945]]
    

提交回复
热议问题