Moon-shaped Posterior

Please share your Stan program and accompanying data if possible.


I am implementing stan code for posterior

I want to get posterior
X \sim \mathcal{N}(\sqrt{\theta_1}+\sqrt{\theta_2},2 ), \theta_1 \geq 0, \theta_2 \geq 0, (\theta_1^0,\theta_2^0 =)=(1/4,1/4)

And followings are my code with stan

library(tidyverse)
library(rstan)
library(ggmcmc)


N <- 5500

sample_num <-N
x <- list()
y <- list()
theta1 <- 0.25
theta2 <- 0.25

# generate samples
for (i in (1:sample_num)){
  x[i] <- rnorm(1,sqrt(theta1)+sqrt(theta2),sqrt(2))
}

model1 <- ' 
data{
  int<lower = 0> N;
  real x[N]; 
}

parameters{
  real<lower=0> theta1;
  real<lower=0> theta2;
}

transformed parameters{
  real theta_base[N];
  for (n in 1:N)
    theta_base[n]=sqrt(theta1)+sqrt(theta2);
}

model{
  for(n in 1:N){
    x[n] ~ normal(theta_base[n],sqrt(2));
  }
}
'


# fit <- stan(model_code = model1, data = x )
fit <- stan(model_code = model1, 
            data = list(N = N, x = x, 'theta1' = theta1, 'theta2'=theta2), 
            iter = 5000, warmup = 500)

But I got error messages

"Error in new_CppObject_xp(fields$.module, fields$.pointer, …) :
Exception: mismatch in number dimensions declared and found in context; processing stage=data initialization; variable name=x; dims declared=(5500); dims found=(5500,1) (in ‘model4892c4eff02_3a7f0cbb8d98b7cdc4a85cd3401a90be’ at line 4)

failed to create the sampler; sampling not done"

I am wondering how to fix my model.

Thank you.

1 Like

Hi WonSeok,

That error is occurring because you’re passing x as a list, rather than a vector. Instead, if you prepare your data via:

theta1 <- 0.25
theta2 <- 0.25

# generate samples
 x <- rnorm(sample_num,sqrt(theta1)+sqrt(theta2),sqrt(2))

You should be able to pass x without error.

Additionally, you’re passing theta1 and theta2 as data, when they’re parameters in the model. This means that your stan call does not need to include them, and so should look like:

data = list(N = N, x = x)

Also, it’s not recommended to have so few warmup draws (i.e., iter = 5000, warmup = 500). Generally the warmup draws should be at least half of the total draws (this is the default if no warmup is specified)

2 Likes

Thank you for your comment! I fixed it.