SiLab-Bonn / pylandau

Simple Landau distribution definitions to be used in Python.
GNU Lesser General Public License v2.1
20 stars 5 forks source link

Move to PyBind11 #9

Open henryiii opened 7 years ago

henryiii commented 7 years ago

You could simplify the code significantly if you moved to using pybind11. This would remove the need to import the numpy headers in setup.py completely. The binding code would be:

At the top of the file

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

namespace py = pybind11;
using namespace pybind11::literals;

And, after the C++ code is imported, or at the bottom of the file, in a file named landau.cpp:

PYBIND11_MODULE(landau, m) {
    m.def("landauPDF", py::vectorize(landauPDF),
            "x"_a, "x0"_a=0., "xi"_a=1.);

    m.def("gaussPDF", py::vectorize(gaussPDF),
            "x"_a, "mu"_a=0., "sigma"_a=1.);

    m.def("landauGaussPDF", py::vectorize(landauGaussPDF),
            "x"_a, "mu"_a=0., "eta"_a=1., "sigma"_a=1.);
}

This does automatic vectorization, as well, so x can be a vector or a single value. Here's a file example: https://gist.github.com/henryiii/9419a0b803664d8ff2a159c1fcfd644e

Compile by hand if you want:

c++ -O3 -Wall -shared -std=c++11 -fPIC `python -m pybind11 --includes` landau.cpp -o landau`python-config --extension-suffix`

To update pylandau, you'd need a little wrapper to add your new functions in python (probably, c++ is easy too as you can see), and a setup.py.

PS: The other option would be to move to using Cython's buffer interface, but I think the above method is simpler.

DavidLP commented 6 years ago

Thank you very much for your suggestion and nice write up. I was not aware of pybind.