# Function for Fitting Latent Factor Multi-Species Occupancy Models

`lfMsPGOcc.Rd`

Function for fitting multi-species occupancy models with species correlations (i.e., a joint species distribution model with imperfect detection). We use Polya-gamma latent variables and a factor modeling approach for dimension reduction.

## Usage

```
lfMsPGOcc(occ.formula, det.formula, data, inits, priors, n.factors,
n.samples, n.omp.threads = 1, verbose = TRUE, n.report = 100,
n.burn = round(.10 * n.samples), n.thin = 1, n.chains = 1,
k.fold, k.fold.threads = 1, k.fold.seed, ...)
```

## Arguments

- occ.formula
a symbolic description of the model to be fit for the occurrence portion of the model using R's model syntax. Only right-hand side of formula is specified. See example below. Random intercepts are allowed using lme4 syntax (Bates et al. 2015).

- det.formula
a symbolic description of the model to be fit for the detection portion of the model using R's model syntax. Only right-hand side of formula is specified. See example below. Random intercepts are allowed using lme4 syntax (Bates et al. 2015).

- data
a list containing data necessary for model fitting. Valid tags are

`y`

,`occ.covs`

,`det.covs`

, and`coords`

.`y`

is a three-dimensional array with first dimension equal to the number of species, second dimension equal to the number of sites, and third dimension equal to the maximum number of replicates at a given site.`occ.covs`

is a matrix or data frame containing the variables used in the occurrence portion of the model, with \(J\) rows for each column (variable).`det.covs`

is a list of variables included in the detection portion of the model. Each list element is a different detection covariate, which can be site-level or observational-level. Site-level covariates are specified as a vector of length \(J\) while observation-level covariates are specified as a matrix or data frame with the number of rows equal to \(J\) and number of columns equal to the maximum number of replicates at a given site.`coords`

is a matrix or data frame with two columns that contain the spatial coordinates of each site. Note that`spOccupancy`

assumes coordinates are specified in a projected coordinate system.- inits
a list with each tag corresponding to a parameter name. Valid tags are

`alpha.comm`

,`beta.comm`

,`beta`

,`alpha`

,`tau.sq.beta`

,`tau.sq.alpha`

,`lambda`

,`sigma.sq.psi`

,`sigma.sq.p`

,`z`

. The value portion of each tag is the parameter's initial value. See`priors`

description for definition of each parameter name. Additionally, the tag`fix`

can be set to`TRUE`

to fix the starting values across all chains. If`fix`

is not specified (the default), starting values are varied randomly across chains.- priors
a list with each tag corresponding to a parameter name. Valid tags are

`beta.comm.normal`

,`alpha.comm.normal`

,`tau.sq.beta.ig`

,`tau.sq.alpha.ig`

,`sigma.sq.psi.ig`

, and`sigma.sq.p.ig`

. Community-level occurrence (`beta.comm`

) and detection (`alpha.comm`

) regression coefficients are assumed to follow a normal distribution. The hyperparameters of the normal distribution are passed as a list of length two with the first and second elements corresponding to the mean and variance of the normal distribution, which are each specified as vectors of length equal to the number of coefficients to be estimated or of length one if priors are the same for all coefficients. If not specified, prior means are set to 0 and prior variances set to 2.72. Community-level variance parameters for occurrence (`tau.sq.beta`

) and detection (`tau.sq.alpha`

) are assumed to follow an inverse Gamma distribution. The hyperparameters of the inverse gamma distribution are passed as a list of length two with the first and second elements corresponding to the shape and scale parameters, which are each specified as vectors of length equal to the number of coefficients to be estimated or a single value if all parameters are assigned the same prior. If not specified, prior shape and scale parameters are set to 0.1. The factor model fits`n.factors`

independent latent factors. The priors for the factor loadings matrix`lambda`

are fixed following standard approaches to ensure parameter identifiability. The upper triangular elements of the`N x n.factors`

matrix are fixed at 0 and the diagonal elements are fixed at 1. The lower triangular elements are assigned a standard normal prior (i.e., mean 0 and variance 1).`sigma.sq.psi`

and`sigma.sq.p`

are the random effect variances for any occurrence or detection random effects, respectively, and are assumed to follow an inverse Gamma distribution. The hyperparameters of the inverse-Gamma distribution are passed as a list of length two with first and second elements corresponding to the shape and scale parameters, respectively, which are each specified as vectors of length equal to the number of random intercepts or of length one if priors are the same for all random effect variances.- n.factors
the number of factors to use in the latent factor model approach. Typically, the number of factors is set to be small (e.g., 4-5) relative to the total number of species in the community, which will lead to substantial decreases in computation time. However, the value can be anywhere between 1 and N (the number of species in the community).

- n.samples
the number of posterior samples to collect in each chain.

- n.omp.threads
a positive integer indicating the number of threads to use for SMP parallel processing. The package must be compiled for OpenMP support. For most Intel-based machines, we recommend setting

`n.omp.threads`

up to the number of hypterthreaded cores. Note,`n.omp.threads`

> 1 might not work on some systems.- verbose
if

`TRUE`

, messages about data preparation, model specification, and progress of the sampler are printed to the screen. Otherwise, no messages are printed.- n.report
the interval to report MCMC progress.

- n.burn
the number of samples out of the total

`n.samples`

to discard as burn-in for each chain. By default, the first 10% of samples is discarded.- n.thin
the thinning interval for collection of MCMC samples. The thinning occurs after the

`n.burn`

samples are discarded. Default value is set to 1.- n.chains
the number of chains to run in sequence.

- k.fold
specifies the number of

*k*folds for cross-validation. If not specified as an argument, then cross-validation is not performed and`k.fold.threads`

and`k.fold.seed`

are ignored. In*k*-fold cross-validation, the data specified in`data`

is randomly partitioned into*k*equal sized subsamples. Of the*k*subsamples,*k*- 1 subsamples are used to fit the model and the remaining*k*samples are used for prediction. The cross-validation process is repeated*k*times (the folds). As a scoring rule, we use the model deviance as described in Hooten and Hobbs (2015). Cross-validation is performed after the full model is fit using all the data. Cross-validation results are reported in the`k.fold.deviance`

object in the return list.- k.fold.threads
number of threads to use for cross-validation. If

`k.fold.threads > 1`

parallel processing is accomplished using the foreach and doParallel packages. Ignored if`k.fold`

is not specified.- k.fold.seed
seed used to split data set into

`k.fold`

parts for k-fold cross-validation. Ignored if`k.fold`

is not specified.- ...
currently no additional arguments

## Note

Some of the underlying code used for generating random numbers from the Polya-Gamma distribution is taken from the pgdraw package written by Daniel F. Schmidt and Enes Makalic. Their code implements Algorithm 6 in PhD thesis of Jesse Bennett Windle (2013) https://repositories.lib.utexas.edu/handle/2152/21842.

## References

Polson, N.G., J.G. Scott, and J. Windle. (2013) Bayesian Inference for
Logistic Models Using Polya-Gamma Latent Variables.
*Journal of the American Statistical Association*, 108:1339-1349.

Bates, Douglas, Martin Maechler, Ben Bolker, Steve Walker (2015). Fitting Linear Mixed-Effects Models Using lme4. Journal of Statistical Software, 67(1), 1-48. doi:10.18637/jss.v067.i01 .

Hooten, M. B., and Hobbs, N. T. (2015). A guide to Bayesian model selection for ecologists. Ecological monographs, 85(1), 3-28.

Dorazio, R. M., and Royle, J. A. (2005). Estimating size and composition of biological communities by modeling the occurrence of species. Journal of the American Statistical Association, 100(470), 389-398.

## Author

Jeffrey W. Doser doserjef@msu.edu,

Andrew O. Finley finleya@msu.edu

## Value

An object of class `lfMsPGOcc`

that is a list comprised of:

- beta.comm.samples
a

`coda`

object of posterior samples for the community level occurrence regression coefficients.- alpha.comm.samples
a

`coda`

object of posterior samples for the community level detection regression coefficients.- tau.sq.beta.samples
a

`coda`

object of posterior samples for the occurrence community variance parameters.- tau.sq.alpha.samples
a

`coda`

object of posterior samples for the detection community variance parameters.- beta.samples
a

`coda`

object of posterior samples for the species level occurrence regression coefficients.- alpha.samples
a

`coda`

object of posterior samples for the species level detection regression coefficients.- lambda.samples
a

`coda`

object of posterior samples for the latent factor loadings.- z.samples
a three-dimensional array of posterior samples for the latent occurrence values for each species.

- psi.samples
a three-dimensional array of posterior samples for the latent occurrence probability values for each species.

- sigma.sq.psi.samples
a

`coda`

object of posterior samples for variances of random intercepts included in the occurrence portion of the model. Only included if random intercepts are specified in`occ.formula`

.- sigma.sq.p.samples
a

`coda`

object of posterior samples for variances of random intercepts included in the detection portion of the model. Only included if random intercepts are specified in`det.formula`

.- w.samples
a three-dimensional array of posterior samples for the latent effects for each latent factor.

- beta.star.samples
a

`coda`

object of posterior samples for the occurrence random effects. Only included if random intercepts are specified in`occ.formula`

.- alpha.star.samples
a

`coda`

object of posterior samples for the detection random effects. Only included if random intercepts are specified in`det.formula`

.- like.samples
a three-dimensional array of posterior samples for the likelihood value associated with each site and species. Used for calculating WAIC.

- rhat
a list of Gelman-Rubin diagnostic values for some of the model parameters.

- ESS
a list of effective sample sizes for some of the model parameters.

- run.time
MCMC sampler execution time reported using

`proc.time()`

.- k.fold.deviance
vector of scoring rules (deviance) from k-fold cross-validation. A separate value is reported for each species. Only included if

`k.fold`

is specified in function call.

The return object will include additional objects used for
subsequent prediction and/or model fit evaluation. Note that detection
probability estimated values are not included in the model object, but can
be extracted using `fitted()`

.

## Examples

```
set.seed(400)
J.x <- 8
J.y <- 8
J <- J.x * J.y
n.rep<- sample(2:4, size = J, replace = TRUE)
N <- 8
# Community-level covariate effects
# Occurrence
beta.mean <- c(0.2, 0.5)
p.occ <- length(beta.mean)
tau.sq.beta <- c(0.6, 0.3)
# Detection
alpha.mean <- c(0.5, 0.2, -0.1)
tau.sq.alpha <- c(0.2, 0.3, 1)
p.det <- length(alpha.mean)
# Draw species-level effects from community means.
beta <- matrix(NA, nrow = N, ncol = p.occ)
alpha <- matrix(NA, nrow = N, ncol = p.det)
p.RE <- list()
# Include a random intercept on detection
p.RE <- list(levels = c(40),
sigma.sq.p = c(2))
for (i in 1:p.occ) {
beta[, i] <- rnorm(N, beta.mean[i], sqrt(tau.sq.beta[i]))
}
for (i in 1:p.det) {
alpha[, i] <- rnorm(N, alpha.mean[i], sqrt(tau.sq.alpha[i]))
}
n.factors <- 4
dat <- simMsOcc(J.x = J.x, J.y = J.y, n.rep = n.rep, N = N, beta = beta, alpha = alpha,
sp = FALSE, factor.model = TRUE, n.factors = n.factors, p.RE = p.RE)
y <- dat$y
X <- dat$X
X.p <- dat$X.p
X.p.re <- dat$X.p.re
# Package all data into a list
occ.covs <- X[, 2, drop = FALSE]
colnames(occ.covs) <- c('occ.cov')
det.covs <- list(det.cov.1 = X.p[, , 2],
det.cov.2 = X.p[, , 3],
det.re = X.p.re[, , 1])
data.list <- list(y = y,
occ.covs = occ.covs,
det.covs = det.covs,
coords = dat$coords)
# Occupancy initial values
prior.list <- list(beta.comm.normal = list(mean = 0, var = 2.72),
alpha.comm.normal = list(mean = 0, var = 2.72),
tau.sq.beta.ig = list(a = 0.1, b = 0.1),
tau.sq.alpha.ig = list(a = 0.1, b = 0.1))
# Initial values
lambda.inits <- matrix(0, N, n.factors)
diag(lambda.inits) <- 1
lambda.inits[lower.tri(lambda.inits)] <- rnorm(sum(lower.tri(lambda.inits)))
inits.list <- list(alpha.comm = 0,
beta.comm = 0,
beta = 0,
alpha = 0,
tau.sq.beta = 1,
tau.sq.alpha = 1,
lambda = lambda.inits,
z = apply(y, c(1, 2), max, na.rm = TRUE))
n.samples <- 3000
n.burn <- 2000
n.thin <- 1
out <- lfMsPGOcc(occ.formula = ~ occ.cov,
det.formula = ~ det.cov.1 + det.cov.2 + (1 | det.re),
data = data.list,
inits = inits.list,
n.samples = n.samples,
priors = prior.list,
n.factors = n.factors,
n.omp.threads = 1,
verbose = TRUE,
n.report = 1000,
n.burn = n.burn,
n.thin = n.thin,
n.chains = 1)
#> ----------------------------------------
#> Preparing to run the model
#> ----------------------------------------
#> No prior specified for sigma.sq.p.ig.
#> Setting prior shape to 0.1 and prior scale to 0.1
#> sigma.sq.p is not specified in initial values.
#> Setting initial values to random values between 0.5 and 10
#> ----------------------------------------
#> Model description
#> ----------------------------------------
#> Latent Factor Multispecies Occupancy Model with Polya-Gamma latent
#> variable fit with 64 sites and 8 species.
#>
#> Samples per Chain: 3000
#> Burn-in: 2000
#> Thinning Rate: 1
#> Number of Chains: 1
#> Total Posterior Samples: 1000
#>
#> Using 4 latent factors.
#>
#> Source compiled with OpenMP support and model fit using 1 thread(s).
#>
#> ----------------------------------------
#> Chain 1
#> ----------------------------------------
#> Sampling ...
#> Sampled: 1000 of 3000, 33.33%
#> -------------------------------------------------
#> Sampled: 2000 of 3000, 66.67%
#> -------------------------------------------------
#> Sampled: 3000 of 3000, 100.00%
summary(out, level = 'community')
#>
#> Call:
#> lfMsPGOcc(occ.formula = ~occ.cov, det.formula = ~det.cov.1 +
#> det.cov.2 + (1 | det.re), data = data.list, inits = inits.list,
#> priors = prior.list, n.factors = n.factors, n.samples = n.samples,
#> n.omp.threads = 1, verbose = TRUE, n.report = 1000, n.burn = n.burn,
#> n.thin = n.thin, n.chains = 1)
#>
#> Samples per Chain: 3000
#> Burn-in: 2000
#> Thinning Rate: 1
#> Number of Chains: 1
#> Total Posterior Samples: 1000
#> Run Time (min): 0.0704
#>
#> ----------------------------------------
#> Community Level
#> ----------------------------------------
#> Occurrence Means (logit scale):
#> Mean SD 2.5% 50% 97.5% Rhat ESS
#> (Intercept) 0.1321 0.2787 -0.4235 0.1369 0.6762 NA 307
#> occ.cov 0.1415 0.2123 -0.2643 0.1395 0.5791 NA 275
#>
#> Occurrence Variances (logit scale):
#> Mean SD 2.5% 50% 97.5% Rhat ESS
#> (Intercept) 0.5201 0.4426 0.0778 0.3939 1.8161 NA 233
#> occ.cov 0.1958 0.1785 0.0346 0.1374 0.6871 NA 341
#>
#> Detection Means (logit scale):
#> Mean SD 2.5% 50% 97.5% Rhat ESS
#> (Intercept) 0.3514 0.1775 0.0135 0.3532 0.6816 NA 222
#> det.cov.1 0.0636 0.2306 -0.3706 0.0713 0.5148 NA 593
#> det.cov.2 0.1212 0.3670 -0.6382 0.1251 0.8182 NA 827
#>
#> Detection Variances (logit scale):
#> Mean SD 2.5% 50% 97.5% Rhat ESS
#> (Intercept) 0.1410 0.1347 0.0265 0.1016 0.4886 NA 279
#> det.cov.1 0.3634 0.3597 0.0681 0.2778 1.2567 NA 351
#> det.cov.2 1.0667 0.8661 0.2960 0.8365 3.2372 NA 633
#>
#> Detection Random Effect Variances (logit scale):
#> Mean SD 2.5% 50% 97.5% Rhat ESS
#> det.re 1.0045 0.3607 0.3238 0.9882 1.7133 NA 24
```