Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move to PyBind11 #9

Open
henryiii opened this issue Nov 17, 2017 · 1 comment
Open

Move to PyBind11 #9

henryiii opened this issue Nov 17, 2017 · 1 comment

Comments

@henryiii
Copy link
Contributor

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
Copy link
Collaborator

DavidLP commented Nov 30, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants