WardBrian / pybind_expose_stan_fns

Exposing Stan functions in Python
BSD 3-Clause "New" or "Revised" License
7 stars 1 forks source link
cmdstan pybind11 python stan

Exposing Stan functions in Python through PyBind11

This repo contains (a very work in progress attempt at) code to expose functions written in a Stan model to the Python runtime through the PyBind11 library.

This is very similar to Exposing Stan user-defined functions using CmdStanR and Rcpp.

This supports all possible Stan functions, including pRNGs and functions which edit the target variable. These are supported through two objects exposed on all models, StanRNG and StanAccumulator, which are thin wrappers for stan::rng_t and stan::math::accumulator<double>, respectively.

Running

This assumes you have a working installation of CmdStan, and a Python environment with both cmdstanpy and PyBind11

import pybind_stan_fns
basic = pybind_stan_fns.expose('./test/basic.stan')
basic.test_printing() # etc

Note: On Windows, the above is not sufficient. One also must have the Microsoft Visual Studio Build Tools, including the optional LLVM/Clang extensions, and a pre-built version of both Sundials and TBB. The expose function assumes these were installed via conda. Our CI Pipeline shows how this is done in Github Actions

Miscellany

There is a (possibly outdated) pure-shell version of this which just runs g++ directly.

./build.sh basic.stan
python test_basic.stan

Similarly on Windows, there is a build.ps1 powershell script.

Finally, there is also a version which attempts to use setuptools for the same effect.