Short blog on conditional parameters in Stan

I just wrote a short post on how to use ternary operator to get optional/conditional parameters and/or data in Stan if anyone’s interested.


Nice, I was just looking for this feature. Here’s a another variant:

data {
  int N;
  vector[N] X;

  real sigma_mu;
  real<lower=0> sigma_sigma;

parameters {
  real mu;
  real<lower=0> sigma[(sigma_sigma > 0) ? 1 :  0];

model {
  real sigma_in = (sigma_sigma > 0) ? sigma[1] : sigma_mu;

  // conditonal prior on sigma
  if (sigma_sigma > 0) sigma[1] ~ normal(sigma_mu, sigma_sigma);

  // likelihood where sigma_in is either a uncertain parameter or a deterministic data input
  X ~ normal(mu, sigma_in);

Calling the above Stan model with sigma_sigma set to a non zero value treats ´sigma_in´ as an uncertain parameter that is sampled during the HMC inference. While setting sigma_sigma set to zero treats the ´sigma_in´ as an deterministic data input, which can result in a more efficient computation (the model above gets almost halved execution time).

Perhaps, this kind of optimization could be done within the Stan language? A sampling statement normal_test_if_data_or_parameter(mu, sigma) could maybe test if ´sigma´ is a data input & equal to zero, in which case sampling is unnecessary.

Update: a less verbose variant.

1 Like

This is great! Coming from R, where ternary operators don’t seem to be very common, the notation of this kind of if-else statement was foreign to me. I also didn’t understand its utility when it was mentioned in the Stan manual. So the post was clarifying!

Also, the post link seems to have a “/” instead of a “-” in it at one point. This link should work:

1 Like

Thanks for noticing, the link probably changed with update to Hugo, fixed.