# How to stop Stan from sampling a transformed parameter

Hey folks,
A model I’m working on uses a Dirichlet-multinomial conjugate pair, and runs accurately. However, the simplex that I feed to my Dirichlet prior (“alpha_vec”) is being needlessly sampled, slowing things down. How can I tell Stan that I don’t need this to be sampled (after all, it’s the same every time)?
Here’s the code

``````data {
// Prior Parameters
int<lower = 1> K; 		// COLS. for Dirichlet & txn mat
int<lower = 1> N; 		// ROWS. for txn mat
real<lower = 0> alpha; 	// for Dirichlet

// Experimental Parameters
int T[N,K]; 		// input RAW txn matrix, the data
}

parameters {
simplex[N] P[K];       // parameter of interest
}

transformed parameters {
vector[K] alpha_vec;
for(i in 1:K){
alpha_vec[i] = alpha;
}
}

model {
for(i in 1:N) {
P[i] ~ dirichlet(alpha_vec);  // prior
T[i] ~ multinomial(P[i]);     // LLK
}
}

``````

The output of the fit (in Rstan) is: I’ve tried relabelling the “transformed parameters” block to “transformed data” and “generated quantities,” but both of these prevent the model from compiling.
Much appreciated!

Could you make it in `transformed data`?

2 Likes

Thanks for the reply! I tried that, but it doesn’t seem to like it: Is it after data like this? transformed data needs to be before the parameters block.

``````data {
// Prior Parameters
int<lower = 1> K; 		// COLS. for Dirichlet & txn mat
int<lower = 1> N; 		// ROWS. for txn mat
real<lower = 0> alpha; 	// for Dirichlet

// Experimental Parameters
int T[N,K]; 		// input RAW txn matrix, the data
}

transformed data {
vector[K] alpha_vec;
for(i in 1:K) {
alpha_vec[i] = alpha;
}
}

parameters {
simplex[N] P[K];       // parameter of interest
}

``````

If the above works then we should really improve that error message because it’s not terribly informative

2 Likes

Yeah good call. It should say something about the required order of the blocks.

2 Likes

Woops — completely forgot about that rule. Worked like a charm. Thanks so much, Steve!

1 Like

The new stanc3 compiler has a different message:

``````
Syntax error in 'model.stan', line 11, column 0 to line 13, column 1, parsing error:
-------------------------------------------------
11:  parameters {
12:    simplex[N] P[K];       // parameter of interest
13:  }
^
14:
15:  transformed data {
-------------------------------------------------

"transformed parameters {", "model {" or "generated quantities {" expected after end of parameters block.
``````

Still not ideal; the caret points to the wrong line it didn’t recognize `transformed data` as a valid (if misplaced) block name.

3 Likes

Yeah still not ideal, but that’s definitely an improvement!

3 Likes