Make the library created by Eigen in C ++ available from Python with Boost.Numpy.

This article

Make a note of what you did at the Sapporo C ++ Study Group Online Mokumokukai # 36.

Installation method

Please hit another place. Do your best.

things to do

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.

C ++ source code

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.

How to compile

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"])

Python code

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.

Postscript

https://github.com/ignisan/boost_numpy_project/blob/master/to_eigen_map.hpp

Recommended Posts

Make the library created by Eigen in C ++ available from Python with Boost.Numpy.
Make OpenCV3 available from python3 installed with pyenv
Make a breakpoint on the c layer with python
Extend python in C ++ (Boost.NumPy)
Make MeCab available from Python3
Make Opencv available in Python
I tried using the Python library from Ruby with PyCall
Pass OpenCV data from the original C ++ library to Python
Call C from Python with DragonFFI
Make the morphological analysis engine MeCab available in Python 3 (March 2016 version)
Read a file in Python with a relative path from the program
Pass a list by reference from Python to C ++ with pybind11
python> link> from __future__ import print_function> Make Python 3.X print () available in Python 2.X
Fill the string with zeros in python and count some characters from the string
A memo organized by renaming the file names in the folder with python
Display Python 3 in the browser with MAMP
What is "mahjong" in the Python library? ??
Read the file line by line in Python
Read the file line by line in Python
Generate C language from S-expressions in Python
Use C ++ functions from python with pybind11
[Implementation example] Read the file line by line with Cython (Python) from the last line
[Python] Created a class to play sin waves in the background with pyaudio
Location information data display in Python --Try plotting with the map display library (folium)-
[Python] Get the files in a folder with Python
Load the network modeled with Rhinoceros in Python ③
The first web app created by Python beginners
[Automation] Extract the table in PDF with Python
Make a copy of the list in Python
Wrap C with Cython for use from Python
Boost.NumPy Tutorial for Extending Python in C ++ (Practice)
Manage AWS nicely with the Python library Boto
Load the network modeled with Rhinoceros in Python ②
Call a Python script from Embedded Python in C ++ / C ++
Wrap C ++ with Cython for use from Python
I want to make C ++ code from Python code!
Read line by line from a file with Python
Make JSON into CSV with Python from Splunk
Use the LibreOffice app in Python (3) Add library
[Modint] Decoding the AtCoder Library ~ Implementation in Python ~
Load the network modeled with Rhinoceros in Python ①
Registering with PyPI from modern Python library self-made
Get the value of a specific key in a list from the dictionary type in the list with Python
"Cython" tutorial to make Python explosive: When C ++ code depends on the library. Preparation
Let's make a leap in the manufacturing industry by utilizing the Web in addition to Python
Make Fatjar by changing the main class with Gradle
Learn Nim with Python (from the beginning of the year).
Complement the library you put in anaconda with jedi-vim
Explain in detail how to make sounds with python
[Python] Get the numbers in the graph image with OCR
[Python] Specify the range from the image by dragging the mouse
Let's call your own C ++ library with Python (Preferences)
Output the time from the time the program was started in python
I asked the problem of the tribonacci sequence in C ++ & the number of function calls when writing with the recurrence function (python is also available)
Make a simple Slackbot with interactive button in python
Try embedding Python in a C ++ program with pybind11
Python points from the perspective of a C programmer
Crawl the URL contained in the twitter tweet with python
Convert the image in .zip to PDF with Python
I wanted to use the Python library from MATLAB
Get the result in dict format with Python psycopg2