Occupancy modeling is possible in Stan as shown here, despite the lack of support for integer parameters.
In many Bayesian applications of occupancy modeling, the true occupancy states (0 or 1) are directly modeled, but this can be avoided by marginalizing out the true occupancy state.
The Stan manual (pg. 96) gives an example of this kind of marginalization for a discrete change-point model.

Here’s a Stan implementation of a dynamic (multi-year) occupancy model of the sort described by MacKenzie et al. (2003).

Here are the results for the probability of colonization $\gamma$, and the probability of persistence $\phi$.
The blue dashed line shows the true value, and the dashed red lines shows the mean of all 1000 posterior modes.
The black lines represent the HPDI for each interation, and the black points represent the posterior modes.
This example uses a uniform prior on both of these parameters - probably an overrepresentation of prior ignorance in most real systems.

Based on some initial exploration, this approach seems much much (much?) faster than explicitly modeling the latent occurrence states in JAGS, with better chain mixing and considerably less autocorrelation. Extension to multi-species models should be straightforward too - huzzah!

References

MacKenzie DI, Nichols JD, Hines JE, Knutson MG, Franklin AB. 2003. Estimating site occupancy, colonization, and local extinction when a species is detected imperfectly. Ecology 84(8): 2200-2207. pdf

Quantifying spatial data (e.g. land cover) around points can be done in a variety of ways, some of which require considerable amounts of patience, clicking around, and/or cash for a license.
Here’s a bit of code that I cobbled together to quickly extract land cover data from the National Land Cover Database for buffered regions around points (e.g. small ponds, point-count locations, etc.), in this case, U.S. capitals.

Here, extract_cover() is a function to do the extraction (with the help of the raster package), and extraction.R makes a parallel call to the function using the doMC package:

# Function to extract the data in R instead of Arc# inputs: year, buffer size (in meters), point data file, # cover data directory, and output file directory# output: csv file with site id, cover type, and % in bufferextract_cover <-function(year, buffer, point_d ="sites.csv", data_dir="NLCD_data", write_dir="extracted"){ require(raster) require(rgdal) require(stringr)# load cover data filename <- paste(data_dir,"/nlcd_", year,"_landcover_2011_edition_2014_03_31.img", sep="") NLCD <- raster(filename)# load site data sites <- read.csv(point_d, header=T) coords <- sites[, c("longitude","latitude")]#convert lat/lon to appropriate projection names(coords)<- c("x","y") coordinates(coords)<-~x + y
proj4string(coords)<- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84") crs_args <- NLCD@crs@projargs
sites_transformed <- spTransform(coords, CRS(crs_args))#extract land cover data for each point, given buffer size Landcover <- extract(NLCD, sites_transformed, buffer=buffer)# summarize each site's data by proportion of each cover type summ <- lapply(Landcover,function(x){ prop.table(table(x))})# generate land cover number to name conversions num.codes <- unique(unlist(Landcover)) cover.names <- NLCD@data@attributes[[1]]$Land.Cover.Class[num.codes +1] levels(cover.names)[1]<-NA# first level is "" conversions <- data.frame(num.codes, cover.names) conversions <- na.omit(conversions) conversions <- conversions[order(conversions$num.codes),]# convert to data frame mydf <- data.frame(id = rep(sites$id, lapply(summ, length)), cover = names(unlist(summ)), percent = unlist(summ))# create cover name column mydf$cover2 <- mydf$cover
levels(mydf$cover2)<- conversions$cover.names
# write output out_name <- paste(write_dir,"/", year,"_cover_", buffer,"_m_buffer.csv", sep="") write.csv(mydf, out_name)}

extraction.R

12345678910111213141516

# Script to actually extract the data at various buffer distances# parallelized for speed (one core per year)library(doMC)years <- c(2001,2006,2011)nyears <- length(years)registerDoMC(nyears)# input vector of distances (in meters)buffer_distances <- c(1000)foreach (i=1:nyears)%dopar%{for(j in buffer_distances){ extract_cover(year = years[i], buffer=j)}}

This is a guest post generously provided by Joe Mihaljevic.

A common goal of community ecology is to understand how and why species composition shifts across space. Common techniques to determine which environmental covariates might lead to such shifts typically rely on ordination of community data to reduce the amount of data. These techniques include redundancy analysis (RDA), canonical correspondence analysis (CCA), and nonmetric multi-dimensional scaling (NMDS), each paired with permutation tests. However, as brought to light by Jackson et al. (2012: Ecosphere), these ordination techniques do not discern species-level covariate effects, making it difficult to attribute community-level pattern shifts to species-level changes. Jackson et al. (2012) propose a hierarchical modeling framework as an alternative, which we extend in this post to correct for imperfect detection.

Multilevel models can estimate species-level random and fixed covariate effects to determine the relative contribution of environmental covariates to changing composition across space (Jackson et al. 2012). For presence/absence data, such models are often formulated as:

Here $y_q$ is a vector of presences/absence of each species at each site ($q=1, … , nm,$ where $n$ is the number of species and $m$ the number of sites). This model can be extended to incorporate multiple covariates.

We are interested in whether species respond differently to environmental gradients (e.g. elevation, temperature, precipitation). If this is the case, then we expect community composition changes along such gradients. Concretely, we are interested in whether $\sigma_{slope}^2$ for any covariate differs from zero.

Jackson et al. (2012) provide code for a maximum likelihood implementation of their model with data from Southern Appalachian understory herbs using the R package lme4. Here we present a simple extension of Jackson and colleague’s work, correcting for detection error with repeat surveys (i.e. multi-species occupancy modeling). Specifically, the above model could be changed slightly to:

Now $y_q$ is the number of times each species is observed at each site over $j$ surveys. $p_{spp[q]}$ represents the species-specific probability of detection when the species is present, and $z_q$ represents the ‘true’ occurence of the species, a Bernoulli random variable with probability, $\psi_q$.

To demonstrate the method, we simulate data for a 20 species community across 100 sites with 4 repeat surveys. We assume that three site-level environmental covariates were measured, two of which have variable affects on occurrence probabilities (i.e. random effects), and one of which has consistent effects for all species (i.e. a fixed effect). We also assumed that species-specific detection probabilities varied, but were independent of environmental covariates.

Using information theory, specifically Watanabe-Akaike information criteria (WAIC), we compared this model, which assumes all covariates have random effects, to all combination of models varying whether each covariate has fixed or random effects. See this GitHub repository for all model statements and code.

A model that assumes all covariates have random effects, and the data-generating model, in which only covariates 1 and 2 have random effects, performed the best, but were indistinguishable from one another:

This result makes sense because the model with all random effects is able to recover species-specific responses to site-level covariates very well:

However, this model estimates that the 95% HDI of $\sigma_{slope}$ of covariate 3 includes zero, indicating that this covariate effectively has a fixed, rather than random effect among species.

Thus, we could conclude that the first two covariates have random effects, while the third covariate has a fixed effect. This means that composition shifts along gradients of covariates 1 and 2. We can visualize the relative contribution of covariate 1 and 2’s random effects to composition using ordination, as discussed in Jackson et al. (2012). To do this, we compare the linear predictor (i.e. $logit^{-1}(\psi_q)$) of the best model that includes only significant random effects to a model that does not have any random effects.

The code to extract linear predictors and ordinate the community is provided on GitHub: