Sampling within another C++ program, how to construct `var_context`?

I am trying to write a C++ program within which posterior samples are generated using Stan’s sampler and then those samples go on to be part of another calculation, rather than returning the samples and calling a new function externally.

I have generated the .hpp file using stanc, which defines a new class, e.g. gaussian_model. I then assume I can generate a new model as something like

gaussian_model model(stan::io::var_context &context, unsigned int seed, ...);

then pass model as an argument to stan::services::sample::hmc_nuts_diag_e_adapt. However, I am having trouble working out, or finding examples, about how to construct a stan::io::var_context object. The array_var_context class seems to have constructors that match more the type of data that might be input and I could translate the data into std::vector, but how do you generate the var_context from the array_var_context?. I can also generate a JSON file of the data for the model or other required format. Is there a way of generating a var_context given these files?

The sampler can be called with stan::services::sample::hmc_nuts_diag_e_adapt, which takes the model object as an argument, and also another stan::io::var_context object. Is this right that this var_context is the initial values for the parameters and chains? If so, what structure should these be in?

The best reference here would be the cmdstan source: cmdstan/command.hpp at develop · stan-dev/cmdstan · GitHub

This shows how cmdstan takes input data and inits, and constructs the var_contexts for sampling

Thanks @andrjohns, that’s what i was looking for. Do you know if there are any plans to document the C++ API?

I’ll defer this to @WardBrian or @Bob_Carpenter since they’re much more familiar with the current doc and plans

I believe the stan-dev/stan repository has documentation if you run “make doxygen”. It is not hosted anywhere to my knowledge.

To answer a few of your questions:

array_var_context is a subclass of var_context. Once you have created it, you can simply pass it directly as a var_context, no further steps needed.

The same is true for the JSON var context in src/stan/io/json/json_data.hpp, which can be used for JSON files