% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/communityModel.R
\encoding{UTF-8}
\name{communityModel}
\alias{communityModel}
\title{Create a community (multi-species) occupancy model for JAGS or Nimble}
\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 = "ranef", occu = "ranef"),
  effortCov = "effort",
  richnessCategories = NULL,
  augmentation = NULL,
  modelFile = NULL,
  nimble = FALSE,
  keyword_quadratic = "_squared"
)
}
\arguments{
\item{data_list}{list. Contains 3 slots: ylist, siteCovs, obsCovs. ylist is a list of detection histories (can be named), e.g. from \code{\link{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 \code{\link{detectionHistory}}.}

\item{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}

\item{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.}

\item{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.}

\item{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)}

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

\item{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).}

\item{effortCov}{character. Name of list item in \code{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 \code{effortCov} is NA).}

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

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

\item{modelFile}{character. Text file name to save model to}

\item{nimble}{logical. If TRUE, model code will be for Nimble (incompatible with JAGS). If FALSE, model code is for JAGS.}

\item{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").}
}
\value{
\code{commOccu} object. It is an S4 class containing all information required to run the models. See  \code{\link{commOccu-class}} for details.
}
\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.
}
\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:
  
  \tabular{ll}{
    \code{Bpvalue} \tab Bayesian p-value (overall) \cr
    \code{Bpvalue_species} \tab Bayesian p-value (by species) \cr
    
    
    \code{Nspecies} \tab Species richness (only in JAGS models)\cr
    \code{Nspecies_station} \tab Species richness at each sampling locations (only in JAGS models) \cr
    \code{Nspecies_Covariate} \tab Species richness by categorical covariate (when using \code{richnessCategories}, only in JAGS models) \cr
    
    
    \code{R2} \tab sum of Freeman-Tukey residuals of observed data within each species \cr
    \code{new.R2} \tab sum of Freeman-Tukey residuals of simulated data within each species \cr
    \code{R3} \tab Total sum of Freeman-Tukey residuals of observed data \cr 
    \code{new.R3} \tab Total sum of Freeman-Tukey residuals of simulated data \cr
    \emph{\code{Ntotal}} \tab Total metacommunity size (= observed species + n0) \cr
    \emph{\code{n0}} \tab Number of unseen species in metacommunity \cr
    \emph{\code{omega}} \tab Data augmentation parameter \cr
    \emph{\code{w}} \tab Metacommunity membership indicator for each species
  }

Quantities in \emph{italic} at the bottom are only returned in full data augmentation. \code{Nspecies} and \code{Nspecies_Covariate} are only returned in JAGS models (because Nimble models don't explicitly return latent occupancy status z).
}
\section{Parameter naming convention}{
 
The parameter names are assembled from building blocks. The nomenclature  is as follows:    
  \tabular{lll}{
    \bold{Name}           \tab \bold{Refers to}  \tab  \bold{Description}  \cr
    \bold{\code{alpha}}   \tab Submodel          \tab detection submodel  \cr
    \bold{\code{beta}}    \tab Submodel          \tab occupancy submode \cr
    \bold{\code{0}}       \tab Intercept         \tab denotes the intercepts (alpha0, beta0)  \cr
    \bold{\code{fixed}}   \tab Effect type       \tab fixed effects (constant across species)  \cr
    \bold{\code{indep}}   \tab Effect type       \tab independent effects (separate for each species)  \cr
    \bold{\code{ranef}}   \tab Effect type       \tab random effects (of species and/or other categorical covariates)  \cr
    \bold{\code{cont}}    \tab Covariate type    \tab continuous covariates \cr
    \bold{\code{categ}}   \tab Covariate type    \tab categorical covariates \cr
    \bold{\code{mean}}    \tab Hyperparameter    \tab mean of random effect \cr
    \bold{\code{sigma}}   \tab Hyperparameter    \tab standard deviation of random effect \cr
    \bold{\code{tau}}     \tab Hyperparameter    \tab precision of random effect (used internally, not returned)
  }


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


An occupancy probability intercept with a random effect of species is: 
  
\bold{\code{beta0.mean}} community mean of the occupancy probability intercept

\bold{\code{beta0.sigma}} standard deviation of the community occupancy probability intercept.

\bold{\code{beta0[1]}} occupancy probability intercept of species 1 (likewise for other species). 


For effects of site covariates, the pattern is:
  
\code{submodel.effectType.covariateType.CovariateName.hyperparameter}

For example:
  
\bold{\code{beta.ranef.cont.habitat.mean}} is the mean community effect of the continuous site covariate 'habitat' on occupancy probability.

\bold{\code{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.: 
  
\bold{\code{alpha.obs.fixed.cont.effort}} is the fixed effect of the continuous observation-level covariate 'effort' on detection probability
}

\examples{

\dontrun{
# the example below fits community occupancy models to the sample data in camtrapR
# models are fit both in JAGS and Nimble
# The data set only contains 5 species and 3 stations, so the results will be nonsense. 
# It is only a technical demonstration with the camtrapR workflow
# for more complete examples, see vignette 5

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
species_to_include <- unique(recordTableSample$Species)

  DetHist_list <- detectionHistory(
    recordTable         = recordTableSample,
    camOp                = camop_no_problem,
    stationCol           = "Station",
    speciesCol           = "Species",
    recordDateTimeCol    = "DateTimeOriginal",
    species              = species_to_include,
    occasionLength       = 7,
    day1                 = "station",
    datesAsOccasionNames = FALSE,
    includeEffort        = TRUE,
    scaleEffort          = TRUE,
    timeZone             = "Asia/Kuala_Lumpur"
)


# 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 = DetHist_list$detection_history,
                  siteCovs = sitecovs,
                  obsCovs = list(effort = DetHist_list$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)


}

}
\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.
}
\author{
Juergen Niedballa
}
