Basic stan newbe translation from jags (really quick I'm sure)

I’m trying to get my head around Stan, and so I’m trying to translate the simplest jags model I can find, and I can’t get it to work in Stan. Rather than taking up your time discussing my stupid Stan errors, could someone please explain how to model this normal=> normal conjugate jags program in Stan? Thanks so much:

Y      <- 100
sigma  <- 5
m      <- 50
s      <- 10

model_string <- "model{
Y  ~  dnorm(mu,inv.var.y)
inv.var.y <- pow(sigma,-2)
mu  ~  dnorm(m, <- pow(s,-2)

model <- jags.model(textConnection(model_string), 
                    data = list(Y=Y,sigma=sigma,m=m,s=s))
update(model, 10000)
samp <- coda.samples(model, 

not necessary to convert sd

data {
  real Y;
  real<lower=0> sigma;
  real m;
  real<lower=0> s;
parameters {
  real mu;
model {
  target += normal_lpdf(Y | mu, sigma);
  target += normal_lpdf(mu | m, s);

Call with

posterior <- stan("this_model.stan", 
                           data = list(Y = 100, sigma = 5, m = 50, s = 10))

Read Appendix B of the Stan User Manual and the FAQ

Thank you Ben. It’s the “target +=” object / operation syntax that I need to get my head around. It appears that I can just add distributions to it, including nonconjugates. Which could be really powerful. Hmmm. Thanks again. This is pretty cool stuff!

The target += foo_lpdf(... | ...) means add the logarithm of the pdf of the foo distribution to the symbol (target) that defines the log-kernel of the posterior PDF. So, you add those for each of the priors and likelihood components. At that point, you have defined the joint posterior distribution that Stan is drawing from. Conjugacy or lack thereof has nothing to do with it because the proposals for the next MCMC iteration are proposed jointly. Avoiding (full-)conditional distributions is what allows Stan to sample more efficiently than BUGS for many (differentiable) models.

You can also code this model as:

model {
  Y ~ normal(mu, sigma);
  mu ~ normal(m, s);

Unlike the target += version, it will drop unneeded constants from the computation.

As you said, target += lets you add anything you want to the log density.

Stan doesn’t exploit conjugacy at all.

thanks Mr. Carpenter. It’s starting to make sense now.