Whith the help of Bob, I am trying to define a generalized poisson distribution. But I am not very clear about dealing with "n" in the function.
Do I need define n<-uniform_rng(-1,1000000)? If so, should I regard n as a parameter or not?
For defining a distribution f(x), there are 3 things, first, we need know the pdf. Second, we need define the parameters. Last, how can we define the x? Besides,for many of distributions, the range of x is (-inf, inf).
library(rstan)
cat("Stan version:", stan_version(), "\n")
stanmodelcode <- "
functions {
real generalized_poisson_log(int y, int n, real theta, real lambda) {
return log(theta)
+ (n - 1) * log(theta + n * lambda)
- lgamma(n + 1)
- n * lambda
- theta;
}
}
data {
int<lower=0> N;
int y[N];
}
parameters {
real<lower=0, upper=0.5> d;
real c;
real<lower=0> sig2;
real<lower=-1, upper=1> u;
real<lower=-1, upper=1> lambda;
vector[N] e;
}
transformed parameters {
vector[N] mu;
real D0;
real D1;
real D2;
real D3;
D0 <- 1;
D1 <- 2*d*u;
D2 <- 2*u*((d-1)/2.0+1)*D1-(2*(d-1/2.0)+1)*D0;
D3 <- 2*u*((d-1)/3.0+1)*D2-(2*(d-1/3.0)+1)*D1;
mu[1] <- exp(c+e[1]);
mu[2] <- exp(c+e[2] + D1*e[1]);
mu[3] <- exp(c+e[3] + D1*e[2] + D2*e[1]);
for (i in 4:N) {
mu[i] <- exp(c+e[i] + D1*e[i-1] + D2*e[i-2]+D3*e[i-3]);
}
}
model {
u ~ uniform(-1,1);
c ~ normal(0,10);
d ~ uniform(0,0.5);
sig2~gamma(3,1);
e~normal(0,sig2);
lambda~uniform(-1,1);
for (j in 1:N) {
y[j] ~ generalized_poisson(n, mu[j]*(1-lambda), lambda);
}
}
"
y=c(0,1,0,1,3,9,2,3,5,3,5,2,2,0,1,0,1,3,3,2,1,1,5,0,3,1,0,1,4,0,0,1,6,14,1,1,0,0,1,1,1,1,0,2,0,2,0,1,0,1,0,1,0,1,0,1,0,0,2,0,1,0,1,0,0,1,2,0,0,1,2,0,3,1,1,0,2,0,4,0,2,1,1,1,1,0,1,1,0,2,1,3,1,2,4,0,0,0,1,0,1,0,2,2,4,2,3,3,0,0,2,7,8,2,4,1,1,2,4,0,1,1,1,3,0,0,0,0,1,0,2,2,0,0,0,0,0,1,2,0,2,0,0,0,1,0,1,0,1,0,2,0,0,1,2,0,1,0,0,0,1,2,1,0,1,3,6)
dat <- list(N = 167, y = y);
fit <- stan(model_code = stanmodelcode, model_name = "example",
data = dat, iter = 2012, chains = 3)
print(fit)