1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
|
"gelman.diag" <- function (x, confidence = 0.95, transform = FALSE,
autoburnin=TRUE)
## Gelman and Rubin's diagnostic
## Gelman, A. and Rubin, D (1992). Inference from iterative simulation
## using multiple sequences. Statistical Science, 7, 457-551.
##
## Correction and Multivariate generalization:
## Brooks, S.P. and Gelman, A. (1997) General methods for monitoring
## convergence of iterative simulations. Journal of Computational and
## Graphical Statistics, 7, 434-455.
{
x <- as.mcmc.list(x)
if (nchain(x) < 2)
stop("You need at least two chains")
## RGA added an autoburnin parameter here, because if I have already
## trimmed burn in, I don't want to do it again.
if (autoburnin && start(x) < end(x)/2 )
x <- window(x, start = end(x)/2 + 1)
Niter <- niter(x)
Nchain <- nchain(x)
Nvar <- nvar(x)
xnames <- varnames(x)
if(transform)
x <- gelman.transform(x)
##
## Estimate mean within-chain variance (W) and between-chain variance
## (B/Niter), and calculate sampling variances and covariance of the
## estimates (varW, varB, covWB)
##
## Multivariate (upper case)
x <- lapply(x, as.matrix)
S2 <- array(sapply(x, var, simplify=TRUE), dim=c(Nvar,Nvar,Nchain))
W <- apply(S2, c(1,2), mean)
xbar <- matrix(sapply(x, apply, 2, mean, simplify=TRUE), nrow=Nvar,
ncol=Nchain)
B <- Niter * var(t(xbar))
if(Nvar > 1) {
emax <- eigen(qr.solve(W,B), symmetric=FALSE, only.values=TRUE)$values[1]
mpsrf <- sqrt( (1 - 1/Niter) + (1 + 1/Nvar) * emax/Niter )
}
else
mpsrf <- NULL
## Univariate (lower case)
w <- diag(W)
b <- diag(B)
s2 <- matrix(apply(S2, 3, diag), nrow=Nvar, ncol=Nchain)
muhat <- apply(xbar,1,mean)
var.w <- apply(s2, 1, var)/Nchain
var.b <- (2 * b^2)/(Nchain - 1)
cov.wb <- (Niter/Nchain) * diag(var(t(s2), t(xbar^2)) -
2 * muhat * var(t(s2), t(xbar)))
##
## Posterior interval combines all uncertainties in a t interval with
## center muhat, scale sqrt(V), and df.V degrees of freedom.
##
V <- (Niter - 1) * w / Niter + (1 + 1/Nchain) * b/ Niter
var.V <- ((Niter - 1)^2 * var.w + (1 + 1/Nchain)^2 *
var.b + 2 * (Niter - 1) * (1 + 1/Nchain) * cov.wb)/Niter^2
df.V <- (2 * V^2)/var.V
##
## Potential scale reduction factor (that would be achieved by
## continuing simulations forever) is estimated by
## R = sqrt(V/W) * df.adj
## where df.adj is a degrees of freedom adjustment for the width
## of the t-interval.
##
## To calculate upper confidence interval we divide R2 = R^2 into two
## parts, fixed and random. The upper limit of the random part is
## calculated assuming that B/W has an F distribution.
##
df.adj <- (df.V + 3)/(df.V + 1)
B.df <- Nchain - 1
W.df <- (2 * w^2)/var.w
R2.fixed <- (Niter - 1)/Niter
R2.random <- (1 + 1/Nchain) * (1/Niter) * (b/w)
R2.estimate <- R2.fixed + R2.random
R2.upper <- R2.fixed + qf((1 + confidence)/2, B.df, W.df) * R2.random
psrf <- cbind(sqrt(df.adj * R2.estimate), sqrt(df.adj * R2.upper))
dimnames(psrf) <- list(xnames,
c("Point est.",
paste(50 * (1+confidence), "% quantile", sep = ""))
)
out <- list(psrf = psrf, mpsrf=mpsrf)
class(out) <- "gelman.diag"
out
}
"gelman.transform" <- function(x)
## Gelman and Rubin diagnostic assumes a normal distribution. To
## improve the normal approximation, variables on [0, Inf) are log
## transformed, and variables on [0,1] are logit-transformed.
{
if (!is.R()) {
# in S-PLUS this function generates a superfluous warning,
# so turn off all warnings during the function.
oldWarn <- getOption("warn")
options(warn=-1)
on.exit(options (warn=oldWarn))
}
if (nvar(x) == 1) {
z <- data.frame(lapply(x, unclass))
if (min(z) > 0) {
y <- if(max(z) < 1)
log(z/(1-z))
else log(z)
for (j in 1:nchain(x)) x[[j]] <- y[,j]
}
}
else for (i in 1:nvar(x)) {
z <- data.frame(lapply(x[, i], unclass))
if (min(z) > 0) {
y <- if (max(z) < 1)
log(z/(1 - z))
else log(z)
for (j in 1:nchain(x)) x[[j]][, i] <- y[, j]
}
}
return(x)
}
"gelman.mv.diag" <- function (x, confidence = 0.95, transform = FALSE)
{
s2 <- sapply(x, var, simplify=TRUE)
W <- matrix(apply(s2, 1, mean), nvar(x), nvar(x))
xbar <- sapply(x, apply, 2, mean, simplify=TRUE)
B <- niter(x) * var(t(xbar))
emax <- eigen(qr.solve(W,B), symmetric=FALSE, only.values=TRUE)$values[1]
mpsrf <- sqrt( (1 - 1/niter(x)) + (1 + 1/nvar(x)) * emax )
return(mpsrf)
}
"print.gelman.diag" <-
function (x, digits = 3, ...)
{
cat("Potential scale reduction factors:\n\n")
print.default(x$psrf, digits = digits, ...)
if(!is.null(x$mpsrf)) {
cat("\nMultivariate psrf\n\n")
cat(format(x$mpsrf,digits = digits))
}
cat("\n")
}
"gelman.plot" <-
function (x, bin.width = 10, max.bins = 50, confidence = 0.95,
transform = FALSE, auto.layout = TRUE, ask,
col = 1:2, lty = 1:2, xlab = "last iteration in chain",
ylab = "shrink factor", type = "l", ...)
{
if (missing(ask)) {
ask <- if (is.R()) {
dev.interactive()
}
else {
interactive()
}
}
x <- as.mcmc.list(x)
oldpar <- NULL
on.exit(par(oldpar))
if (auto.layout)
oldpar <- par(mfrow = set.mfrow(Nchains = nchain(x), Nparms = nvar(x)))
y <- gelman.preplot(x, bin.width = bin.width, max.bins = max.bins,
confidence = confidence)
all.na <- apply(is.na(y$shrink[, , 1, drop = FALSE]), 2, all)
if (!any(all.na))
for (j in 1:nvar(x)) {
matplot(y$last.iter, y$shrink[, j, ], col = col,
lty = lty, xlab = xlab, ylab = ylab, type = type,
...)
abline(h = 1)
ymax <- max(c(1, y$shrink[, j, ]), na.rm = TRUE)
leg <- dimnames(y$shrink)[[3]]
xmax <- max(y$last.iter)
legend(xmax, ymax, legend = leg, lty = lty, bty = "n",
col = col, xjust = 1, yjust = 1)
title(main = varnames(x)[j])
if (j==1)
oldpar <- c(oldpar, par(ask = ask))
}
return(invisible(y))
}
"gelman.preplot" <-
function (x, confidence = 0.95, transform = FALSE, bin.width = 10,
max.bins = 50)
{
x <- as.mcmc.list(x)
if (niter(x) <= 50)
stop("Less than 50 iterations in chain")
nbin <- min(floor((niter(x) - 50)/thin(x)), max.bins)
binw <- floor((niter(x) - 50)/nbin)
last.iter <- c(seq(from = start(x) + 50 * thin(x), by = binw *
thin(x), length = nbin), end(x))
shrink <- array(dim = c(nbin + 1, nvar(x), 2))
dimnames(shrink) <- list(last.iter, varnames(x),
c("median", paste(50 * (confidence + 1), "%",
sep = ""))
)
for (i in 1:(nbin + 1)) {
shrink[i, , ] <- gelman.diag(window(x, end = last.iter[i]),
confidence = confidence,
transform = transform)$psrf
}
all.na <- apply(is.na(shrink[, , 1, drop = FALSE]), 2, all)
if (any(all.na)) {
cat("\n******* Error: *******\n")
cat("Cannot compute Gelman & Rubin's diagnostic for any chain \n")
cat("segments for variables", varnames(x)[all.na], "\n")
cat("This indicates convergence failure\n")
}
return(list(shrink = shrink, last.iter = last.iter))
}
if (!is.R()){
qr.solve <- function (a, b, tol = 1e-07) {
if (!is.qr(a))
a <- qr(a, tol = tol)
nc <- ncol(a$qr)
if (a$rank != nc)
stop("singular matrix 'a' in solve")
if (missing(b)) {
if (nc != nrow(a$qr))
stop("only square matrices can be inverted")
b <- diag(1, nc)
}
return(qr.coef(a, b))
}
}
|