if (FALSE) {
set.seed(11119)
n <- 150
x1 <- runif(n, 0, 0.5)
true.beta1 <- c(1, 1)
true.beta2 <- c(1, -2)
true.beta3 <- c(1, 2)
## set true two breaks at (50, 100)
true.s <- rep(1:3, each=n/3)
mu1 <- exp(1 + x1[true.s==1]*1)
mu2 <- exp(1 + x1[true.s==2]*-2)
mu3 <- exp(1 + x1[true.s==3]*2)
y <- as.ts(c(rpois(n/3, mu1), rpois(n/3, mu2), rpois(n/3, mu3)))
formula = y ~ x1
## fit multiple models with a varying number of breaks
model0 <- MCMCpoissonChange(formula, m=0,
mcmc = 1000, burnin = 1000, verbose = 500,
b0 = rep(0, 2), B0 = 1/5*diag(2), marginal.likelihood = "Chib95")
model1 <- MCMCpoissonChange(formula, m=1,
mcmc = 1000, burnin = 1000, verbose = 500,
b0 = rep(0, 2), B0 = 1/5*diag(2), marginal.likelihood = "Chib95")
model2 <- MCMCpoissonChange(formula, m=2,
mcmc = 1000, burnin = 1000, verbose = 500,
b0 = rep(0, 2), B0 = 1/5*diag(2), marginal.likelihood = "Chib95")
model3 <- MCMCpoissonChange(formula, m=3,
mcmc = 1000, burnin = 1000, verbose = 500,
b0 = rep(0, 2), B0 = 1/5*diag(2), marginal.likelihood = "Chib95")
model4 <- MCMCpoissonChange(formula, m=4,
mcmc = 1000, burnin = 1000, verbose = 500,
b0 = rep(0, 2), B0 = 1/5*diag(2), marginal.likelihood = "Chib95")
model5 <- MCMCpoissonChange(formula, m=5,
mcmc = 1000, burnin = 1000, verbose = 500,
b0 = rep(0, 2), B0 = 1/5*diag(2), marginal.likelihood = "Chib95")
## find the most reasonable one
print(BayesFactor(model0, model1, model2, model3, model4, model5))
## draw plots using the "right" model
par(mfrow=c(attr(model2, "m") + 1, 1), mai=c(0.4, 0.6, 0.3, 0.05))
plotState(model2, legend.control = c(1, 0.6))
plotChangepoint(model2, verbose = TRUE, ylab="Density", start=1, overlay=TRUE)
## No covariate case
model2.1 <- MCMCpoissonChange(y ~ 1, m = 2, c0 = 2, d0 = 1,
mcmc = 1000, burnin = 1000, verbose = 500,
marginal.likelihood = "Chib95")
print(BayesFactor(model2, model2.1))
}
Run the code above in your browser using DataLab