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
xtensor is a C++ library meant for numerical analysis with multi-dimensional array expressions.
xtensor provides
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}
#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]]