% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/PPC.residuals.R
\name{PPC.community}
\alias{PPC.community}
\title{Calculate Community-Level Posterior Predictive Checks for Occupancy Models}
\usage{
PPC.community(
  p,
  psi,
  y,
  input_format = c("predict", "lists"),
  K = NULL,
  model = c("Occupancy", "RN"),
  zhat = NULL,
  z.cond = TRUE,
  type = c("FT", "PearChi2", "Deviance"),
  return.residuals = TRUE,
  show_progress = TRUE,
  ...
)
}
\arguments{
\item{p}{Either a 4D array [stations, species, iterations, occasions] from 
\code{\link{predict}} or a list of 3D arrays [iterations, stations, occasions], 
one per species}

\item{psi}{Either a 3D array [stations, species, iterations] from 
\code{\link{predict}} or a list of 2D arrays [iterations, stations], one per species}

\item{y}{List of detection histories, one matrix/vector per species}

\item{input_format}{Character indicating format of p and psi ("predict" or "lists")}

\item{K}{Number of occasions as either a scalar or site vector. Calculated automatically 
if y is a list of matrices.}

\item{model}{Character indicating model type ("Occupancy" or "RN")}

\item{zhat}{List of z estimate matrices, one per species (optional). Each matrix 
should follow the format specified in \code{\link{PPC.residuals}}.}

\item{z.cond}{Logical. If TRUE, new data is conditioned on estimated z (testing only 
detection model fit). If FALSE, generates new z for each posterior sample 
(testing complete model).}

\item{type}{Character indicating residual type ("FT", "PearChi2", or "Deviance")}

\item{return.residuals}{Logical. If TRUE, returns species-specific residuals along 
with Bayesian p-values. If FALSE, returns only the p-values.}

\item{show_progress}{Logical; whether to show a progress bar during computation 
(if package pbapply is available)}

\item{...}{Additional arguments passed to \code{\link{PPC.residuals}}.}
}
\value{
If return.residuals=TRUE, returns a list containing:
  \itemize{
    \item bp_values - Data frame with species-specific and community-level 
          Bayesian p-values
    \item species_results - List containing the complete PPC.residuals output 
          for each species
  }
  If return.residuals=FALSE, returns only the data frame of Bayesian p-values.
}
\description{
A wrapper function that applies Posterior Predictive Checks (PPC) across multiple 
species in a community occupancy model (from \code{\link{communityModel}}.
It calculates species-specific and community-level Bayesian p-values to assess 
model fit. The function accepts both \code{\link{predict}} output format and 
list format for model parameters.
}
\details{
This function extends the single-species PPC analysis to the community level by:
\itemize{
  \item Applying residual calculations to each species in the community
  \item Aggregating results to assess community-level model fit
  \item Providing both species-specific and community-level diagnostics
}

This function provides flexibility in input formats to accommodate different workflows:
\itemize{
  \item Direct output from camtrapR's predict() function (4D/3D arrays)
  \item Lists of species-specific arrays (for custom workflows)
}
}
\examples{
\dontrun{

# Create and fit model 
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)



# create predictions for p and psi
draws <- 100

p <- predict(object = mod.jags,
             mcmc.list = fit.jags,
             type = "p_array",
             draws = draws)
# output is in order [station, species, draw, occasion]
 
 psi <- predict(object = mod.jags,
                mcmc.list = fit.jags,
                type = "psi_array",
                draws = draws)
 # output is in order [station, species, draw]



ppc_comm <- PPC.community(
  p = p,
  psi = psi,
  y = mod.jags@input$ylist, 
  model = "Occupancy",
  type = "FT")
  
# Bayesian p-values
 ppc_comm$BP
 
   
 str(ppc_comm$residuals)
 
 # get individual species PPC results
 ppc_species <- ppc_comm$residuals[[1]] # first species
 
 plot(apply(ppc_species$res.obs, 2, mean), apply(ppc_species$res.new, 2, mean),
 xlab = "Observed residuals",
 ylab = "Predicted residuals"
 )
 
 abline(0,1)  # diagonal line is not visible due to tiny data set
  
 }
}
\seealso{
\code{\link{PPC.residuals}} for details on the underlying single-species 
  calculations
}
\author{
Rahel Sollmann
}
