= in model

Hi!
I am pretty much a beginner here still. There are some pieces of code where I wonder what is the “best” solution. Many of them involve convenience variables where I really just want to shuffle a value from one place to another. See below. The = assignment does not work. I can hack in a uniform(a,a) but I suspect this is not good at all. So, what is the idiomatic way of handling this?


  for(p in 1:num_pools){
      for(m in 1:num_mutants){
          if( poolconc_prior[p,m] == 0){  
              poolconc[m] = 0;
          } else {
              poolconc[m] ~ exponential(1000);
          }
      }
  }

Here is a more complex later piece of logic where the model is just deterministic

  for(m in 1:num_mutants){
    for(L in 1:num_libraries){
      if( library_previous_day[L] == -1){  
        //First day: This is the initial transfection of mice
        mouseconc[m,L] = poolconc[m]; 
      } else {
        //This is a later day; simulate growth
        mouseconc[m,L] = pow(2.0, mouseconc[m, library_previous_day[L]] * growthrate[growthrate_index[L]]);
      }
    }
  }

All input appreciated!

minor correction, 2nd case: the function is deterministic, but the input is not. so ~ in some sense makes sense … except STAN seems to force me to provide a distribution?

With Stan, it’s not possible to have fixed values for parameters. If you have declared poolconc as a parameter, then all elements need to have a prior specified.

If you want to have a vector/matrix which is partially composed of parameters with priors, you need to declare a separate vector of those elements as parameters and then assign them using the transformed parameters block.

Something like:

parameters {
  vector[N_pars] poolconc_pars;
}

transformed parameters {
  vector[m] poolconc;
 {
  int par_ind = 1; // temp variable to track index of poolconc_pars vector
  for(p in 1:num_pools){
        for(m in 1:num_mutants){
            if( poolconc_prior[p,m] == 0){  
                poolconc[m] = 0;
            } else {
                poolconc[m]  = poolconc_pars[par_ind];
               par_ind  += 1;
            }
        }
    }
  }
}

model {
  poolconc_pars ~ exponential(1000);
}
1 Like

Thanks for the excellent answer!

Note to others; so my need here largely follows from handling sparse input. But I think I would naturally get your solution if I melt and use long format for all the input matrices. So I guess this is the solution I should go for

There’s also a discussion in the User’s Guide on the two ways to do this.

Long form is usually the better way to go if you don’t need to impute the missing values and the missing values are conditionally independent given parameters. Usually that means missing observations rather than missing predictors.