Stan math library and interfacing with python

Has anyone tried wrapping C++ code, using the stan-math library, for use in Python? I’d appreciate any help or advice.

I’ve been relatively successful using the library from within R, thanks to Tobias Madsen’s blog post. But I’d really like to use it in Python.

I tried using cython and the eigency library. It compiles, and I’m able to pass my function a numpy array and some parameter values. But it doesn’t give me the same answer as that from my c++ test code.

If you are curious, the code is up on github:
But I’ll try and produce a more manageable, minimal working example later in the week.

I also tried pybind11 with the C++11 branch of stan-maths, but I had even less success with that.

I am new to C++ and I haven’t really used cython or pybind11 before. Any pointers would be most appreciated.

PyStan itself does this, so you might want to take a look at what’s going on there:

Thanks, I had a quick look. PyStan appears to work with standard Python data structures. My idea was to send NumPy arrays to my C++ code, which worked with Eigen vector / matrices, and then output NumPy arrays to Python. But PyStan’s approach is likely easier and could definitely work for me.

If the stan maths library starts using a newer version of boost, then I might be able to leverage their new extension API to wrap NumPy. But I realise that’s a big change that would affect all other stan projects.

We’re using 1.64 now in 2.17!

Thanks. I’m using 2.17 now, and I’m successfully calling code that uses stan maths with pybind11. pybind11 is basically like boost-python. Works really well. I’m sure there are other who would be interested in doing this, so I’ll try and write something about it soon. But, at the moment, I’m a little under the gun with my Ph.D.


Stan 2.17.1 (or 2.18.0) will fix the performance regression of Stan 2.17.0. It’s already fixed on the development branch. (Detail: Adding std::string wrappers for error messages cut the speed of the whole thing roughly in half.)

1 Like