-
Notifications
You must be signed in to change notification settings - Fork 4
/
convergence_criteria.R
254 lines (211 loc) · 7.71 KB
/
convergence_criteria.R
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
#' Gelman-Rubin criterion for convergence
#'
#' Calculates the Gelman-Rubin criterion for convergence
#' (uses \code{\link[coda]{gelman.diag}} from package \strong{coda}).
#' @inheritParams sharedParams
#' @inheritParams coda::gelman.diag
#' @inheritParams summary.JointAI
#' @references
#' Gelman, A and Rubin, DB (1992) Inference from iterative simulation using
#' multiple sequences, \emph{Statistical Science}, \strong{7}, 457-511.
#'
#' Brooks, SP. and Gelman, A. (1998) General methods for monitoring convergence
#' of iterative simulations.
#' \emph{Journal of Computational and Graphical Statistics}, \strong{7}, 434-455.
#'
#' @seealso
#' The vignette
#' \href{https://nerler.github.io/JointAI/articles/SelectingParameters.html}{Parameter Selection}
#' contains some examples how to specify the argument \code{subset}.
#'
#'
#' @examples
#' mod1 <- lm_imp(y ~ C1 + C2 + M2, data = wideDF, n.iter = 100)
#' GR_crit(mod1)
#'
#'
#'
#' @export
GR_crit <- function(object, confidence = 0.95, transform = FALSE,
autoburnin = TRUE, multivariate = TRUE, subset = NULL,
exclude_chains = NULL, start = NULL, end = NULL,
thin = NULL, warn = TRUE, mess = TRUE, ...) {
if (!inherits(object, "JointAI"))
errormsg('Object must be of class "JointAI".')
if (is.null(object$MCMC))
errormsg("No MCMC sample.")
if (is.null(start))
start <- start(object$MCMC)
if (is.null(end))
end <- end(object$MCMC)
if (is.null(thin))
thin <- coda::thin(object$MCMC)
MCMC <- get_subset(object, subset, warn = warn, mess = mess)
chains <- seq_along(MCMC)
if (!is.null(exclude_chains)) {
chains <- chains[-exclude_chains]
}
MCMC <- window(MCMC[chains], start = start, end = end, thin = thin)
plotnams <- get_plotmain(object, colnames(MCMC[[1]]), ylab = TRUE)
for (i in seq_len(length(MCMC)))
colnames(MCMC[[i]]) <- plotnams
coda::gelman.diag(x = MCMC, confidence = confidence, transform = transform,
autoburnin = autoburnin, multivariate = multivariate)
}
#' Calculate and plot the Monte Carlo error
#'
#' Calculate, print and plot the Monte Carlo error of the samples from a
#' 'JointAI' model, combining the samples from all MCMC chains.
#' @param x object inheriting from class 'JointAI'
#' @param digits number of digits for the printed output
#' @inheritParams sharedParams
#' @inheritDotParams mcmcse::mcse.mat -x
#'
#' @return An object of class \code{MCElist} with elements \code{unscaled},
#' \code{scaled} and \code{digits}. The first two are matrices with
#' columns \code{est} (posterior mean), \code{MCSE} (Monte Carlo error),
#' \code{SD} (posterior standard deviation) and \code{MCSE/SD}
#' (Monte Carlo error divided by post. standard deviation.)
#'
#' @note Lesaffre & Lawson (2012; p. 195) suggest the Monte Carlo error of a
#' parameter should not be more than 5% of the posterior standard
#' deviation of this parameter (i.e., \eqn{MCSE/SD \le 0.05}).
#'
#' \strong{Long variable names:}\cr
#' The default plot margins may not be wide enough when variable names are
#' longer than a few characters. The plot margin can be adjusted (globally)
#' using the argument \code{"mar"} in \code{\link[graphics]{par}}.
#'
#'
#' @references
#' Lesaffre, E., & Lawson, A. B. (2012).
#' \emph{Bayesian Biostatistics}.
#' John Wiley & Sons.
#'
#' @seealso
#' The vignette
#' \href{https://nerler.github.io/JointAI/articles/SelectingParameters.html}{Parameter Selection}
#' provides some examples how to specify the argument \code{subset}.
#'
#' @examples
#'
#' \dontrun{
#'
#' mod <- lm_imp(y ~ C1 + C2 + M2, data = wideDF, n.iter = 100)
#'
#' MC_error(mod)
#'
#' plot(MC_error(mod), ablinepars = list(lty = 2),
#' plotpars = list(pch = 19, col = 'blue'))
#' }
#'
#' @export
MC_error <- function(x, subset = NULL, exclude_chains = NULL,
start = NULL, end = NULL, thin = NULL,
digits = 2, warn = TRUE, mess = TRUE, ...) {
if (!inherits(x, "JointAI"))
errormsg("%s must be of class %s.", dQuote("x"), sQuote("JointAI"))
if (is.null(x$MCMC)) errormsg("No MCMC sample.")
if (!"mcmcse" %in% installed.packages()[, "Package"])
errormsg("The package 'mcmcse' needs to be installed to use the function
%s.", dQuote("MC_error()"))
if (is.null(start))
start <- start(x$MCMC)
if (is.null(end))
end <- end(x$MCMC)
if (is.null(thin))
thin <- coda::thin(x$MCMC)
# MC error for MCMC sample scaled back to data scale
MCMC <- get_subset(object = x, subset = subset, warn = warn, mess = mess)
chains <- seq_along(MCMC)
if (!is.null(exclude_chains)) {
chains <- chains[-exclude_chains]
}
MCMC <- do.call(rbind, window(MCMC[chains],
start = start, end = end, thin = thin))
plotnams <- get_plotmain(x, colnames(MCMC), ylab = TRUE)
colnames(MCMC) <- plotnams
MCE1 <- t(apply(MCMC, 2, function(k) {
mce <- try(mcmcse::mcse(k, ...), silent = TRUE)
if (inherits(mce, "try-error")) {
c(NA, NA)
} else {
unlist(mce)
}
}))
colnames(MCE1) <- c("est", "MCSE")
MCE1 <- cbind(MCE1,
SD = apply(MCMC, 2, sd)[match(colnames(MCMC), row.names(MCE1))]
)
MCE1 <- cbind(MCE1,
"MCSE/SD" = MCE1[, "MCSE"] / MCE1[, "SD"])
# MC error for scaled MCMC sample
if (!is.null(x$sample)) {
mcmc <- do.call(rbind, window(x$sample[chains],
start = start, end = end, thin = thin))
MCE2 <- t(apply(mcmc, 2, function(k) {
mce <- try(mcmcse::mcse(k, ...), silent = TRUE)
if (inherits(mce, "try-error")) {
c(NA, NA)
} else {
unlist(mce)
}
}))
colnames(MCE2) <- c("est", "MCSE")
MCE2 <- cbind(MCE2, SD = apply(mcmc, 2, sd))
MCE2 <- cbind(MCE2, "MCSE/SD" = MCE2[, "MCSE"] / MCE2[, "SD"])
} else {
MCE2 <- NULL
}
out <- list(data_scale = MCE1, sampling_scale = MCE2, digits = digits)
class(out) <- "MCElist"
return(out)
}
#' @export
print.MCElist <- function(x, ...) {
print(x$data_scale, digits = x$digits)
}
# Plot Monte Carlo error
#' @param data_scale logical; show the Monte Carlo error of the sample
#' transformed back to the scale of the data (\code{TRUE}) or
#' on the sampling scale (this requires the argument
#' \code{keep_scaled_mcmc = TRUE} to be set when fitting the
#' model)
#' @param plotpars optional; list of parameters passed to
#' \code{plot()}
#' @param ablinepars optional; list of parameters passed to
#' \code{\link[graphics]{abline}()}
#' @param minlength number of characters the variable names are abbreviated to
#' @describeIn MC_error plot Monte Carlo error
#' @export
plot.MCElist <- function(x, data_scale = TRUE, plotpars = NULL,
ablinepars = list(v = 0.05), minlength = 20, ...) {
mce <- if (data_scale == TRUE) {
x$data_scale
} else {
x$sampling_scale
}
theaxis <- NULL
names <- rownames(x$data_scale)
names <- abbreviate(names, minlength = minlength)
plotpars$x <- mce[, 4]
plotpars$y <- rev(seq_len(nrow(mce)))
if (is.null(plotpars$xlim))
plotpars$xlim <- range(0, plotpars$x[!is.infinite(plotpars$x)],
na.rm = TRUE)
if (is.null(plotpars$xlab))
plotpars$xlab <- "MCE/SD"
if (is.null(plotpars$ylab))
plotpars$ylab <- ""
if (is.null(plotpars$yaxt)) {
plotpars$yaxt <- "n"
theaxis <- expression(axis(side = 2, at = rev(seq_len(nrow(mce))),
labels = names,
las = 2, cex.axis = 0.8))
}
if (is.null(ablinepars$v))
ablinepars$v <- 0.05
do.call(plot, plotpars)
eval(theaxis)
do.call(abline, ablinepars)
}