Random subset of integers within the transformed parameters block

How can I generate a random set of integers to be used dynamically within the transformed parameters block for subsetting a vector in each MCMC iteration?

For example, I would like to randomly select 10 elements from a vector during each iteration.

I’m aware that I can generate this set in the transformed data block using the following code:

int<lower=1, upper=m> set[m];
  for (i in 1:m) {
    set[i] = categorical_rng(rep_vector(1,m) / m);
  }

However, this block is executed only once during initialization. Using the generated quantities block won’t allow me to use the set in other blocks.

Is there a way to generate a fresh set of random integers for subsetting in each MCMC iteration?

You cannot do this; it would break gradients and would not be amenable to sampling, so it isn’t allowed.

1 Like

Thank you. It does seem a bit restrictive.
One potential workaround might involve utilizing the MCMC iteration or step number, although I haven’t come across a straightforward method for achieving this yet (Is it possible to access the iteration/step number inside a Stan program? - #23 by Louis).

Subsetting based on the iteration number might not break gradients, but it would break adaptation and also would fail to work, and so it isn’t allowed. Restrictions like these are the price we pay for efficient and accurate dynamic HMC.

1 Like