Interfacing Stan with an external program

Hi there,

I am a very basic Stan user who’s been using it for constraining cosmological models for a couple of months now.
My challenges so far have been quite simple, taking a dataset with a x, f(x) and an error σ, and compare it with my model which as an analytical expression for f(x), which I have coded in Stan, using a Gaussian likelihood.

Now, I am looking to extend my analysis using a function which cannot be easily coded in Stan, in fact, most people in my field don’t code it either as there are already pre-existing programs optimized to perform such calculations, as they are quite expensive.
In this case, the program which I am looking to use, which is called CLASS, is written in C, can be called directly from the terminal given a configuration file, and features both a Python and C++ wrapper.
I know that Stan can work with external C++ functions, but this is a wrapper for a C program which I have no idea how it works internally.

Considering that Stan has showed to perform significantly well, I would like to know how hard could it be to have Stan use the output of this program has its model, instead of a function coded in a .stan model file, consider its available wrappers.

Here is one example, but you would need to do this manually with cmdstan or maybe with rstan (or pystan2)

Maybe I should have showed what I had already looked for, because I already came across that post (interestingly, by an astronomer), unfortunately the Github link seems to be dead.

I was also concerned about using pystan2, which has a lot more feature of pystan, which I’m currently using, yet I thought it was deprecated. Should I be using pystan2?

Here are old docs

And old github

I would not recommend using pystan2 but doing the same steps manually with CmdStan. (I think cmdstanpy might not work too well with this workflow, but I might be wrong cc @mitzimorris @WardBrian )


It is possible, but there are a few extra steps (such as placing the function in a specific namespace) detailed there

1 Like

Thank you for the links.
I wonder if such a feature is more easily implemented in RStan, as was mentioned before, because if so, I wouldn’t mind giving R a try.