Make a note of what you did at the Sapporo C ++ Study Group Online Mokumokukai # 36.
Please hit another place. Do your best.
As a simple example, the sum of two-dimensional arrays prepared by Python numpy It calculates using the C ++ Eigen library and returns it to Python again.
cpplib.cpp
#define EIGEN_DEFAULT_TO_ROW_MAJOR
#include<Eigen/Core>
#include<boost/numpy.hpp>
namespace py = boost::python;
namespace np = boost::numpy;
np::ndarray add_double(const np::ndarray lhs, const np::ndarray rhs) {
using Stride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
const auto
lrows = lhs.shape(0),
lcols = lhs.shape(1),
rrows = rhs.shape(0),
rcols = rhs.shape(1);
const Stride
lstride(lhs.strides(0)/sizeof(double), lhs.strides(1)/sizeof(double)),
rstride(rhs.strides(0)/sizeof(double), rhs.strides(1)/sizeof(double));
const Eigen::Map<const Eigen::MatrixXd, Eigen::Unaligned, Stride>
lmat(reinterpret_cast<double*>(lhs.get_data()), lrows, lcols, lstride),
rmat(reinterpret_cast<double*>(rhs.get_data()), rrows, rcols, rstride);
np::ndarray ret = np::empty(
py::make_tuple(lmat.rows(),lmat.cols()),
np::dtype::get_builtin<double>());
Eigen::Map<Eigen::MatrixXd>
ret_mat(reinterpret_cast<double*>(ret.get_data()), lmat.rows(), lmat.cols());
ret_mat = lmat + rmat;
return ret;
}
BOOST_PYTHON_MODULE(cpplib) {
Py_Initialize();
np::initialize();
py::def("add_double",add_double);
}
It may be easier to write if you just want to add matrices, but I've written it so that it can be applied. It is unavoidable that the type is limited to double
. The only way to do it is to check dtype
and branch, but there is no choice but to judge at runtime.
I will do it with SCons. For example, like this. I'm doing it in a mingw environment.
SConstruct
# vim: filetype=python
# SConstruct
env = Environment(
SHLIBPREFIX="",
SHLIBSUFFIX=".pyd",
CXX="/mingw64/bin/g++",
CXXFLAGS=["-std=c++14"],
LINKFLAGS=["-std=c++14"],
CPPPATH=[
"/mingw64/include/eigen3",
"/mingw64/include/python3.5m", ],
LIBPATH=["/mingw64/lib"])
env.SharedLibrary("cpplib", ["cpplib.cpp"],
LIBS=["boost_numpy", "python3.5.dll", "boost_python3-mt"])
usecpp.py
import numpy as np
from cpplib import add_double
a = np.array(
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 1, 2, 3],
[4, 5, 6, 7], ], dtype=np.float64)
b = np.array(
[[5, 6],
[4, 5], ], dtype=np.float64)
result = add_double(a[1::2, 1::2], b[::1, ::1])
print(result)
Result is
Since [[6,8], [5,7]]
and [[5,6], [4,5]]
are added
$ python3 usecpp.py
[[ 11. 14.]
[ 9. 12.]]
It will be. The cloudy meeting time has expired here as well.
https://github.com/ignisan/boost_numpy_project/blob/master/to_eigen_map.hpp
Recommended Posts