Using Pure C++ Instead of CommandStan


#1

I’m trying to do what CmdStan is doing (minus writing and reading text files) using pure C++ code.

For example, using the generated CommandStan model executable, I would do this:

./model data file=data.R output file=sampleOutput.csv random seed=1234567890 sample num_samples=1000 num_warmup=1000

Digging through unit tests I have been able to figure out part of it (some code omitted for brevity):

model_namespace::model *myModel = new model_namespace::model(varContext, seed, &os);

stan::mcmc::unit_e_static_uniform<stan_model, rng_t>
            sampler(*myModel, base_rng);

sampler.z() = z_init;
sampler.init_hamiltonian(logger);
sampler.set_nominal_stepsize(0.1);
sampler.set_stepsize_jitter(0);
sampler.sample_stepsize();

stan::mcmc::sample init_sample(z_init.q, 0, 0);
stan::mcmc::sample s = sampler.transition(init_sample, logger);

Ultimately I would like to be able to, through c++, get my parameter’s mean and standard deviation.

I’m by no means an expert in this field so it’s taking me a large amount of time to dig through the source code trying to find the proper procedure. I’ve found some documentation explaining the model concept, but I haven’t been able to find details on what I’m looking to do. So I was hoping for a nudge in the right direction from someone that understands this better than I.


#2

Running the commands in CmdStan involves the code in src/stan/services in the services repo.

What you need to do to get output in C++ is implement all the callbacks. There are examples in the CmdStan code that calls these service methods.

Calculations of things like mean are done in the summary executable of CmdStan. You can trace down through that, too, to see where things are going on. You could also look at how PyStan and RStan use the underlying Stan services and how they implement callbacks.

The other place to look is unit tests. But these aren’t great up at these high levels due to the combinatorics and difficultly of stubbing out all the callbacks.

We’re about to do a major facelift on the model concept to implement it as a proper base class that can plug into other applications, but that’s going to take a bit of time.


#3

Thanks Bob! I’ll take a look.