Including boost function into Stan by Pystan 2.18.0

Hello Stanimaniacs,

Now I’d like to use associated legendre function of the first kind in Stan.
As well as this topic(Legendre polynomials), I tried to import C++ function to Stan. Checked the milestone in PyStan, I used version 2.18.0 released one weeks ago because it looks that introduce utility is now available,

First I tested import from Stan file checking this issue(, and it goes well. Next I tried importing besselK function from C++ file as this article( explained, but it failed. Then, I noticed that PyStan disallow the undefined function and cannot be changed(Line 141 in Above example doesn’t have the example about including hpp file with include declaration. Is there any method to use C++ function in PyStan?

The Stan file I tried is

functions {
    #include besselK.hpp
    real besselK(real v, real z);
model {}

, hpp file is

template <typename T0__, typename T1__>
besselK(const T0__& v, const T1__& z, std::ostream* pstream__) -> decltype(v + z) {
  return boost::math::cyl_bessel_k(v, z);

, and Python command is

from pystan import StanModel
model = StanModel(file="besselK.stan")

You probably need to edit the PyStan source.

There was one blogpost going through that but I have not tested that.

+1 for use of the term “Stanimaniancs”

1 Like


Thanks for your information. But if importing C++ code to PyStan is impossible, because the function I’d like to import has already been in Boost, it might be better to edit the Stan code to enable to use associated Legendre function.


This nickname is inspired by Prof. DM Blei ( I like it too.

I thought Stanimals was canonical.

1 Like

I agree, it is probably easier that way.

I have not followed external C++ discussion lately, but was there some plan to handle external hpp files (in Stan-side)?

@Bob_Carpenter @sakrejda