# NOT RUN {
##
## Example 1: Fit an AR(p) model to sunspot data:
##
# Use this variable to set the autoregressive model order
ar.order <- 2
data <- sqrt(as.numeric(sunspot.year))
data <- data - mean(data)
# If you run the example be aware that this may take several minutes
print("example may take some time to run")
mcmc <- gibbs_AR(data=data, Ntotal=20000, burnin=8000, ar.order=ar.order)
# Plot spectral estimates on log-scale (excluding the zero frequency).
N <- length(mcmc$psd.median)
pdgrm <- (abs(fft(data))^2 / (2*pi*length(data)))[1:N]
plot.ts(log(pdgrm[-1]), col="gray",
main=paste0("Sunspot AR results on logarithmic scale for p=", ar.order))
lines(log(mcmc$psd.median[-1]))
lines(log(mcmc$psd.p05[-1]),lty=2)
lines(log(mcmc$psd.p95[-1]),lty=2)
lines(log(mcmc$psd.u05[-1]),lty=3)
lines(log(mcmc$psd.u95[-1]),lty=3)
legend(x="topright", legend=c("periodogram", "pointwise median",
"pointwise CI", "uniform CI"), lty=c(1,1,2,3), col=c("gray", 1, 1, 1))
##
## Example 2: Fit an AR(p) model to high-peaked AR(1) data
##
# Use this variable to set the autoregressive model order
ar.order <- 1
n <- 256
data <- arima.sim(n=n, model=list(ar=0.95))
data <- data - mean(data)
psd_true <- psd_arma(pi*omegaFreq(n), ar=0.95, ma=numeric(0), sigma2=1)
# If you run the example be aware that this may take several minutes
print("example may take some time to run")
mcmc <- gibbs_AR(data=data, Ntotal=20000, burnin=8000, ar.order=1)
# Plot spectral estimates
N <- length(mcmc$psd.median)
pdgrm <- (abs(fft(data))^2 / (2*pi*length(data)))[1:N]
plot.ts(pdgrm[-1], col="gray",
main=paste0("AR(1) data AR results for p=", ar.order))
lines(mcmc$psd.median[-1])
lines(mcmc$psd.p05[-1],lty=2)
lines(mcmc$psd.p95[-1],lty=2)
lines(mcmc$psd.u05[-1],lty=3)
lines(mcmc$psd.u95[-1],lty=3)
lines(psd_true[-1],col=2)
legend(x="topright", legend=c("periodogram", "true psd",
"pointwise median", "pointwise CI", "uniform CI"), lty=c(1,1,1,2,3),
col=c("gray", "red", 1, 1, 1))
# Compute the Integrated Absolute Error (IAE) of posterior median
cat("IAE=", mean(abs(mcmc$psd.median-psd_true)[-1]) , sep="")
# }
Run the code above in your browser using DataLab