communityModel: Create a community (multi-species) occupancy model for JAGS...

View source: R/communityModel.R

communityModelR Documentation

Create a community (multi-species) occupancy model for JAGS or Nimble

Description

Flexibly creates complete code and input data for community occupancy models for JAGS amd Nimble (both standard occupancy models and Royle-Nichols occupancy models), and automatically sets initial values and parameters to monitor. Supports fixed and random effects of covariates on detection and occupancy probabilities, using both continuous and categorical covariates (both site and site-occasion covariates).

Optionally includes data augmentation (fully open community, or up to known maximum number of species, or no data augmentation). Allows combination of all these parameters for fast and flexible customization of community occupancy models.

Incidentally, the function can also be used to create model code and input for single-species single-season occupancy models (it is the special case of the community model with only one species). Such a model will run slower than proper single-species model JAGS code due to the additional species loop, but it is possible.

The function returns several derived quantities, e.g. species richness, Bayesian p-values (overall and by species), Freeman-Tukey residuals for actual and simulated data (by station and total). If doing data augmentation, metacommunity size and number of unseen species are returned also.

Usage

communityModel(
  data_list,
  model = c("Occupancy", "RN"),
  occuCovs = list(fixed = NULL, independent = NULL, ranef = NULL),
  detCovs = list(fixed = NULL, ranef = NULL),
  detCovsObservation = list(fixed = NULL, ranef = NULL),
  speciesSiteRandomEffect = list(det = FALSE, occu = FALSE),
  intercepts = list(det = "fixed", occu = "fixed"),
  effortCov = "effort",
  richnessCategories = NULL,
  augmentation = NULL,
  modelFile = NULL,
  nimble = FALSE,
  keyword_quadratic = "_squared"
)

Arguments

data_list

list. Contains 3 slots: ylist, siteCovs, obsCovs. ylist is a list of detection histories (can be named), e.g. from detectionHistory. siteCovs is a data.frame with site covariates (optional). obsCovs is a list of site-occasion level covariates (e.g. site-occasion-specific effort, which is also returned by detectionHistory.

model

character. "Occupancy" for standard occupancy model, or "RN" for the occupancy model of Royle and Nichols (2003), which relates probability of detection of the species to the number of individuals available for detection at each station

occuCovs

list. Up to 3 items named "fixed", "independent", and/or "ranef". Specifies fixed, independent or random effects of covariates on occupancy probability (continuous or categorical covariates). Independent effects are only supported for continuous covariates.

detCovs

list. Up to 3 items named "fixed", "independent", and/or "ranef". Specifies fixed, independent or random effects of covariates on detection probability (continuous or categorical covariates). Independent effects are only supported for continuous covariates.

detCovsObservation

list. Up to 2 items named "fixed" and/or "ranef". Specifies fixed or random effects of observation-level covariates on detection probability (continuous or categorical covariates - categorical must be coded as character matrix)

speciesSiteRandomEffect

list. Two items named "det" and "occu". If TRUE, adds a random effect of species and station. Only implemented for detection probability.

intercepts

list. Two items named "det" and "occu" for detection and occupancy probability intercepts. Values can be "fixed" (= constant across species), "independent" (= independent estimates for each species), or "ranef" (= random effect of species on intercept).

effortCov

character. Name of list item in data_list$obsCovs which contains effort. This does not include effort as a covariate on detection probability, but only uses NA / not NA information to create binary effort and ensure detection probabilities p are 0 when there was no effort (p will be 0 whereever effortCov is NA).

richnessCategories

character. Name of categorical covariate in data_list$siteCovs for which to calculate separate richness estimates (optional). Can be useful to obtain separate richness estimates for different areas.

augmentation

If NULL, no data augmentation (only use species in data_list$ylist), otherwise named list or vector with total number of (potential) species. Names: "maxknown" or "full". Example: augmentation = c(maxknown = 30) or augmentation = c(full = 30)

modelFile

character. Text file name to save model to

nimble

logical. If TRUE, model code will be for Nimble (incompatible with JAGS). If FALSE, model code is for JAGS.

keyword_quadratic

character. A suffix in covariate names in the model that indicates a covariate is a quadratic effect of another covariate which does not carry the suffix in its name (e.g. if the covariate is "elevation", the quadratic covariate would be "elevation_squared").

Details

For examples of implementation, see Vignette 5: Multi-species occupancy models.

Fixed effects of covariates are constant across species, whereas random effect covariates differ between species. Independent effect differ between species and are independent (there is no underlying hyperdistribution). Fixed, independent and random effects are allowed for station-level detection and occupancy covariates (a.k.a. site covariates). Fixed and random effects are also allowed for station-occasion level covariates (a.k.a. observation covariates). Currently independent effects are only supported for continuous site covariates, not categorical site covariates or observation-level covariates.

By default, random effects will be by species. It is however possible to use categorical site covariates for grouping (continuous|categorical). Furthermore, is is possible to use use nested random effects of species and another categorical site covariate (so that there is a random effect of species and an additional random effect of a categorical covariate within each species).

Derived quantities returned by the model are:

Bpvalue Bayesian p-value (overall)
Bpvalue_species Bayesian p-value (by species)
Nspecies Species richness (only in JAGS models)
Nspecies_station Species richness at each sampling locations (only in JAGS models)
Nspecies_Covariate Species richness by categorical covariate (when using richnessCategories, only in JAGS models)
R2 sum of Freeman-Tukey residuals of observed data within each species
new.R2 sum of Freeman-Tukey residuals of simulated data within each species
R3 Total sum of Freeman-Tukey residuals of observed data
new.R3 Total sum of Freeman-Tukey residuals of simulated data
Ntotal Total metacommunity size (= observed species + n0)
n0 Number of unseen species in metacommunity
omega Data augmentation parameter
w Metacommunity membership indicator for each species

Quantities in italic at the bottom are only returned in full data augmentation. Nspecies and Nspecies_Covariate are only returned in JAGS models (because Nimble models don't explicitly return latent occupancy status z).

Value

commOccu object. It is an S4 class containing all information required to run the models. See commOccu-class for details.

Parameter naming convention

The parameter names are assembled from building blocks. The nomenclature is as follows:

Name Refers to Description
alpha Submodel detection submodel
beta Submodel occupancy submode
0 Intercept denotes the intercepts (alpha0, beta0)
fixed Effect type fixed effects (constant across species)
indep Effect type independent effects (separate for each species)
ranef Effect type random effects (of species and/or other categorical covariates)
cont Covariate type continuous covariates
categ Covariate type categorical covariates
mean Hyperparameter mean of random effect
sigma Hyperparameter standard deviation of random effect
tau Hyperparameter precision of random effect (used internally, not returned)

For example, a fixed intercept of occupancy (constant across species) is beta0, and a fixed intercept of detection probability is alpha0.

An occupancy probability intercept with a random effect of species is:

beta0.mean community mean of the occupancy probability intercept

beta0.sigma standard deviation of the community occupancy probability intercept.

beta0[1] occupancy probability intercept of species 1 (likewise for other species).

For effects of site covariates, the pattern is:

submodel.effectType.covariateType.CovariateName.hyperparameter

For example:

beta.ranef.cont.habitat.mean is the mean community effect of the continuous site covariate 'habitat' on occupancy probability.

beta.ranef.cont.habitat[1] is the effect of continuous site covariate 'habitat' on occupancy probability of species 1.

Site-occasion covariates are denoted by ".obs" after the submodel, e.g.:

alpha.obs.fixed.cont.effort is the fixed effect of the continuous observation-level covariate 'effort' on detection probability

Author(s)

Juergen Niedballa

References

Kéry, M., and J. A. Royle. "Applied hierarchical modelling in ecology - Modeling distribution, abundance and species richness using R and BUGS." Volume 1: Prelude and Static Models. Elsevier/Academic Press, 2016.

Examples


## Not run: 

data("camtraps")

# create camera operation matrix
camop_no_problem <- cameraOperation(CTtable      = camtraps,
                                    stationCol   = "Station",
                                    setupCol     = "Setup_date",
                                    retrievalCol = "Retrieval_date",
                                    hasProblems  = FALSE,
                                    dateFormat   = "dmy"
)

data("recordTableSample")

# make list of detection histories
DetHist_list <- lapply(unique(recordTableSample$Species), FUN = function(x) {
  detectionHistory(
    recordTable         = recordTableSample,
    camOp                = camop_no_problem,
    stationCol           = "Station",
    speciesCol           = "Species",
    recordDateTimeCol    = "DateTimeOriginal",
    species              = x,
    occasionLength       = 7,
    day1                 = "station",
    datesAsOccasionNames = FALSE,
    includeEffort        = TRUE,
    scaleEffort          = TRUE,
    timeZone             = "Asia/Kuala_Lumpur"
  )}
)

# assign species names to list items
names(DetHist_list) <- unique(recordTableSample$Species)

# extract detection histories (omit effort matrices)
ylist <- lapply(DetHist_list, FUN = function(x) x$detection_history)

# create some fake covariates for demonstration
sitecovs <- camtraps[, c(1:3)]
sitecovs$elevation <- c(300, 500, 600)   

# scale numeric covariates
sitecovs[, c(2:4)] <- scale(sitecovs[,-1])


# bundle input data for communityModel
data_list <- list(ylist = ylist,
                  siteCovs = sitecovs,
                  obsCovs = list(effort = DetHist_list[[1]]$effort))


# create community model for JAGS
modelfile1 <- tempfile(fileext = ".txt")
mod.jags <- communityModel(data_list,
                           occuCovs = list(fixed = "utm_y", ranef = "elevation"),
                           detCovsObservation = list(fixed = "effort"),
                           intercepts = list(det = "ranef", occu = "ranef"),
                           modelFile = modelfile1)

summary(mod.jags)

# fit in JAGS
fit.jags <- fit(mod.jags,
                n.iter = 1000,
                n.burnin = 500,
                chains = 3)   
summary(fit.jags)

# response curves (= marginal effect plots)
plot_effects(mod.jags, 
             fit.jags, 
             submodel = "state")
plot_effects(mod.jags, 
             fit.jags, 
             submodel = "det")
             
# effect sizes plot
plot_coef(mod.jags, 
          fit.jags, 
          submodel = "state")
plot_coef(mod.jags, 
          fit.jags, 
          submodel = "det")              

# create community model for Nimble
modelfile2 <- tempfile(fileext = ".txt")
mod.nimble <- communityModel(data_list,
                             occuCovs = list(fixed = "utm_x", ranef = "utm_y"),
                             detCovsObservation = list(fixed = "effort"),
                             intercepts = list(det = "ranef", occu = "ranef"),
                             modelFile = modelfile2, 
                             nimble = TRUE)      # set nimble = TRUE

# load nimbleEcology package 
# currently necessary to do explicitly, to avoid additional package dependencies
require(nimbleEcology)

# fit uncompiled model in Nimble
fit.nimble.uncomp <- fit(mod.nimble, 
                         n.iter = 10, 
                         chains = 1)

# fit compiled model in Nimble
fit.nimble.comp <- fit(mod.nimble, 
                       n.iter = 5000, 
                       n.burnin = 2500,
                       chains = 3, 
                       compile = TRUE)

# parameter summary statistics
summary(fit.nimble.comp)


# response curves (= marginal effect plots)
plot_effects(mod.nimble, 
             fit.nimble.comp, 
             submodel = "state")
plot_effects(mod.nimble, 
             fit.nimble.comp, 
             submodel = "det")

# effect sizes plot
plot_coef(mod.nimble, 
          fit.nimble.comp, 
          submodel = "state")
plot_coef(mod.nimble, 
          fit.nimble.comp, 
          submodel = "det")   

# traceplots
plot(fit.nimble.comp)



## End(Not run)


camtrapR documentation built on May 29, 2024, 6:45 a.m.