The intrinsic conditional auto-regressive (ICAR) model for spatial count data. Options include the BYM model, the BYM2 model, and a solo ICAR term.
stan_icar(
formula,
slx,
re,
data,
C,
family = poisson(),
type = c("icar", "bym", "bym2"),
scale_factor = NULL,
prior = NULL,
ME = NULL,
centerx = FALSE,
censor_point,
prior_only = FALSE,
chains = 4,
iter = 2000,
refresh = 500,
keep_all = FALSE,
slim = FALSE,
drop = NULL,
pars = NULL,
control = NULL,
quiet = FALSE,
...
)
Besag, J. (1974). Spatial interaction and the statistical analysis of lattice systems. Journal of the Royal Statistical Society: Series B (Methodological), 36(2), 192-225.
Besag, J., York, J., and Mollié, A. (1991). Bayesian image restoration, with two applications in spatial statistics. Annals of the Institute of Statistical Mathematics, 43(1), 1-20.
Donegan, Connor and Morris, Mitzi (2021). Flexible functions for ICAR, BYM, and BYM2 models in Stan. Code repository. https://github.com/ConnorDonegan/Stan-IAR
Donegan, Connor (2021b). Building spatial conditional autoregressive (CAR) models in the Stan programming language. OSF Preprints. doi:10.31219/osf.io/3ey65 .
Freni-Sterrantino, Anna, Massimo Ventrucci, and Håvard Rue (2018). A Note on Intrinsic Conditional Autoregressive Models for Disconnected Graphs. Spatial and Spatio-Temporal Epidemiology, 26: 25–34.
Morris, Mitzi (2017). Spatial Models in Stan: Intrinsic Auto-Regressive Models for Areal Data. https://mc-stan.org/users/documentation/case-studies/icar_stan.html
Morris, M., Wheeler-Martin, K., Simpson, D., Mooney, S. J., Gelman, A., & DiMaggio, C. (2019). Bayesian hierarchical spatial models: Implementing the Besag York Mollié model in stan. Spatial and spatio-temporal epidemiology, 31, 100301.
Riebler, A., Sorbye, S. H., Simpson, D., & Rue, H. (2016). An intuitive Bayesian spatial model for disease mapping that accounts for scaling. Statistical Methods in Medical Research, 25(4), 1145-1165.
A model formula, following the R formula syntax. Binomial models can be specified by setting the left hand side of the equation to a data frame of successes and failures, as in cbind(successes, failures) ~ x
.
Formula to specify any spatially-lagged covariates. As in, ~ x1 + x2
(the intercept term will be removed internally). When setting priors for beta
, remember to include priors for any SLX terms.
To include a varying intercept (or "random effects") term, alpha_re
, specify the grouping variable here using formula syntax, as in ~ ID
. Then, alpha_re
is a vector of parameters added to the linear predictor of the model, and:
~ N(0, alpha_tau)
alpha_re ~ Student_t(d.f., location, scale). alpha_tau
Before using this term, read the Details
section and the type
argument. Specifically, if you use type = bym
, then an observational-level re
term is already included in the model. (Similar for type = bym2
.)
A data.frame
or an object coercible to a data frame by as.data.frame
containing the model data.
Spatial connectivity matrix which will be used to construct an edge list for the ICAR model, and to calculate residual spatial autocorrelation as well as any user specified slx
terms. It will automatically be row-standardized before calculating slx
terms (matching the ICAR model). C
must be a binary symmetric n x n
matrix.
The likelihood function for the outcome variable. Current options are binomial(link = "logit")
and poisson(link = "log")
.
Defaults to "icar" (partial pooling of neighboring observations through parameter phi
); specify "bym" to add a second parameter vector theta
to perform partial pooling across all observations; specify "bym2" for the innovation introduced by Riebler et al. (2016). See Details
for more information.
For the BYM2 model, optional. If missing, this will be set to a vector of ones. See Details
.
A named list of parameters for prior distributions (see priors
):
The intercept is assigned a Gaussian prior distribution (see normal
Regression coefficients are assigned Gaussian prior distributions. Variables must follow their order of appearance in the model formula
. Note that if you also use slx
terms (spatially lagged covariates), and you use custom priors for beta
, then you have to provide priors for the slx terms. Since slx terms are prepended to the design matrix, the prior for the slx term will be listed first.
For family = gaussian()
and family = student_t()
models, the scale parameter, sigma
, is assigned a (half-) Student's t prior distribution. The half-Student's t prior for sigma
is constrained to be positive.
nu
is the degrees of freedom parameter in the Student's t likelihood (only used when family = student_t()
). nu
is assigned a gamma prior distribution. The default prior is prior = list(nu = gamma2(alpha = 3, beta = 0.2))
.
The scale parameter for random effects, or varying intercepts, terms. This scale parameter, tau
, is assigned a half-Student's t prior. To set this, use, e.g., prior = list(tau = student_t(df = 20, location = 0, scale = 20))
.
To model observational uncertainty (i.e. measurement or sampling error) in any or all of the covariates, provide a list of data as constructed by the prep_me_data
function.
To center predictors on their mean values, use centerx = TRUE
. If the ME argument is used, the modeled covariate (i.e., latent variable), rather than the raw observations, will be centered. When using the ME argument, this is the recommended method for centering the covariates.
Integer value indicating the maximum censored value; this argument is for modeling censored (suppressed) outcome data, typically disease case counts or deaths. For example, the US Centers for Disease Control and Prevention censors (does not report) death counts that are nine or fewer, so if you're using CDC WONDER mortality data you could provide censor_point = 9
.
Draw samples from the prior distributions of parameters only.
Number of MCMC chains to estimate.
Number of samples per chain. .
Stan will print the progress of the sampler every refresh
number of samples; set refresh=0
to silence this.
If keep_all = TRUE
then samples for all parameters in the Stan model will be kept; this is necessary if you want to do model comparison with Bayes factors and the bridgesampling
package.
If slim = TRUE
, then the Stan model will not collect the most memory-intensive parameters (including n-length vectors of fitted values, log-likelihoods, and ME-modeled covariate values). This will disable many convenience functions that are otherwise available for fitted geostan
models, such as the extraction of residuals, fitted values, and spatial trends, WAIC, and spatial diagnostics, and ME diagnostics; many quantities of interest, such as fitted values and spatial trends, can still be calculated manually using given parameter estimates. The "slim" option is designed for data-intensive routines, such as regression with raster data, Monte Carlo studies, and measurement error models. For more control over which parameters are kept or dropped, use the drop
argument instead of slim
.
Provide a vector of character strings to specify the names of any parameters that you do not want MCMC samples for. Dropping parameters in this way can improve sampling speed and reduce memory usage. The following parameter vectors can potentially be dropped from ICAR models:
The N-length vector of fitted values
Vector of 'random effects'/varying intercepts.
N-length vector of 'latent'/modeled covariate values created for measurement error (ME) models.
The N-length vector of spatially-autocorrelated parameters (with the ICAR prior).
The N-length vector of spatially unstructured parameters ('random effects'), for the BYM and BYM2 models.
If slim = TRUE
, then drop
will be ignored.
Optional; specify any additional parameters you'd like stored from the Stan model.
A named list of parameters to control the sampler's behavior. See stan
for details.
Controls (most) automatic printing to the console. By default, any prior distributions that have not been assigned by the user are printed to the console. If quiet = TRUE
, these will not be printed. Using quiet = TRUE
will also force refresh = 0
.
Other arguments passed to sampling.
An object of class class geostan_fit
(a list) containing:
Summaries of the main parameters of interest; a data frame
Residual spatial autocorrelation as measured by the Moran coefficient.
an object of class stanfit
returned by rstan::stan
a data frame containing the model data
The edge list representing all unique sets of neighbors and the weight attached to each pair (i.e., their corresponding element in the connectivity matrix C
Spatial connectivity matrix
the user-provided or default family
argument used to fit the model
The model formula provided by the user (not including ICAR component)
The slx
formula
A list with two name elements, formula
and Data
, containing the formula re
and a data frame with columns id
(the grouping variable) and idx
(the index values assigned to each group).
Prior specifications.
If covariates are centered internally (centerx = TRUE
), then x_center
is a numeric vector of the values on which covariates were centered.
A data frame with the name of the spatial parameter ("phi"
if type = "icar"
else "convolution"
) and method (toupper(type)
).
The intrinsic conditional autoregressive (ICAR) model for spatial data was introduced by Besag et al. (1991). The Stan code for the ICAR component of the model and the BYM2 option is from Morris et al. (2019) with adjustments to enable non-binary weights and disconnected graph structures (see Freni-Sterrantino (2018) and Donegan (2021)).
The exact specification depends on the type
argument.
For Poisson models for count data, y, the basic model specification (type = "icar"
) is:
$$y ~ Poisson(e^{O + \mu + \phi}) $$ $$\phi \sim ICAR(\tau_s) $$ $$\tau_s \sim Gauss(0, 1)$$
where \(\mu\) contains an intercept and potentially covariates. The spatial trend \(phi\) has a mean of zero and a single scale parameter \(\tau_s\) (which user's will see printed as the parameter named spatial_scale
).
The ICAR prior model is a CAR model that has a spatial autocorrelation parameter \(\rho\) equal to 1 (see stan_car). Thus the ICAR prior places high probability on a very smooth spatially (or temporally) varying mean. This is rarely sufficient to model the amount of variation present in social and health data. For this reason, the BYM model is typically employed.
Often, an observational-level random effect term, theta
, is added to capture (heterogeneous or unstructured) deviations from \(\mu + \phi\). The combined term is referred to as a convolution term:
\( convolution = \phi + \theta. \)
This is known as the BYM model (Besag et al. 1991), and can be specified using type = "bym"
:
\(y \sim Poisson(e^{O + \mu + \phi + \theta}) \) $$ \phi \sim ICAR(\tau_s) $$ $$ \theta \sim Gaussian(0, \tau_{ns}) $$ $$ \tau_s \sim Gaussian(0, 1) $$ $$ \tau_{ns} \sim Gaussian(0, 1) $$
The model is named after Besag, York, and Mollié (1991).
Riebler et al. (2016) introduce a variation on the BYM model (type = "bym2"
). This specification combines \(\phi\) and \(\theta\) using a mixing parameter \(\rho\) that controls the proportion of the variation that is attributable to the spatially autocorrelated term \(\phi\) rather than the spatially unstructured term \(\theta\). The terms share a single scale parameter \(\tau\):
$$convolution = [sqrt(\rho * S) * \tilde{\phi} + sqrt(1 - \rho) \tilde{\theta}] * \tau $$ $$ \tilde{\phi} \sim Gaussian(0, 1) $$ $$ \tilde{\theta} \sim Gaussian(0, 1) $$ $$ \tau \sim Gaussian(0, 1) $$
The terms \(\tilde{\phi}\), \(\tilde{\theta}\) are standard normal deviates, \(\rho\) is restricted to values between zero and one, and \(S\) is the 'scale_factor' (a constant term provided by the user). By default, the 'scale_factor' is equal to one, so that it does nothing. Riebler et al. (2016) argue that the interpretation or meaning of the scale of the ICAR model depends on the graph structure of the connectivity matrix \(C\). This implies that the same prior distribution assigned to \(\tau_s\) will differ in its implications if \(C\) is changed; in other words, the priors are not transportable across models, and models that use the same nominal prior actually have different priors assigned to \(\tau_s\).
Borrowing R
code from Morris (2017) and following Freni-Sterrantino et al. (2018), the following R
code can be used to create the 'scale_factor' \(S\) for the BYM2 model (note, this requires the INLA R package), given a spatial adjacency matrix, \(C\):
## create a list of data for stan_icar
geostan::prep_icar_data(C)
icar.data <-## calculate scale_factor for each of k connected group of nodes
icar.data$k
k <- vector(mode = "numeric", length = k)
scale_factor <-for (j in 1:k) {
which(icar.data$comp_id == j)
g.idx <-if (length(g.idx) == 1) {
1
scale_factor[j] <-next
} C[g.idx, g.idx]
Cg <- scale_c(Cg)
scale_factor[j] <- }
This code adjusts for 'islands' or areas with zero neighbors, and it also handles disconnected graph structures (see Donegan and Morris 2021). Following Freni-Sterrantino (2018), disconnected components of the graph structure are given their own intercept term; however, this value is added to \(\phi\) automatically inside the Stan model. Therefore, the user never needs to make any adjustments for this term. (To avoid complications from using a disconnected graph structure, you can apply a proper CAR model instead of the ICAR: stan_car
).
Note, the code above requires the scale_c
function; it has package dependencies that are not included in geostan
. To use scale_c
, you have to load the following R
function:
#' compute scaling factor for adjacency matrix, accounting for differences in spatial connectivity
#'
#' @param C connectivity matrix
#'
#' @details
#'
#' Requires the following packages:
#'
#' library(Matrix)
#' library(INLA);
#' library(spdep)
#' library(igraph)
#'
#' @source Morris (2017)
#'
function(C) {
scale_c <- function(x) exp(mean(log(x)))
geometric_mean <- dim(C)[1]
N = Diagonal(N, rowSums(C)) - C
Q = Q + Diagonal(N) * max(diag(Q)) * sqrt(.Machine$double.eps)
Q_pert = inla.qinv(Q_pert, constr=list(A = matrix(1,1,N),e=0))
Q_inv = geometric_mean(Matrix::diag(Q_inv))
scaling_factor <-return(scaling_factor)
}
The CAR models can also incorporate spatially-lagged covariates, measurement/sampling error in covariates (particularly when using small area survey estimates as covariates), missing outcome data, and censored outcomes (such as arise when a disease surveillance system suppresses data for privacy reasons). For details on these options, please see the Details section in the documentation for stan_glm.
# \donttest{
data(sentencing)
C <- shape2mat(sentencing, "B")
log_e <- log(sentencing$expected_sents)
fit.bym <- stan_icar(sents ~ offset(log_e),
family = poisson(),
data = sentencing,
type = "bym",
C = C,
chains = 2, iter = 800) # for speed only
# spatial diagnostics
sp_diag(fit.bym, sentencing)
# check effective sample size and convergence
library(rstan)
rstan::stan_ess(fit.bym$stanfit)
rstan::stan_rhat(fit.bym$stanfit)
# calculate log-standardized incidence ratios
# (observed/exected case counts)
library(ggplot2)
library(sf)
f <- fitted(fit.bym, rates = FALSE)$mean
SSR <- f / sentencing$expected_sents
log.SSR <- log( SSR, base = 2)
ggplot(sentencing) +
geom_sf(aes(fill = log.SSR)) +
scale_fill_gradient2(
low = "navy",
high = "darkred"
) +
labs(title = "Log-standardized incidence ratios",
subtitle = "log( Fitted/Expected), base 2") +
theme_void() +
theme(
legend.position = "bottom",
legend.key.height = unit(0.35, "cm"),
legend.key.width = unit(1.5, "cm")
)
# }