Is it possible to access the iteration/step number inside a Stan program?

I also found myself wanting to access the mcmc iteration number. I found a simple way to do it, which I share here just in case it is useful to someone. What bbbales2 suggested almost works. The key idea is to call the C++ function in the generated quantities block since such block is executed only once per mcmc iteration. We can define the following two C++ functions:

static int itct = 1;
inline void add_iter(std::ostream* pstream__) {
    itct += 1;
}
inline int get_iter(std::ostream* pstream__) {
    return itct;
}

Then within Stan:

functions{
    void add_iter();
    int get_iter();
}
model{
    print(get_iter()); // this will return the mcmc iteration number
}
generated quantities{
    add_iter(); // increment the counter after each iteration
}

You place the “add_iter()” function within the generated quantities block. Then, you can call the “get_iter()” function in any of the other blocks whenever needed and this will return the iteration number.

If you’re running multiple chains and you would like to discriminate among chains, then you could use something like the C++ function “getpid()” to get the PID for each chain/process.

3 Likes