##
##Control coarseness of fan via pn
##
# calculate percentiles across time
th.pn <- pn(sims = th.mcmc)
th.pn2 <- pn(sims = th.mcmc, p = c(1, 10, 40, 50))
# empty plot
plot(NULL, type = "n", xlim = c(1, 945), ylim = range(th.pn), ylab = "Theta")
# add fan
fan(th.pn)
# empty plot
plot(NULL, type = "n", xlim = c(1, 945), ylim = range(th.pn), ylab = "Theta")
# add coarser fan
fan(th.pn2)
##
##Prediction intervals
##
th.pn <- pn(sims = th.mcmc, p.int=seq(10,90,10), type="intervals")
head(th.pn)
plot(NULL, type = "n", xlim = c(1, 945), ylim = range(th.pn), ylab = "Theta")
fan(th.pn, ln=c(50,80,90))
fan.txt(th.pn, pn.l = c(10,30,70), hl.lab=c("L","U"))
##
##Forecast fans 1) default 2) coarser colours, different contour line colour and anchoring fan
##
# create BUGS model
library("tsbugs")
r <- diff(log(ew))
y <- diff(r)
pop.bug <- sv.bugs(y, k=25, sim=TRUE,
sv.mean.prior2 = "dgamma(0.000001,0.000001)",
sv.ar.prior2 = "dunif(-0.999, 0.999)")
# run in OpenBUGS
library("R2OpenBUGS")
writeLines(pop.bug$bug, "pop.txt")
pop <- bugs(data = pop.bug$data,
inits = list(list(psi0.star=exp(12), psi1=0.5, itau2=0.5)),
param = c("psi0", "psi1", "tau", "y.new", "y.sim"),
model = "pop.txt",
n.iter = 11000, n.burnin = 1000, n.chains = 1)
# derive posterior predictive distributions of the population growth rate and population total
ynew.mcmc <- pop$sims.list$y.new
rnew.mcmc <- apply(ynew.mcmc, 1, diffinv, xi = tail(r,1))
rnew.mcmc <- t(rnew.mcmc[-1,])
pnew.mcmc <- apply(1+rnew.mcmc, 1, cumprod) * tail(ew,1)
pnew.mcmc <- t(pnew.mcmc)
# calculate percentiles across time
r0 <- tsp(r)[2]
rnew.pn <- pn(sims = rnew.mcmc, start = r0 + 1)
pnew.pn <- pn(sims = pnew.mcmc/1e+06, start = r0 + 1, anchor = tail(ew/1e+06, 1),)
# plot ew
par(mfrow = c(1 ,2))
plot(ew/1e+06, ylim = c(40, 80), xlim = c(1940, 2040), ylab = "Population (m)", lwd = 2)
# add fan
fan(pnew.pn)
# plot ew
plot(ew/1e+06, ylim = c(40, 80), xlim = c(1940, 2040), ylab = "Population (m)", lwd = 2)
# add fan
fan(pnew.pn2, ln.col = "black")
Run the code above in your browser using DataLab