Fitting a Spatial Factor Multi-Species Occupancy Model

Data from: Madidi

model
code
analysis
102 sites, 19 mammal species
Authors

German Forero

Robert Wallace

Galo Zapara-Rios

Emiliana Isasi-Catalá

Diego J. Lizcano

Published

August 16, 2025

Single-species occupancy models

Single-species occupancy models (MacKenzie et al., 2002) are widely used in ecology to estimate and predict the spatial distribution of a species from data collected in presence–absence repeated surveys. The popularity of these models stems from their ability to estimate the effects of environmental or management covariates on species occurrences, while accounting for false-negative errors in detection, which are common in surveys of natural populations.

Multi-species occupancy models

Multi-species occupancy models for estimating the effects of environmental covariates on several species occurrences while accounting for imperfect detection were build on the principle of the Single-species occupancy model, and developed more than 20 years ago.

Multi-species occupancy models are a powerful tool for combining information from multiple species to estimate both individual and community-level responses to management and environmental variables.

Objective

We want to asses the effect of protected areas on the occupancy of the species. We hypothesize that several mammal species have benefited of the conservation actions provided by protected areas, so we expect a decreases in occupancy from the interior of the protected area to the exterior as a function of the distance to the protected area border.

To account for several ecological factors we also tested and included elevation and forest integrity index as occupancy covariates.

We used the newly developed R package spOccupancy as approach to modelling the probability of occurrence of each species as a function of fixed effects of measured environmental covariates and random effects designed to account for unobserved sources of spatial dependence (spatial autocorrelation).

Code
library(grateful) # Facilitate Citation of R Packages
library(readxl) # Read Excel Files
library(DT) # A Wrapper of the JavaScript Library 'DataTables'
library(sf) # Simple Features for R
library(mapview) # Interactive Viewing of Spatial Data in R
library(maps) # Draw Geographical Maps
library(tmap) # Thematic Maps
library(terra) # Spatial Data Analysis
library(elevatr) # Access Elevation Data from Various APIs

# library(rjags) # Bayesian Graphical Models using MCMC 
library(bayesplot) # Plotting for Bayesian Models # Plotting for Bayesian Models
library(tictoc) # Functions for Timing R Scripts, as Well as Implementations of "Stack" and "StackList" Structures 
library(MCMCvis) # Tools to Visualize, Manipulate, and Summarize MCMC Output
library(coda) # Output Analysis and Diagnostics for MCMC
library(beepr) # Easily Play Notification Sounds on any Platform 
library(snowfall) # Easier Cluster Computing (Based on 'snow')

#library(ggmcmc)
library(camtrapR) # Camera Trap Data Management and Preparation 
library(spOccupancy) # Single-Species, Multi-Species, and Integrated Spatial Occupancy
library(tidyverse) # Easily Install and Load the 'Tidyverse'

Fitting a Multi-Species Spatial Occupancy Model

We use a more computationally efficient approach for fitting spatial multi-species occupancy models. This alternative approach is called a “spatial factor multi-species occupancy model”, and is described in depth in Doser, Finley, and Banerjee (2023). This newer approach also accounts for residual species correlations (i.e., it is a joint species distribution model with imperfect detection). The simulation results from Doser, Finley, and Banerjee (2023) show that this new alternative approach outperforms, or performs equally to spMsPGOcc(), while being substantially faster.

The Latent factor multi-species occupancy model is described in detail here

Data from Plantas Medicinales Putumayo

Here we use the table: - COL-18-Putumayo2023

Code
source("C:/CodigoR/WCS-CameraTrap/R/organiza_datos_v3.R")

AP_PlantasMed <- read_sf("C:/CodigoR/Occu_APs/shp/PlantasMedicinales/WDPA_WDOECM_May2025_Public_555511938_shp-polygons.shp")

### Ecu 17, Ecu 18, ECU 20, Ecu 22  

# load data and make array_locID column
Col_18 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Colombia/COL-018-Putumayo2023_WCS_WI.xlsx") |> mutate(array_locID=paste("Col_18", locationID, sep="_"))


# get sites
Col_18_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Colombia/COL-018-Putumayo2023_WCS_WI.xlsx")



# get elevation map
elevation_18 <- rast(get_elev_raster(Col_18_sites, z = 10)) #z =1-14
# bb <-  st_as_sfc(st_bbox(elevation_17)) # make bounding box 




# extract covs using points and add to _sites
covs_Col_18_sites <- cbind(Col_18_sites, terra::extract(elevation_18, Col_18_sites))
# covs_Col_17_sites <- cbind(Col_17_sites, terra::extract(elevation_17, Col_17_sites))


# get which are in and out
covs_Col_18_sites$in_AP = st_intersects(covs_Col_18_sites, AP_PlantasMed, sparse = FALSE)
# covs_Col_17_sites$in_AP = st_intersects(covs_Col_17_sites, AP_Yasuni, sparse = FALSE)




# make a map
mapview (elevation_18, alpha=0.5) + 
  mapview (AP_PlantasMed, color = "green", col.regions = "green", alpha = 0.5) +
  mapview (covs_Col_18_sites, zcol = "in_AP", col.regions =c("red","blue"), burst = TRUE) 
  # mapview (covs_Col_17_sites, zcol = "in_AP", col.regions =c("red","blue"), burst = TRUE) +

Data fom Bajo Madidi and Heath

Here we use the tables: - BOL-008a - BOL-008b - BOL14a - BOL14b

Code
source("C:/CodigoR/WCS-CameraTrap/R/organiza_datos_v3.R")

Area_Madidi <- read_sf("C:/CodigoR/Occu_APs/shp/Area_Madidi/WDPA_WDOECM_Jul2025_Public_303894_shp-polygons.shp")

Madidi_NP <- read_sf("C:/CodigoR/Occu_APs/shp/Madidi_NP/WDPA_WDOECM_Jul2025_Public_98183_shp-polygons.shp")
#AP_Tahuayo <- read_sf("C:/CodigoR/Occu_APs/shp/Tahuayo/WDPA_WDOECM_Jun2025_Public_555555621_shp-polygons.shp")

# load data and make array_locID column
#Bol_Pacaya <- read_excel("F:/WCS-CameraTrap/data/BDcorregidas/Peru/PER-003_BD_ACRCTT_T0.xlsx", sheet = "Image")


Bol_Madidi_1 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Bolivia/Guido/BOL-008a.xlsx") |> mutate(Point.x=as.character(paste("M1",Point.x, sep = "-"))) |> mutate(Point.y=as.character(paste("M1",Point.y, sep = "-")))
65 cameras in Cameras. 
 61 cameras in Deployment. 
 61 deployments in Deployment. 
 31 points in Deployment. 
 61 cameras in Images. 
 31 points in Images. 
[1] "dates ok"
year: 2005 
 Jaguar_Design: yes 
Code
Bol_Madidi_2 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Bolivia/Guido/BOL-008b.xlsx") |> mutate(Point.x=as.character(paste("M2",Point.x, sep = "-"))) |> mutate(Point.y=as.character(paste("M2",Point.y, sep = "-")))
60 cameras in Cameras. 
 52 cameras in Deployment. 
 52 deployments in Deployment. 
 30 points in Deployment. 
 51 cameras in Images. 
 30 points in Images. 
[1] "dates ok"
year: 2005 
 Jaguar_Design: yes 
Code
Bol_Madidi_3 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Bolivia/Guido/BOL-014a.xlsx")|> mutate(Point.x=as.character(paste("M3",Point.x, sep = "-"))) |> mutate(Point.y=as.character(paste("M3",Point.y, sep = "-")))
47 cameras in Cameras. 
 44 cameras in Deployment. 
 44 deployments in Deployment. 
 26 points in Deployment. 
 44 cameras in Images. 
 26 points in Images. 
[1] "dates ok"
year: 2009 
 Jaguar_Design: yes 
Code
Bol_Madidi_4 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Bolivia/Guido/BOL-014b.xlsx")|> mutate(Point.x=as.character(paste("M4",Point.x, sep = "-"))) |> mutate(Point.y=as.character(paste("M1",Point.y, sep = "-")))
29 cameras in Cameras. 
 22 cameras in Deployment. 
 22 deployments in Deployment. 
 15 points in Deployment. 
 22 cameras in Images. 
 15 points in Images. 
[1] "dates ok"
year: 2009 
 Jaguar_Design: yes 
Code
FLII2016 <- rast("C:/CodigoR/WCS_2024/FLI/raster/FLII_final/FLII_2016.tif")



# get sites
Bol_Madidi_sites1 <-  Bol_Madidi_1 |> 
   dplyr::bind_rows(Bol_Madidi_2) |> 
   dplyr::bind_rows(Bol_Madidi_3) |> 
   dplyr::bind_rows(Bol_Madidi_4) |> 
  select("Latitude", "Longitude", "Point.x" 
) |> dplyr::distinct( )  

Bol_Madidi_sites <- sf::st_as_sf(Bol_Madidi_sites1, coords = c("Longitude","Latitude"))
st_crs(Bol_Madidi_sites) <- 4326


# get elevation map
elevation_17 <- rast(get_elev_raster(Bol_Madidi_sites, z = 9)) #z =1-14
# bb <-  st_as_sfc(st_bbox(elevation_17)) # make bounding box 




# extract covs using points and add to _sites
covs_Bol_Madidi_sites <- cbind(Bol_Madidi_sites, terra::extract(elevation_17, Bol_Madidi_sites))
# covs_Ecu_17_sites <- cbind(Ecu_17_sites, terra::extract(elevation_17, Ecu_17_sites))


# get which are in and out
covs_Bol_Madidi_sites$in_AP = st_intersects(covs_Bol_Madidi_sites, Madidi_NP, sparse = FALSE)
# covs_Ecu_17_sites$in_AP = st_intersects(covs_Ecu_17_sites, AP_Machalilla, sparse = FALSE)


# make a map
mapview (elevation_17, alpha=0.7) + 
  mapview (Madidi_NP, color = "green", col.regions = "green", alpha = 0.5) +
  mapview (Area_Madidi, color = "yellow", col.regions = "yellow", alpha = 0.5) +
  #mapview (AP_Tahuayo, color = "green", col.regions = "green", alpha = 0.5) +
  mapview (covs_Bol_Madidi_sites, zcol = "in_AP", col.regions =c("red","blue"), burst = TRUE) 

Tamshiyacu Tahuayo data

Here we use the tables: - PER-003_BD_ACRCTT_T0.xlsx - PER-002_BD_ACRTT-PILOTO.xlsx

Code
source("C:/CodigoR/WCS-CameraTrap/R/organiza_datos_v3.R")

AP_Pacaya <- read_sf("C:/CodigoR/Occu_APs/shp/PacayaSamiria/WDPA_WDOECM_Jun2025_Public_249_shp-polygons.shp")

AP_Tahuayo <- read_sf("C:/CodigoR/Occu_APs/shp/Tahuayo/WDPA_WDOECM_Jun2025_Public_555555621_shp-polygons.shp")

# load data and make array_locID column
Per_Tahuayo_piloto <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Peru/PER-002_BD_ACRTT-PILOTO.xlsx")



Per_Tahuayo <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Peru/PER-003_BD_ACRCTT_T0.xlsx")

 
FLII2016 <- rast("C:/CodigoR/WCS_2024/FLI/raster/FLII_final/FLII_2016.tif")

# get sites
# Per_Pacaya_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Peru/PER-003_BD_ACRCTT_T0.xlsx")

# get sites
Per_Tahuayo_sites1 <- Per_Tahuayo |> select("Latitude",
                                    "Longitude",
                                    "Camera_Id" 
                                    ) |> dplyr::distinct( )  

Per_Tahuayo_sites <- sf::st_as_sf(Per_Tahuayo_sites1, coords = c("Longitude","Latitude"))
st_crs(Per_Tahuayo_sites) <- 4326



# get Pacaya sites
Per_Tahuayo_piloto_sites1 <- Per_Tahuayo_piloto |> select("Latitude",
                                    "Longitude",
                                    "Camera_Id" 
                                    ) |> dplyr::distinct( )  

Per_Tahuayo_piloto_sites <- sf::st_as_sf(Per_Tahuayo_piloto_sites1, coords = c("Longitude","Latitude"))
st_crs(Per_Tahuayo_piloto_sites) <- 4326




# get elevation map
elevation_PE <- rast(get_elev_raster(Per_Tahuayo_sites, z = 10)) #z =1-14
# bb <-  st_as_sfc(st_bbox(elevation_17)) # make bounding box 





# extract covs using points and add to _sites
covs_Per_Tahuayo_sites <- cbind(Per_Tahuayo_sites,
                                terra::extract(elevation_PE,
                                               Per_Tahuayo_sites)
                                )

# extract covs using points and add to _sites
covs_Per_Tahuayo_piloto_sites <- cbind(Per_Tahuayo_piloto_sites, terra::extract(elevation_PE, Per_Tahuayo_piloto_sites))



# get which are in and out
covs_Per_Tahuayo_sites$in_AP = st_intersects(covs_Per_Tahuayo_sites, AP_Tahuayo, sparse = FALSE)

covs_Per_Tahuayo_piloto_sites$in_AP = st_intersects(covs_Per_Tahuayo_piloto_sites, AP_Tahuayo, sparse = FALSE)




# make a map
mapview (elevation_PE, alpha=0.5) + 
  mapview (AP_Pacaya, color = "green", col.regions = "green", alpha = 0.5) +
  mapview (AP_Tahuayo, color = "green", col.regions = "green", alpha = 0.5) +
  mapview (covs_Per_Tahuayo_sites, zcol = "in_AP", col.regions =c("red","blue"), burst = TRUE) +   
  mapview (covs_Per_Tahuayo_piloto_sites, 
           zcol = "in_AP", 
           col.regions =c("blue"), 
           burst = TRUE) 

Yasuni data

Here we use the tables Ecu-13, Ecu-17, Ecu-18 y Ecu-20

Code
source("C:/CodigoR/WCS-CameraTrap/R/organiza_datos_v3.R")

AP_Yasuni <- read_sf("C:/CodigoR/Occu_APs/shp/Yasuni/WDPA_WDOECM_May2025_Public_186_shp-polygons.shp")

### Ecu 17, Ecu 18, ECU 20, Ecu 22  

# load data and make array_locID column
Ecu_13 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-013.xlsx") |> mutate(array_locID=paste("Ecu_13", locationID, sep="_"))
Ecu_17 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-017.xlsx") |> mutate(array_locID=paste("Ecu_17", locationID, sep="_"))
Ecu_18 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-018.xlsx")|> mutate(array_locID=paste("Ecu_18", locationID, sep="_"))
Ecu_20 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-020_Fix.xlsx")|> mutate(array_locID=paste("Ecu_20", locationID, sep="_"))
# Ecu_21 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-021.xlsx") |> mutate(array_locID=paste("Ecu_14", locationID, sep="_"))
Ecu_22 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-022.xlsx")|> mutate(array_locID=paste("Ecu_22", locationID, sep="_"))



# get sites
Ecu_13_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-013.xlsx")
Ecu_17_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-017.xlsx")
Ecu_18_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-018.xlsx")
Ecu_20_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-020_Fix.xlsx")
# Ecu_21_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-021.xlsx")
Ecu_22_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-022.xlsx")




# get elevation map
elevation_EC <- rast(get_elev_raster(Ecu_17_sites, z = 7)) #z =1-14
bb <-  st_as_sfc(st_bbox(elevation_EC)) # make bounding box 




# extract covs using points and add to _sites
covs_Ecu_13_sites <- cbind(Ecu_13_sites, terra::extract(elevation_EC, Ecu_13_sites))
covs_Ecu_17_sites <- cbind(Ecu_17_sites, terra::extract(elevation_EC, Ecu_17_sites))
covs_Ecu_18_sites <- cbind(Ecu_18_sites, terra::extract(elevation_EC, Ecu_18_sites))
covs_Ecu_20_sites <- cbind(Ecu_20_sites, terra::extract(elevation_EC, Ecu_20_sites))
#covs_Ecu_21_sites <- cbind(Ecu_21_sites, terra::extract(elevation_17, Ecu_21_sites))
covs_Ecu_22_sites <- cbind(Ecu_22_sites, terra::extract(elevation_EC, Ecu_22_sites))

# get which are in and out
covs_Ecu_13_sites$in_AP = st_intersects(covs_Ecu_13_sites, AP_Yasuni, sparse = FALSE)
covs_Ecu_17_sites$in_AP = st_intersects(covs_Ecu_17_sites, AP_Yasuni, sparse = FALSE)
covs_Ecu_18_sites$in_AP = st_intersects(covs_Ecu_18_sites, AP_Yasuni, sparse = FALSE)
covs_Ecu_20_sites$in_AP = st_intersects(covs_Ecu_20_sites, AP_Yasuni, sparse = FALSE)
#covs_Ecu_21_sites$in_AP = st_intersects(covs_Ecu_21_sites, AP_Yasuni, sparse = FALSE)
covs_Ecu_22_sites$in_AP = st_intersects(covs_Ecu_22_sites, AP_Yasuni, sparse = FALSE)

# covs_Ecu_16_sites$in_AP = st_intersects(covs_Ecu_16_sites, AP_Llanganates, sparse = FALSE)



# make a map
mapview (elevation_EC, alpha=0.5) + 
  mapview (AP_Yasuni, color = "green", col.regions = "green", alpha = 0.5) +
  mapview (covs_Ecu_13_sites, zcol = "in_AP", col.regions =c("red"), burst = TRUE) +
  mapview (covs_Ecu_17_sites, zcol = "in_AP", col.regions =c("red","blue"), burst = TRUE) +
  mapview (covs_Ecu_18_sites, zcol = "in_AP", col.regions =c("red"), burst = TRUE) +
  mapview (covs_Ecu_20_sites, zcol = "in_AP", col.regions =c("red","blue"), burst = TRUE) +
#  mapview (covs_Ecu_21_sites, zcol = "in_AP", col.regions =c("red"), burst = TRUE) +
  mapview (covs_Ecu_22_sites, zcol = "in_AP", burst = TRUE, col.regions = c("red") ) #+
  # mapview (covs_Ecu_16_sites, zcol = "in_AP", burst = TRUE, col.regions =c("red","blue")) 

Llanganates data

Here we use the tables Ecu-14, Ecu-15 y Ecu-16.

Code
AP_Llanganates <- read_sf("C:/CodigoR/Occu_APs/shp/Llanganates/WDPA_WDOECM_May2025_Public_97512_shp-polygons.shp")

### Ecu 14, Ecu 15  y Ecu 16

# load data and make array_locID column
Ecu_14 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-014.xlsx") |> mutate(array_locID=paste("Ecu_14", locationID, sep="_"))
Ecu_15 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-015.xlsx")|> mutate(array_locID=paste("Ecu_15", locationID, sep="_"))
Ecu_16 <- loadproject("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-016.xlsx")|> mutate(array_locID=paste("Ecu_16", locationID, sep="_"))



# get sites
Ecu_14_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-014.xlsx")
Ecu_15_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-015.xlsx")
Ecu_16_sites <- get.sites("F:/WCS-CameraTrap/data/BDcorregidas/Ecuador/ECU-016.xlsx")




# get elevation map
elevation_14 <- rast(get_elev_raster(Ecu_14_sites, z = 7)) #z =1-14
bb <-  st_as_sfc(st_bbox(elevation_14)) # make bounding box 




# extract covs using points and add to _sites
covs_Ecu_14_sites <- cbind(Ecu_14_sites, terra::extract(elevation_14, Ecu_14_sites))

covs_Ecu_15_sites <- cbind(Ecu_15_sites, terra::extract(elevation_14, Ecu_15_sites))

covs_Ecu_16_sites <- cbind(Ecu_16_sites, terra::extract(elevation_14, Ecu_16_sites))

# get which are in and out
covs_Ecu_14_sites$in_AP = st_intersects(covs_Ecu_14_sites, AP_Llanganates, sparse = FALSE)

covs_Ecu_15_sites$in_AP = st_intersects(covs_Ecu_15_sites, AP_Llanganates, sparse = FALSE)

covs_Ecu_16_sites$in_AP = st_intersects(covs_Ecu_16_sites, AP_Llanganates, sparse = FALSE)



# make a map
mapview (elevation_14, alpha=0.7) + 
  mapview (AP_Llanganates, color = "green", col.regions = "green", alpha = 0.5) +
  mapview (covs_Ecu_14_sites, zcol = "in_AP", col.regions =c("red","blue"), burst = TRUE) +
  mapview (covs_Ecu_15_sites, zcol = "in_AP", burst = TRUE, col.regions = c("blue") )+
  mapview (covs_Ecu_16_sites, zcol = "in_AP", burst = TRUE, col.regions =c("red","blue")) 

Pacoche 2014 data

Here we use the tables Pacoche_DL_CT-RVP-2014

Camera trap operation data and detection history

Code
# # Join 3 tables
# # fix count in ECU 13, 17, 22,
# Ecu_13$Count <- as.character(Ecu_13$Count)
# Ecu_17$Count <- as.character(Ecu_17$Count)
# Ecu_22$Count <- as.character(Ecu_22$Count)
# 
# Ecu_full <- Ecu_13 |> full_join(Ecu_17) |> 
#                       full_join(Ecu_18) |> 
#                       full_join(Ecu_20) |> 
# #                      full_join(Ecu_21) |> 
#                       full_join(Ecu_22)
# 
# ###### Bolivia

Bol_full <- Bol_Madidi_1  |> 
   full_join(Bol_Madidi_2) |> 
   full_join(Bol_Madidi_3) |> 
   full_join(Bol_Madidi_4) 
# change camera Id by point. two cameras in one
Bol_full <- Bol_full |> mutate(Camera_Id=Point.x)


# # Ecu_18$Count <- as.numeric(Ecu_18$Count)
# Per_Tahuayo_piloto$Longitude <- as.numeric(Per_Tahuayo_piloto$Longitude)
# Per_Tahuayo_piloto$Latitude <- as.numeric(Per_Tahuayo_piloto$Latitude)
# 
# 
# Per_full <- Per_Tahuayo|> 
#   full_join(Per_Tahuayo_piloto) #|> 
#                       # full_join(Ecu_18) |> 
#                       # full_join(Ecu_20) |> 
#                       # full_join(Ecu_21) |> 
#                       # full_join(Ecu_22)
# 
# # rename camera id
# # Per_full$camid <- Per_full$`Camera_Id`
# 
# Ecu_full$Count <- as.numeric(Ecu_full$Count)
# Per_full$Count <- as.numeric(Per_full$Count)


#################### Ecuador Llanganates

# # Join 3 tables
# Ecu_Llanganates <- Ecu_14 |> full_join(Ecu_15) |> full_join(Ecu_16)
# 
# 
# # make columns equal to 46
# Ecu_full <- Ecu_full[,-47]
# Col_18 <- Col_18[,-47]
# Ecu_Llanganates <- Ecu_Llanganates[,-c(50,49,48,47)]

##################################
data_full <- Bol_full# rbind(Ecu_full, 
                   # Per_full,
                   # Bol_full,
                   # Col_18,
                   # Ecu_Llanganates)


# fix date format
# 
# Formatting a Date object
data_full$start_date <- as.Date(data_full$"start_date", "%Y/%m/%d")
data_full$start_date <- format(data_full$start_date, "%Y-%m-%d")

data_full$end_date <- as.Date(data_full$"end_date", "%Y/%m/%d")
data_full$end_date <- format(data_full$end_date, "%Y-%m-%d")

data_full$eventDate <- as.Date(data_full$"Date_Time_Captured", "%Y/%m/%d")
data_full$eventDate <- format(data_full$eventDate, "%Y-%m-%d")

# Per_full$eventDateTime <- ymd_hms(paste(Per_full$"photo_date", Per_full$"photo_time", sep=" "))
data_full$eventDateTime <- ymd_hms(data_full$"Date_Time_Captured")

###############################
# remove duplicated cameras
################################
# ind1 <- which(data_full$Camera_Id=="ECU-020-C0027")
# ind2 <- which(data_full$Camera_Id=="ECU-020-C0006")
# data_full <- data_full[-ind1,]
# data_full <- data_full[-ind2,]


# filter 2021 and make uniques
CToperation  <- data_full |> dplyr::group_by(Camera_Id) |> #(array_locID) |> 
                           mutate(minStart=start_date, maxEnd=end_date) |> distinct(Longitude, Latitude, minStart, maxEnd) |> dplyr::ungroup()
# remove one duplicated
# View(CToperation)
# CToperation <- CToperation[-15,]

# Duplicated Madidi
# 98 107, 97 104, 90 102, 81 87, 74 82
# M3-19: M3-21: M4-10: M4-12: M4-18:  From Madidi
CToperation <- CToperation[-c(107, 104, 102, 87, 82),]

#CToperation[231,3] <- "-4.482831" #Latitude
#CToperation[93,3] <- "-0.5548211" #Latitude
#CToperation[93,2] <- "-76.48333"

# duplicated in llanganates
# CToperation <- CToperation[-464,] 

### Check duplicated
# View(as.data.frame(sort(table(CToperation$Latitude))))
# View(as.data.frame(sort(table(CToperation$Longitude))))
# View(as.data.frame(table(CToperation$Camera_Id)))

# CToperation <- CToperation[-c(90,94),]
# Latitude -4.48283
# Latitude -0.554820969700813
# Longitude -76.4833290316164

# Generamos la matríz de operación de las cámaras

camop <- cameraOperation(CTtable= CToperation, # Tabla de operación
                         stationCol= "Camera_Id", # Columna que define la estación
                         setupCol= "minStart", #Columna fecha de colocación
                         retrievalCol= "maxEnd", #Columna fecha de retiro
                         #hasProblems= T, # Hubo fallos de cámaras
                         dateFormat= "%Y-%m-%d")#, #, # Formato de las fechas
                         #cameraCol="Camera_Id")
                         # sessionCol= "Year")

# Generar las historias de detección ---------------------------------------
## remove plroblem species

# Per_full$scientificName <- paste(Per_full$genus, Per_full$species, sep=" ")

#### remove NAs and setups
# ind <- which(is.na(data_full$scientificName))
# data_full <- data_full[-ind,]
# ind <- which(Per_full$scientificName=="NA NA")
# Per_full <- Per_full[-ind,]

# ind <- which(Per_full$scientificName=="Set up")
# Per_full <- Per_full[-ind,]
# 
# ind <- which(Per_full$scientificName=="Blank")
# Per_full <- Per_full[-ind,]
# 
# ind <- which(Per_full$scientificName=="Unidentifiable")
# Per_full <- Per_full[-ind,]


DetHist_list <- lapply(unique(data_full$scientificName), FUN = function(x) {
  detectionHistory(
    recordTable         = data_full, # abla de registros
    camOp                = camop, # Matriz de operación de cámaras
    stationCol           = "Camera_Id",
    speciesCol           = "scientificName",
    recordDateTimeCol    = "eventDateTime",
    recordDateTimeFormat  = "%Y-%m-%d %H:%M:%S",
    species              = x,     # la función reemplaza x por cada una de las especies
    occasionLength       = 7, # Colapso de las historias a 10 ías
    day1                 = "station", # "survey" a specific date, "station", #inicie en la fecha de cada survey
    datesAsOccasionNames = FALSE,
    includeEffort        = TRUE,
    scaleEffort          = FALSE,
    #unmarkedMultFrameInput=TRUE
    timeZone             = "America/Bogota" 
    )
  }
)

# names
names(DetHist_list) <- unique(data_full$scientificName)

# Finalmente creamos una lista nueva donde estén solo las historias de detección
ylist <- lapply(DetHist_list, FUN = function(x) x$detection_history)
# otra lista con effort scaled
efort <- lapply(DetHist_list, FUN = function(x) x$effort)

# number of observetions per sp, collapsed to 7 days
# lapply(ylist, sum, na.rm = TRUE)

Arrange spatial covariates

The standard EPSG code for a Lambert Azimuthal Equal-Area projection for South America is EPSG:10603 (WGS 84 / GLANCE South America). This projection is specifically designed for the continent and has its center located around the central meridian for the region. The units are meters.

FLII scores range from 0 (lowest integrity) to 10 (highest). Grantham discretized this range to define three broad illustrative categories: low (≤6.0); medium (>6.0 and <9.6); and high integrity (≥9.6).

Code
# #transform coord data to Lambert Azimuthal Equal-Area
# AP_Tahuayo_UTM <- st_transform(AP_Tahuayo, "EPSG:10603")
# # Convert to LINESTRING
# AP_Tahuayo_UTM_line <- st_cast(AP_Tahuayo_UTM,"MULTILINESTRING")# "LINESTRING")
# #transform Yasuni to Lambert Azimuthal Equal-Area
# AP_Yasuni_UTM <- st_transform(AP_Yasuni, "EPSG:10603")
# # Convert to LINESTRING
# AP_Yasuni_UTM_line <- st_cast(AP_Yasuni_UTM, "MULTILINESTRING")

#transform Yasuni to Lambert Azimuthal Equal-Area
AP_Madidi_UTM <- st_transform(Madidi_NP, "EPSG:10603")
# Convert to LINESTRING
AP_Madidi_UTM_line <- st_cast(AP_Madidi_UTM, "MULTILINESTRING")

# # Plantas
# AP_PlantasMed_UTM <- st_transform(AP_PlantasMed, "EPSG:10603")
# 
# #Llanganates
# AP_Llanganates_UTM <- st_transform(AP_Llanganates, "EPSG:10603")


############## sf AP Union 
AP_merged_sf_UTM <- AP_Madidi_UTM# st_union(
                             # AP_Yasuni_UTM,
                             # AP_Tahuayo_UTM,
                             # AP_Madidi_UTM,
                             # AP_PlantasMed_UTM,
                             # AP_Llanganates_UTM
                             # )

AP_merged_line <- st_cast(AP_merged_sf_UTM, to="MULTILINESTRING")


# make sf() from data table
data_full_sf <- CToperation |> 
    st_as_sf(coords = c("Longitude", "Latitude"), 
              crs = 4326)

# get the elevation point from AWS
elev_data <- elevatr::get_elev_point(locations = data_full_sf, src = "aws")
Mosaicing & Projecting
Note: Elevation units are in meters
Code
# extract elev and paste to table
data_full_sf$elev <- elev_data$elevation
str(data_full_sf$elev)
 num [1:102] 207 212 207 212 213 211 209 207 209 211 ...
Code
# extract in AP
data_full_sf$in_AP = as.factor(st_intersects(data_full_sf, Madidi_NP, sparse = FALSE))

in_AP <- as.numeric((st_drop_geometry(data_full_sf$in_AP)))

# extract FLII
data_full_sf$FLII <- terra::extract(FLII2016, data_full_sf)[,2]
str(data_full_sf$FLII)
 num [1:102] 9.99 9.99 10 9.99 10 ...
Code
# Replace all NAs with min flii in a numeric column
data_full_sf$FLII[is.na(data_full_sf$FLII)] <- min(data_full_sf$FLII, na.rm = TRUE)

# mapview(full_sites_14_15_16_sf, zcol = "in_AP", burst = TRUE)

# Transform coord to Lambert Azimuthal Equal-Area
data_full_sf_UTM <- st_transform(data_full_sf, "EPSG:10603")


coords <- st_coordinates(data_full_sf_UTM)
#str(coords)

#### fix duplicated coord
# -1840583.53296873  en x
# -1842515.36969736  en x
# 1547741.44311964  en y
# 1541202.24796904 en y

# which(coords[,1]=="-1840583.53296873")
# which(coords[,1]=="-1842515.36969736")
# which(coords[,2]=="1547741.44311964")
# which(coords[,2]=="1541202.24796904")

# make Ecu_14_15_16 an sf object
#    cam_sf <- st_as_sf(Ecu_14_15_16, coords = c("lon","lat"))   #crs="EPSG:4326")
    #--- set CRS ---#
#    st_crs(cam_sf) <- 4326




# Calculate the distance
#multiplic <- full_sites_14_15_16_sf_UTM |> mutate(multiplic= as.numeric(in_AP)) 
multiplic=ifelse(data_full_sf_UTM$in_AP=="TRUE",-1,1)
data_full_sf_UTM$border_dist <- as.numeric(st_distance(data_full_sf_UTM, AP_Madidi_UTM_line) * multiplic )
# print(border_dist)

# convert true false to inside 1, outside 0
data_full_sf_UTM <- data_full_sf_UTM |>
  mutate(in_AP = case_when(
    str_detect(in_AP, "TRUE") ~ 1, # "inside_AP",
    str_detect(in_AP, "FALSE") ~ 0 #"outside_AP"
  )) |> mutate(in_AP=as.factor(in_AP))


hist(data_full_sf_UTM$border_dist)

Code
hist(data_full_sf_UTM$elev)

Prepare the model

TipData in a 3D array

The data must be placed in a three-dimensional array with dimensions corresponding to species, sites, and replicates in that order.

The function sfMsPGOcc

Fits multi-species spatial occupancy models with species correlations (i.e., a spatially-explicit joint species distribution model with imperfect detection). We use Polya-Gamma latent variables and a spatial factor modeling approach. Currently, models are implemented using a Nearest Neighbor Gaussian Process.

Code
# Detection-nondetection data ---------
# Species of interest, can select individually
# curr.sp <- sort(unique(Ecu_14_15_16$.id))# c('BAWW', 'BLJA', 'GCFL')
# sort(names(DetHist_list))
selected.sp <-  c(
"Atelocynus microtis" ,
#"Coendou prehensilis" ,
"Cuniculus paca",           
"Dasyprocta punctata",      
"Dasypus novemcinctus" ,    
"Didelphis marsupialis",    
"Eira barbara",  
#"Herpailurus yagouaroundi",
"Leopardus pardalis",    
#"Leopardus tigrinus" ,
"Leopardus wiedii",         
"Mazama americana",
"Mazama gouazoubira",
#"Mitu tuberosum" ,
#"Myoprocta pratti",
"Myrmecophaga tridactyla",
"Nasua nasua" ,
# "Mazama americana",         
# "Myotis myotis",           
# "Nasua narica",             
# "Odocoileus virginianus",   
"Panthera onca" ,
# "Procyon cancrivorus" ,
"Pecari tajacu",    
#"Penelope jacquacu" ,
"Priodontes maximus" ,
"Procyon cancrivorus",      
# "Psophia leucoptera",
"Puma concolor" ,
# "Puma yagouaroundi",        
# "Rattus rattus" ,
# "Roedor sp.",
# "Sciurus sp.",       
# "Sus scrofa",               
# "Sylvilagus brasiliensis",  
#"Tamandua tetradactyla",   
#"Tapirus pinchaque" ,
"Tapirus terrestris",
"Tayassu pecari"
#"Tinamus major"            
              )

# y.msom <- y[which(sp.codes %in% selected.sp), , ]
# str(y.msom)

# Use selection
y.selected <- ylist[selected.sp]   

#####################################
#### three-dimensional array with dimensions corresponding to:
#### species, sites, and replicates
#####################################

# 1. Load the abind library to make arrays easily 
library(abind)
my_array_abind <- abind(y.selected, # start from list
                        along = 3, # 3D array
                        use.first.dimnames=TRUE) # keep names

# Transpose the array to have:
# species, sites, and sampling occasions in that order
# The new order is (3rd dim, 1st dim, 2nd dim)
transposed_array <- aperm(my_array_abind, c(3, 1, 2))

#### site covs
sitecovs <- as.data.frame(st_drop_geometry(
                    data_full_sf_UTM[,5:8]))

 sitecovs[, 1] <- as.vector((sitecovs[,1]))   # scale numeric covariates
 sitecovs[, 1] <- as.numeric((sitecovs[,2]))   # scale numeric covariates
 sitecovs[, 3] <- as.vector((sitecovs[,3]))   # scale numeric covariates
 sitecovs[, 4] <- as.vector((sitecovs[,4]))   # scale numeric covariates
 # sitecovs$fact <- factor(c("A", "A", "B"))    # categorical covariate

names(sitecovs) <- c("elev", "in_AP", "FLII", "border_dist")

# check consistancy equal number of spatial covariates and rows in data
# identical(nrow(ylist[[1]]), nrow(covars)) 

# Base de datos para los análisis -----------------------------------------

# match the names to "y"  "occ.covs" "det.covs" "coords" 
data_list <- list(y = transposed_array, # Historias de detección
                  occ.covs = sitecovs, # covs de sitio
                  det.covs  = list(effort = DetHist_list[[1]]$effort),
                  coords = st_coordinates(data_full_sf_UTM)
                  )  # agregamos el esfuerzo de muestreo como covariable de observación

Running the model

We let spOccupancy set the initial values by default based on the prior distributions.

Code
# Running the model

# 3. 1 Modelo multi-especie  -----------------------------------------

# 2. Model fitting --------------------------------------------------------
# Fit a non-spatial, multi-species occupancy model. 
out.null <- msPGOcc(occ.formula = ~ scale(elev) +
                               scale(border_dist) + 
                               scale(FLII) , 
               det.formula = ~ scale(effort) , # Ordinal.day + I(Ordinal.day^2) + Year
                 data = data_list, 
                 n.samples = 6000, 
                 n.thin = 10, 
                 n.burn = 1000, 
                 n.chains = 3,
                 n.report = 1000);beep(sound = 4)
----------------------------------------
    Preparing to run the model
----------------------------------------
No prior specified for beta.comm.normal.
Setting prior mean to 0 and prior variance to 2.72
No prior specified for alpha.comm.normal.
Setting prior mean to 0 and prior variance to 2.72
No prior specified for tau.sq.beta.ig.
Setting prior shape to 0.1 and prior scale to 0.1
No prior specified for tau.sq.alpha.ig.
Setting prior shape to 0.1 and prior scale to 0.1
z is not specified in initial values.
Setting initial values based on observed data
beta.comm is not specified in initial values.
Setting initial values to random values from the prior distribution
alpha.comm is not specified in initial values.
Setting initial values to random values from the prior distribution
tau.sq.beta is not specified in initial values.
Setting initial values to random values between 0.5 and 10
tau.sq.alpha is not specified in initial values.
Setting to initial values to random values between 0.5 and 10
beta is not specified in initial values.
Setting initial values to random values from the community-level normal distribution
alpha is not specified in initial values.
Setting initial values to random values from the community-level normal distribution
----------------------------------------
    Model description
----------------------------------------
Multi-species Occupancy Model with Polya-Gamma latent
variable fit with 102 sites and 19 species.

Samples per Chain: 6000 
Burn-in: 1000 
Thinning Rate: 10 
Number of Chains: 3 
Total Posterior Samples: 1500 

Source compiled with OpenMP support and model fit using 1 thread(s).

----------------------------------------
    Chain 1
----------------------------------------
Sampling ... 
Sampled: 1000 of 6000, 16.67%
-------------------------------------------------
Sampled: 2000 of 6000, 33.33%
-------------------------------------------------
Sampled: 3000 of 6000, 50.00%
-------------------------------------------------
Sampled: 4000 of 6000, 66.67%
-------------------------------------------------
Sampled: 5000 of 6000, 83.33%
-------------------------------------------------
Sampled: 6000 of 6000, 100.00%
----------------------------------------
    Chain 2
----------------------------------------
Sampling ... 
Sampled: 1000 of 6000, 16.67%
-------------------------------------------------
Sampled: 2000 of 6000, 33.33%
-------------------------------------------------
Sampled: 3000 of 6000, 50.00%
-------------------------------------------------
Sampled: 4000 of 6000, 66.67%
-------------------------------------------------
Sampled: 5000 of 6000, 83.33%
-------------------------------------------------
Sampled: 6000 of 6000, 100.00%
----------------------------------------
    Chain 3
----------------------------------------
Sampling ... 
Sampled: 1000 of 6000, 16.67%
-------------------------------------------------
Sampled: 2000 of 6000, 33.33%
-------------------------------------------------
Sampled: 3000 of 6000, 50.00%
-------------------------------------------------
Sampled: 4000 of 6000, 66.67%
-------------------------------------------------
Sampled: 5000 of 6000, 83.33%
-------------------------------------------------
Sampled: 6000 of 6000, 100.00%
Code
summary(out.null, level = 'community')

Call:
msPGOcc(occ.formula = ~scale(elev) + scale(border_dist) + scale(FLII), 
    det.formula = ~scale(effort), data = data_list, n.samples = 6000, 
    n.report = 1000, n.burn = 1000, n.thin = 10, n.chains = 3)

Samples per Chain: 6000
Burn-in: 1000
Thinning Rate: 10
Number of Chains: 3
Total Posterior Samples: 1500
Run Time (min): 0.9908

----------------------------------------
    Community Level
----------------------------------------
Occurrence Means (logit scale): 
                      Mean     SD    2.5%     50%   97.5%   Rhat  ESS
(Intercept)        -1.5978 0.3712 -2.2998 -1.5959 -0.9215 1.0134  111
scale(elev)         0.0131 0.1345 -0.2433  0.0136  0.2864 1.0152 1025
scale(border_dist) -0.0703 0.1533 -0.3646 -0.0673  0.2181 1.0028  940
scale(FLII)         0.4767 0.1757  0.1484  0.4710  0.8424 1.0095  982

Occurrence Variances (logit scale): 
                     Mean     SD   2.5%    50%  97.5%   Rhat ESS
(Intercept)        0.9101 0.5864 0.1118 0.8184 2.2673 1.0033 210
scale(elev)        0.1199 0.0841 0.0291 0.0976 0.3377 1.0060 982
scale(border_dist) 0.1581 0.1312 0.0356 0.1263 0.4466 1.0134 840
scale(FLII)        0.1901 0.1646 0.0343 0.1400 0.6505 1.0055 746

Detection Means (logit scale): 
                 Mean     SD    2.5%     50%   97.5%   Rhat ESS
(Intercept)   -2.1370 0.3541 -2.9021 -2.0928 -1.5572 1.0117 133
scale(effort)  1.0522 0.1905  0.6772  1.0474  1.4404 1.0050 958

Detection Variances (logit scale): 
                Mean     SD   2.5%    50%  97.5%   Rhat ESS
(Intercept)   0.7347 0.6089 0.0730 0.5737 2.2869 1.0201 110
scale(effort) 0.1930 0.1645 0.0348 0.1451 0.6217 1.0319 762
Code
# Fit a non-spatial, Latent Factor Multi-Species Occupancy Model. 
  out.lfMs <- msPGOcc(occ.formula = ~ scale(elev) +
                               scale(border_dist) + 
                               scale(FLII) , 
               det.formula = ~ scale(effort), # Ordinal.day + I(Ordinal.day^2) + Year
                 data = data_list, 
                 n.omp.threads = 6,
                 n.samples = 6000, 
                 n.factors = 5, # balance of rare sp. and run time
                 n.thin = 10, 
                 n.burn = 1000, 
                 n.chains = 3,
                 n.report = 1000);beep(sound = 4)
----------------------------------------
    Preparing to run the model
----------------------------------------
Warning in msPGOcc(occ.formula = ~scale(elev) + scale(border_dist) +
scale(FLII), : 'n.factors' is not an argument
No prior specified for beta.comm.normal.
Setting prior mean to 0 and prior variance to 2.72
No prior specified for alpha.comm.normal.
Setting prior mean to 0 and prior variance to 2.72
No prior specified for tau.sq.beta.ig.
Setting prior shape to 0.1 and prior scale to 0.1
No prior specified for tau.sq.alpha.ig.
Setting prior shape to 0.1 and prior scale to 0.1
z is not specified in initial values.
Setting initial values based on observed data
beta.comm is not specified in initial values.
Setting initial values to random values from the prior distribution
alpha.comm is not specified in initial values.
Setting initial values to random values from the prior distribution
tau.sq.beta is not specified in initial values.
Setting initial values to random values between 0.5 and 10
tau.sq.alpha is not specified in initial values.
Setting to initial values to random values between 0.5 and 10
beta is not specified in initial values.
Setting initial values to random values from the community-level normal distribution
alpha is not specified in initial values.
Setting initial values to random values from the community-level normal distribution
----------------------------------------
    Model description
----------------------------------------
Multi-species Occupancy Model with Polya-Gamma latent
variable fit with 102 sites and 19 species.

Samples per Chain: 6000 
Burn-in: 1000 
Thinning Rate: 10 
Number of Chains: 3 
Total Posterior Samples: 1500 

Source compiled with OpenMP support and model fit using 6 thread(s).

----------------------------------------
    Chain 1
----------------------------------------
Sampling ... 
Sampled: 1000 of 6000, 16.67%
-------------------------------------------------
Sampled: 2000 of 6000, 33.33%
-------------------------------------------------
Sampled: 3000 of 6000, 50.00%
-------------------------------------------------
Sampled: 4000 of 6000, 66.67%
-------------------------------------------------
Sampled: 5000 of 6000, 83.33%
-------------------------------------------------
Sampled: 6000 of 6000, 100.00%
----------------------------------------
    Chain 2
----------------------------------------
Sampling ... 
Sampled: 1000 of 6000, 16.67%
-------------------------------------------------
Sampled: 2000 of 6000, 33.33%
-------------------------------------------------
Sampled: 3000 of 6000, 50.00%
-------------------------------------------------
Sampled: 4000 of 6000, 66.67%
-------------------------------------------------
Sampled: 5000 of 6000, 83.33%
-------------------------------------------------
Sampled: 6000 of 6000, 100.00%
----------------------------------------
    Chain 3
----------------------------------------
Sampling ... 
Sampled: 1000 of 6000, 16.67%
-------------------------------------------------
Sampled: 2000 of 6000, 33.33%
-------------------------------------------------
Sampled: 3000 of 6000, 50.00%
-------------------------------------------------
Sampled: 4000 of 6000, 66.67%
-------------------------------------------------
Sampled: 5000 of 6000, 83.33%
-------------------------------------------------
Sampled: 6000 of 6000, 100.00%
Code
summary(out.lfMs, level = 'community')

Call:
msPGOcc(occ.formula = ~scale(elev) + scale(border_dist) + scale(FLII), 
    det.formula = ~scale(effort), data = data_list, n.samples = 6000, 
    n.omp.threads = 6, n.report = 1000, n.burn = 1000, n.thin = 10, 
    n.chains = 3, n.factors = 5)

Samples per Chain: 6000
Burn-in: 1000
Thinning Rate: 10
Number of Chains: 3
Total Posterior Samples: 1500
Run Time (min): 1.0313

----------------------------------------
    Community Level
----------------------------------------
Occurrence Means (logit scale): 
                      Mean     SD    2.5%     50%   97.5%   Rhat  ESS
(Intercept)        -1.4102 0.3776 -2.1855 -1.3748 -0.7779 1.1323   93
scale(elev)         0.0082 0.1433 -0.2636  0.0064  0.3049 1.0022 1000
scale(border_dist) -0.0669 0.1515 -0.3478 -0.0684  0.2271 1.0006 1061
scale(FLII)         0.4777 0.1705  0.1623  0.4775  0.8251 1.0161  901

Occurrence Variances (logit scale): 
                     Mean     SD   2.5%    50%  97.5%   Rhat  ESS
(Intercept)        0.6854 0.5553 0.0559 0.5567 1.9962 1.1128  165
scale(elev)        0.1237 0.0944 0.0285 0.0998 0.3695 1.0093  948
scale(border_dist) 0.1601 0.1230 0.0364 0.1244 0.4795 1.0184 1084
scale(FLII)        0.1828 0.1774 0.0332 0.1301 0.5963 1.0006  729

Detection Means (logit scale): 
                 Mean     SD    2.5%     50%  97.5%   Rhat ESS
(Intercept)   -2.2875 0.3816 -3.0606 -2.2659 -1.622 1.0564 137
scale(effort)  1.0503 0.1944  0.6781  1.0446  1.440 1.0049 682

Detection Variances (logit scale): 
                Mean     SD   2.5%    50%  97.5%   Rhat ESS
(Intercept)   1.0339 0.7292 0.1215 0.8953 2.8374 1.0476 118
scale(effort) 0.1929 0.1751 0.0320 0.1425 0.6519 1.0180 778
Code
# Fit a Spatial Factor Multi-Species Occupancy Model
# latent spatial factors.
tictoc::tic()
  out.sp <- sfMsPGOcc(occ.formula = ~ scale(elev) +
                               scale(border_dist) + 
                               scale(FLII) , 
               det.formula = ~ scale(effort), # Ordinal.day + I(Ordinal.day^2) + Year,            
                      data = data_list, 
                      n.omp.threads = 6,
                      n.batch = 600, 
                      batch.length = 25, # iter=600*25
                      n.thin = 10, 
                      n.burn = 5000, 
                      n.chains = 3,
                      NNGP = TRUE,
                      n.factors = 5, # balance of rare sp. and run time
                      n.neighbors = 15,
                      cov.model = 'exponential',
                      n.report = 1000);beep(sound = 4)
----------------------------------------
    Preparing to run the model
----------------------------------------
No prior specified for beta.comm.normal.
Setting prior mean to 0 and prior variance to 2.72
No prior specified for alpha.comm.normal.
Setting prior mean to 0 and prior variance to 2.72
No prior specified for tau.sq.beta.
Using an inverse-Gamma prior with prior shape 0.1 and prior scale 0.1
No prior specified for tau.sq.alpha.
Using an inverse-Gamma prior with prior shape 0.1 and prior scale 0.1
No prior specified for phi.unif.
Setting uniform bounds based on the range of observed spatial coordinates.
z is not specified in initial values.
Setting initial values based on observed data
beta.comm is not specified in initial values.
Setting initial values to random values from the prior distribution
alpha.comm is not specified in initial values.
Setting initial values to random values from the prior distribution
tau.sq.beta is not specified in initial values.
Setting initial values to random values between 0.5 and 10
tau.sq.alpha is not specified in initial values.
Setting initial values to random values between 0.5 and 10
beta is not specified in initial values.
Setting initial values to random values from the community-level normal distribution
alpha is not specified in initial values.
Setting initial values to random values from the community-level normal distribution
phi is not specified in initial values.
Setting initial value to random values from the prior distribution
lambda is not specified in initial values.
Setting initial values of the lower triangle to 0
----------------------------------------
    Building the neighbor list
----------------------------------------
----------------------------------------
Building the neighbors of neighbors list
----------------------------------------
----------------------------------------
    Model description
----------------------------------------
Spatial Factor NNGP Multi-species Occupancy Model with Polya-Gamma latent
variable fit with 102 sites and 19 species.

Samples per chain: 15000 (600 batches of length 25)
Burn-in: 5000 
Thinning Rate: 10 
Number of Chains: 3 
Total Posterior Samples: 3000 

Using the exponential spatial correlation model.

Using 5 latent spatial factors.
Using 15 nearest neighbors.

Source compiled with OpenMP support and model fit using 6 thread(s).

Adaptive Metropolis with target acceptance rate: 43.0
----------------------------------------
    Chain 1
----------------------------------------
Sampling ... 
Batch: 600 of 600, 100.00%
----------------------------------------
    Chain 2
----------------------------------------
Sampling ... 
Batch: 600 of 600, 100.00%
----------------------------------------
    Chain 3
----------------------------------------
Sampling ... 
Batch: 600 of 600, 100.00%
Code
tictoc::toc()
442.52 sec elapsed
Code
#########################
tictoc::tic()
  out.sp.cat <- sfMsPGOcc(occ.formula = ~ scale(elev) +
                               factor(in_AP) + 
                               scale(FLII) , 
               det.formula = ~ scale(effort), # Ordinal.day + I(Ordinal.day^2) + Year,            
                      data = data_list, 
                      n.omp.threads = 6,
                      n.batch = 600, 
                      batch.length = 25, # iter=600*25
                      n.thin = 10, 
                      n.burn = 5000, 
                      n.chains = 3,
                      NNGP = TRUE,
                      n.factors = 5, # balance of rare sp. and run time
                      n.neighbors = 15,
                      cov.model = 'exponential',
                      n.report = 1000);beep(sound = 4)
----------------------------------------
    Preparing to run the model
----------------------------------------
No prior specified for beta.comm.normal.
Setting prior mean to 0 and prior variance to 2.72
No prior specified for alpha.comm.normal.
Setting prior mean to 0 and prior variance to 2.72
No prior specified for tau.sq.beta.
Using an inverse-Gamma prior with prior shape 0.1 and prior scale 0.1
No prior specified for tau.sq.alpha.
Using an inverse-Gamma prior with prior shape 0.1 and prior scale 0.1
No prior specified for phi.unif.
Setting uniform bounds based on the range of observed spatial coordinates.
z is not specified in initial values.
Setting initial values based on observed data
beta.comm is not specified in initial values.
Setting initial values to random values from the prior distribution
alpha.comm is not specified in initial values.
Setting initial values to random values from the prior distribution
tau.sq.beta is not specified in initial values.
Setting initial values to random values between 0.5 and 10
tau.sq.alpha is not specified in initial values.
Setting initial values to random values between 0.5 and 10
beta is not specified in initial values.
Setting initial values to random values from the community-level normal distribution
alpha is not specified in initial values.
Setting initial values to random values from the community-level normal distribution
phi is not specified in initial values.
Setting initial value to random values from the prior distribution
lambda is not specified in initial values.
Setting initial values of the lower triangle to 0
----------------------------------------
    Building the neighbor list
----------------------------------------
----------------------------------------
Building the neighbors of neighbors list
----------------------------------------
----------------------------------------
    Model description
----------------------------------------
Spatial Factor NNGP Multi-species Occupancy Model with Polya-Gamma latent
variable fit with 102 sites and 19 species.

Samples per chain: 15000 (600 batches of length 25)
Burn-in: 5000 
Thinning Rate: 10 
Number of Chains: 3 
Total Posterior Samples: 3000 

Using the exponential spatial correlation model.

Using 5 latent spatial factors.
Using 15 nearest neighbors.

Source compiled with OpenMP support and model fit using 6 thread(s).

Adaptive Metropolis with target acceptance rate: 43.0
----------------------------------------
    Chain 1
----------------------------------------
Sampling ... 
Batch: 600 of 600, 100.00%
----------------------------------------
    Chain 2
----------------------------------------
Sampling ... 
Batch: 600 of 600, 100.00%
----------------------------------------
    Chain 3
----------------------------------------
Sampling ... 
Batch: 600 of 600, 100.00%
Code
tictoc::toc()
412.55 sec elapsed
Code
# tictoc::tic()
#   out.sp.gaus <- sfMsPGOcc(occ.formula = ~ scale(border_dist) , 
#                            det.formula = ~ scale(effort), # Ordinal.day + I(Ordinal.day^2) + Year,              
#                            data = data_list, 
#                            n.batch = 400, 
#                            batch.length = 25,
#                            n.thin = 5, 
#                            n.burn = 5000, 
#                            n.chains = 1,
#                            NNGP = TRUE,
#                            n.factors = 5,
#                            n.neighbors = 15,
#                            cov.model = 'gaussian',
#                            n.report = 100);beep(sound = 4)
# tictoc::toc()

# save the results to not run again
# save(out, file="C:/CodigoR/Occu_APs_all/blog/2025-10-15-analysis/result/result_2.R") # guardamos los resultados para no correr de nuevo
# save the results to not run again
# save(out.sp, file="C:/CodigoR/Occu_APs_all/blog/2025-10-15-analysis/result/sp_result_2.R") # guardamos los resultados para no correr de nuevo

# save(out.lfMs, file="C:/CodigoR/Occu_APs_all/blog/2025-10-15-analysis/result/lfms_result_2.R") # guardamos los resultados para no correr de nuevo


# load("C:/CodigoR/Occu_APs_all/blog/2025-10-15-analysis/result/sp_result_2.R")
# summary(fit.commu)

Model validation

We next perform a posterior predictive check using the Freeman-Tukey statistic grouping the data by sites. We summarize the posterior predictive check with the summary() function, which reports a Bayesian p-value. A Bayesian p-value that hovers around 0.5 indicates adequate model fit, while values less than 0.1 or greater than 0.9 suggest our model does not fit the data well (Hobbs and Hooten 2015). As always with a simulation-based analysis using MCMC, you will get numerically slightly different values.

Code
# 3. Model validation -----------------------------------------------------
# Perform a posterior predictive check to assess model fit. 
ppc.out <- ppcOcc(out.null, fit.stat = 'freeman-tukey', 
                  group = 1)
ppc.out.lfMs <- ppcOcc(out.lfMs, fit.stat = 'freeman-tukey', 
                  group = 1)
ppc.out.sp <- ppcOcc(out.sp, fit.stat = 'freeman-tukey',
                     group = 1)

# Calculate a Bayesian p-value as a simple measure of Goodness of Fit.
# Bayesian p-values between 0.1 and 0.9 indicate adequate model fit. 
summary(ppc.out)

Call:
ppcOcc(object = out.null, fit.stat = "freeman-tukey", group = 1)

Samples per Chain: 6000
Burn-in: 1000
Thinning Rate: 10
Number of Chains: 3
Total Posterior Samples: 1500

----------------------------------------
    Community Level
----------------------------------------
Bayesian p-value:  0.4594 

----------------------------------------
    Species Level
----------------------------------------
Atelocynus microtis Bayesian p-value: 0.2853
Cuniculus paca Bayesian p-value: 0.452
Dasyprocta punctata Bayesian p-value: 0.4833
Dasypus novemcinctus Bayesian p-value: 0.61
Didelphis marsupialis Bayesian p-value: 0.4993
Eira barbara Bayesian p-value: 0.4853
Leopardus pardalis Bayesian p-value: 0.538
Leopardus wiedii Bayesian p-value: 0.3933
Mazama americana Bayesian p-value: 0.4587
Mazama gouazoubira Bayesian p-value: 0.3287
Myrmecophaga tridactyla Bayesian p-value: 0.306
Nasua nasua Bayesian p-value: 0.354
Panthera onca Bayesian p-value: 0.754
Pecari tajacu Bayesian p-value: 0.4533
Priodontes maximus Bayesian p-value: 0.552
Procyon cancrivorus Bayesian p-value: 0.4973
Puma concolor Bayesian p-value: 0.3273
Tapirus terrestris Bayesian p-value: 0.5313
Tayassu pecari Bayesian p-value: 0.4193
Fit statistic:  freeman-tukey 
Code
summary(ppc.out.lfMs)

Call:
ppcOcc(object = out.lfMs, fit.stat = "freeman-tukey", group = 1)

Samples per Chain: 6000
Burn-in: 1000
Thinning Rate: 10
Number of Chains: 3
Total Posterior Samples: 1500

----------------------------------------
    Community Level
----------------------------------------
Bayesian p-value:  0.4383 

----------------------------------------
    Species Level
----------------------------------------
Atelocynus microtis Bayesian p-value: 0.214
Cuniculus paca Bayesian p-value: 0.4347
Dasyprocta punctata Bayesian p-value: 0.4913
Dasypus novemcinctus Bayesian p-value: 0.6107
Didelphis marsupialis Bayesian p-value: 0.4633
Eira barbara Bayesian p-value: 0.538
Leopardus pardalis Bayesian p-value: 0.56
Leopardus wiedii Bayesian p-value: 0.324
Mazama americana Bayesian p-value: 0.4613
Mazama gouazoubira Bayesian p-value: 0.304
Myrmecophaga tridactyla Bayesian p-value: 0.2333
Nasua nasua Bayesian p-value: 0.294
Panthera onca Bayesian p-value: 0.7193
Pecari tajacu Bayesian p-value: 0.4407
Priodontes maximus Bayesian p-value: 0.538
Procyon cancrivorus Bayesian p-value: 0.4793
Puma concolor Bayesian p-value: 0.2907
Tapirus terrestris Bayesian p-value: 0.494
Tayassu pecari Bayesian p-value: 0.4373
Fit statistic:  freeman-tukey 
Code
summary(ppc.out.sp)

Call:
ppcOcc(object = out.sp, fit.stat = "freeman-tukey", group = 1)

Samples per Chain: 15000
Burn-in: 5000
Thinning Rate: 10
Number of Chains: 3
Total Posterior Samples: 3000

----------------------------------------
    Community Level
----------------------------------------
Bayesian p-value:  0.4367 

----------------------------------------
    Species Level
----------------------------------------
Atelocynus microtis Bayesian p-value: 0.204
Cuniculus paca Bayesian p-value: 0.4573
Dasyprocta punctata Bayesian p-value: 0.653
Dasypus novemcinctus Bayesian p-value: 0.6017
Didelphis marsupialis Bayesian p-value: 0.4277
Eira barbara Bayesian p-value: 0.6077
Leopardus pardalis Bayesian p-value: 0.5553
Leopardus wiedii Bayesian p-value: 0.2713
Mazama americana Bayesian p-value: 0.4197
Mazama gouazoubira Bayesian p-value: 0.212
Myrmecophaga tridactyla Bayesian p-value: 0.1453
Nasua nasua Bayesian p-value: 0.2643
Panthera onca Bayesian p-value: 0.7177
Pecari tajacu Bayesian p-value: 0.5107
Priodontes maximus Bayesian p-value: 0.536
Procyon cancrivorus Bayesian p-value: 0.501
Puma concolor Bayesian p-value: 0.2487
Tapirus terrestris Bayesian p-value: 0.4983
Tayassu pecari Bayesian p-value: 0.4657
Fit statistic:  freeman-tukey 
Important

A Bayesian p-value that around 0.5 indicates adequate model fit, while values less than 0.1 or greater than 0.9 suggest our model does not fit the data well.

Fit plot

Code
#### fit plot
ppc.df <- data.frame(fit = ppc.out.sp$fit.y, 
                     fit.rep = ppc.out.sp$fit.y.rep, 
                     color = 'lightskyblue1')

ppc.df$color[ppc.df$fit.rep.1 > ppc.df$fit.1] <- 'lightsalmon'
plot(ppc.df$fit.1, ppc.df$fit.rep.1, bg = ppc.df$color, pch = 21, 
     ylab = 'Fit', xlab = 'True')
lines(ppc.df$fit.1, ppc.df$fit.1, col = 'black')

The most symmetrical, better fit!

The most symmetrical, better fit!

Model comparison

Code
# 4. Model comparison -----------------------------------------------------
# Compute Widely Applicable Information Criterion (WAIC)
# Lower values indicate better model fit. 
waicOcc(out.null)
       elpd          pD        WAIC 
-1121.32455    53.47446  2349.59803 
Code
waicOcc(out.lfMs)
       elpd          pD        WAIC 
-1121.80238    53.78068  2351.16612 
Code
waicOcc(out.sp)
     elpd        pD      WAIC 
-949.2893  180.0161 2258.6107 
Code
waicOcc(out.sp.cat)
     elpd        pD      WAIC 
-949.5264  180.4332 2259.9193 

Model comparison as table

Code
# Here we summarize the spatial factor loadings
# summary(out.sp$lambda.samples)

# Resultados --------------------------------------------------------------
# Extraemos lo tabla de valores estimados
modresult <- cbind(as.data.frame(waicOcc(out.null)),
                  as.data.frame(waicOcc(out.sp)),
                  as.data.frame(waicOcc(out.lfMs)),
                  as.data.frame(waicOcc(out.sp.cat))
                  #as.data.frame(waicOcc(out.sp.gaus))
                  )
# View(modresult)
modresult_sorted <- as.data.frame(t(modresult)) |> 
  arrange(WAIC) # sort by
  
DT::datatable(modresult_sorted)
Important

Lower values in WAIC indicate better model fit.

WAIC is the Widely Applicable Information Criterion (Watanabe 2010).

Posterior Summary

Code
# 5. Posterior summaries --------------------------------------------------
# Concise summary of main parameter estimates
summary(out.sp, level = 'community')

Call:
sfMsPGOcc(occ.formula = ~scale(elev) + scale(border_dist) + scale(FLII), 
    det.formula = ~scale(effort), data = data_list, cov.model = "exponential", 
    NNGP = TRUE, n.neighbors = 15, n.factors = 5, n.batch = 600, 
    batch.length = 25, n.omp.threads = 6, n.report = 1000, n.burn = 5000, 
    n.thin = 10, n.chains = 3)

Samples per Chain: 15000
Burn-in: 5000
Thinning Rate: 10
Number of Chains: 3
Total Posterior Samples: 3000
Run Time (min): 7.374

----------------------------------------
    Community Level
----------------------------------------
Occurrence Means (logit scale): 
                      Mean     SD    2.5%     50%   97.5%   Rhat  ESS
(Intercept)        -1.8822 0.4398 -2.8707 -1.8307 -1.1459 1.0219  172
scale(elev)         0.0275 0.2356 -0.4364  0.0271  0.5007 1.0014  925
scale(border_dist) -0.1668 0.2510 -0.6461 -0.1717  0.3236 1.0075 1004
scale(FLII)         0.6698 0.2708  0.1372  0.6616  1.2407 1.0012  885

Occurrence Variances (logit scale): 
                     Mean     SD   2.5%    50%  97.5%   Rhat  ESS
(Intercept)        0.7568 0.7979 0.0543 0.4827 2.9515 1.0303  194
scale(elev)        0.2242 0.2158 0.0359 0.1607 0.7703 1.0236 1228
scale(border_dist) 0.2672 0.2244 0.0394 0.2022 0.8844 1.0001 1243
scale(FLII)        0.3318 0.3571 0.0392 0.2241 1.2539 1.0138  854

Detection Means (logit scale): 
                 Mean     SD    2.5%     50%   97.5%   Rhat  ESS
(Intercept)   -2.4411 0.3548 -3.1559 -2.4392 -1.7576 1.0217  298
scale(effort)  1.0623 0.2010  0.6941  1.0541  1.4869 1.0041 1454

Detection Variances (logit scale): 
                Mean     SD   2.5%    50%  97.5%   Rhat  ESS
(Intercept)   1.2981 0.7211 0.2960 1.1677 3.0346 1.0077  379
scale(effort) 0.2024 0.1750 0.0351 0.1494 0.6865 1.0033 1426

----------------------------------------
    Spatial Covariance
----------------------------------------
        Mean     SD  2.5%    50%  97.5%   Rhat  ESS
phi-1 0.0048 0.0033 7e-04 0.0039 0.0112 1.0035  770
phi-2 0.0051 0.0034 6e-04 0.0046 0.0113 1.0085  947
phi-3 0.0056 0.0033 7e-04 0.0054 0.0112 1.0136 1202
phi-4 0.0059 0.0033 8e-04 0.0058 0.0113 1.0039 1595
phi-5 0.0055 0.0034 3e-04 0.0054 0.0113 1.0376  346
Code
summary(out.sp, level = 'species')

Call:
sfMsPGOcc(occ.formula = ~scale(elev) + scale(border_dist) + scale(FLII), 
    det.formula = ~scale(effort), data = data_list, cov.model = "exponential", 
    NNGP = TRUE, n.neighbors = 15, n.factors = 5, n.batch = 600, 
    batch.length = 25, n.omp.threads = 6, n.report = 1000, n.burn = 5000, 
    n.thin = 10, n.chains = 3)

Samples per Chain: 15000
Burn-in: 5000
Thinning Rate: 10
Number of Chains: 3
Total Posterior Samples: 3000
Run Time (min): 7.374

----------------------------------------
    Species Level
----------------------------------------
Occurrence (logit scale): 
                                              Mean     SD    2.5%     50%
(Intercept)-Atelocynus microtis            -2.4248 0.7888 -4.0237 -2.3635
(Intercept)-Cuniculus paca                 -1.6327 0.4637 -2.5541 -1.6271
(Intercept)-Dasyprocta punctata            -1.2489 0.5331 -2.2716 -1.2659
(Intercept)-Dasypus novemcinctus           -1.9086 0.8565 -3.7810 -1.8260
(Intercept)-Didelphis marsupialis          -1.7132 0.6312 -2.9455 -1.7112
(Intercept)-Eira barbara                   -2.4254 1.1651 -5.2279 -2.1226
(Intercept)-Leopardus pardalis             -1.0627 0.5527 -2.0721 -1.0940
(Intercept)-Leopardus wiedii               -2.1964 0.9194 -4.2625 -2.0650
(Intercept)-Mazama americana               -1.7172 0.4974 -2.7749 -1.6913
(Intercept)-Mazama gouazoubira             -2.0897 0.8736 -3.9795 -1.9982
(Intercept)-Myrmecophaga tridactyla        -2.2657 0.9198 -4.3058 -2.1433
(Intercept)-Nasua nasua                    -2.3442 1.0053 -4.7004 -2.1741
(Intercept)-Panthera onca                  -1.5283 0.7558 -3.0104 -1.5287
(Intercept)-Pecari tajacu                  -1.5730 0.5248 -2.6135 -1.5722
(Intercept)-Priodontes maximus             -2.1483 0.9805 -4.3693 -1.9739
(Intercept)-Procyon cancrivorus            -2.2675 1.0401 -4.6563 -2.0602
(Intercept)-Puma concolor                  -2.4844 1.0522 -4.8196 -2.2841
(Intercept)-Tapirus terrestris             -1.4783 0.4872 -2.4929 -1.4644
(Intercept)-Tayassu pecari                 -1.8036 0.5115 -2.9153 -1.7721
scale(elev)-Atelocynus microtis             0.0217 0.3896 -0.7290  0.0219
scale(elev)-Cuniculus paca                 -0.1911 0.3469 -0.9149 -0.1866
scale(elev)-Dasyprocta punctata            -0.1559 0.3905 -0.9281 -0.1479
scale(elev)-Dasypus novemcinctus           -0.0762 0.4609 -1.0367 -0.0612
scale(elev)-Didelphis marsupialis           0.3920 0.4376 -0.3590  0.3564
scale(elev)-Eira barbara                    0.1225 0.5200 -0.8644  0.1040
scale(elev)-Leopardus pardalis             -0.2509 0.3785 -1.0014 -0.2478
scale(elev)-Leopardus wiedii                0.0829 0.4557 -0.7738  0.0631
scale(elev)-Mazama americana                0.0342 0.3644 -0.6713  0.0265
scale(elev)-Mazama gouazoubira             -0.1024 0.4539 -1.0569 -0.0957
scale(elev)-Myrmecophaga tridactyla        -0.1184 0.4518 -1.0987 -0.0998
scale(elev)-Nasua nasua                     0.1241 0.4609 -0.7638  0.1114
scale(elev)-Panthera onca                   0.1788 0.4544 -0.6628  0.1614
scale(elev)-Pecari tajacu                  -0.1404 0.4055 -1.0040 -0.1274
scale(elev)-Priodontes maximus              0.1748 0.4771 -0.7195  0.1458
scale(elev)-Procyon cancrivorus            -0.1495 0.5050 -1.2394 -0.1047
scale(elev)-Puma concolor                   0.2895 0.4820 -0.5874  0.2529
scale(elev)-Tapirus terrestris              0.3653 0.3731 -0.3241  0.3510
scale(elev)-Tayassu pecari                 -0.0656 0.3590 -0.7560 -0.0662
scale(border_dist)-Atelocynus microtis     -0.3836 0.4812 -1.4422 -0.3615
scale(border_dist)-Cuniculus paca          -0.2510 0.3758 -1.0048 -0.2512
scale(border_dist)-Dasyprocta punctata      0.0391 0.4082 -0.7367  0.0288
scale(border_dist)-Dasypus novemcinctus    -0.0471 0.5023 -0.9945 -0.0641
scale(border_dist)-Didelphis marsupialis   -0.3917 0.4491 -1.3391 -0.3706
scale(border_dist)-Eira barbara            -0.1971 0.5255 -1.2911 -0.1999
scale(border_dist)-Leopardus pardalis      -0.2752 0.3900 -1.0571 -0.2666
scale(border_dist)-Leopardus wiedii        -0.1132 0.4785 -1.0685 -0.1269
scale(border_dist)-Mazama americana         0.1268 0.4106 -0.6237  0.1174
scale(border_dist)-Mazama gouazoubira      -0.0619 0.4878 -0.9675 -0.0791
scale(border_dist)-Myrmecophaga tridactyla  0.2139 0.5360 -0.7255  0.1734
scale(border_dist)-Nasua nasua             -0.1737 0.5107 -1.2326 -0.1816
scale(border_dist)-Panthera onca           -0.4358 0.5220 -1.5720 -0.4133
scale(border_dist)-Pecari tajacu            0.2000 0.4551 -0.6332  0.1712
scale(border_dist)-Priodontes maximus      -0.0654 0.5252 -1.0653 -0.0857
scale(border_dist)-Procyon cancrivorus     -0.0533 0.5027 -0.9925 -0.0845
scale(border_dist)-Puma concolor           -0.2925 0.5173 -1.4395 -0.2631
scale(border_dist)-Tapirus terrestris      -0.5179 0.4250 -1.4233 -0.4930
scale(border_dist)-Tayassu pecari          -0.4997 0.4132 -1.3823 -0.4875
scale(FLII)-Atelocynus microtis             0.7302 0.5343 -0.2619  0.6997
scale(FLII)-Cuniculus paca                  0.4940 0.3989 -0.3134  0.4962
scale(FLII)-Dasyprocta punctata             0.6604 0.4142 -0.1546  0.6504
scale(FLII)-Dasypus novemcinctus            0.3642 0.5306 -0.8186  0.3958
scale(FLII)-Didelphis marsupialis           0.9957 0.5714  0.0473  0.9312
scale(FLII)-Eira barbara                    0.6589 0.5901 -0.5587  0.6694
scale(FLII)-Leopardus pardalis              0.8372 0.4217  0.0635  0.8166
scale(FLII)-Leopardus wiedii                0.8183 0.5651 -0.1953  0.7778
scale(FLII)-Mazama americana                0.6656 0.3994 -0.0929  0.6584
scale(FLII)-Mazama gouazoubira              0.2770 0.5644 -0.9600  0.3173
scale(FLII)-Myrmecophaga tridactyla         0.3088 0.5514 -0.8757  0.3451
scale(FLII)-Nasua nasua                     0.7476 0.5910 -0.3370  0.7094
scale(FLII)-Panthera onca                   0.8266 0.5590 -0.1737  0.7839
scale(FLII)-Pecari tajacu                   0.6357 0.4297 -0.2473  0.6330
scale(FLII)-Priodontes maximus              0.3841 0.5630 -0.7816  0.4284
scale(FLII)-Procyon cancrivorus             0.6899 0.5852 -0.4162  0.6674
scale(FLII)-Puma concolor                   0.7091 0.5668 -0.3744  0.6876
scale(FLII)-Tapirus terrestris              1.2005 0.5824  0.2897  1.1126
scale(FLII)-Tayassu pecari                  0.9190 0.4822  0.0602  0.8762
                                             97.5%   Rhat  ESS
(Intercept)-Atelocynus microtis            -1.0709 1.0130  218
(Intercept)-Cuniculus paca                 -0.6946 1.0111 1008
(Intercept)-Dasyprocta punctata            -0.1639 1.0026  972
(Intercept)-Dasypus novemcinctus           -0.3423 1.0172  342
(Intercept)-Didelphis marsupialis          -0.4108 1.0070  867
(Intercept)-Eira barbara                   -0.7405 1.0110  172
(Intercept)-Leopardus pardalis              0.1107 1.0018 1042
(Intercept)-Leopardus wiedii               -0.6878 1.0199  220
(Intercept)-Mazama americana               -0.7736 1.0034  849
(Intercept)-Mazama gouazoubira             -0.5407 1.0356  310
(Intercept)-Myrmecophaga tridactyla        -0.7487 1.0205  270
(Intercept)-Nasua nasua                    -0.7363 1.0124  180
(Intercept)-Panthera onca                   0.0585 1.0119  643
(Intercept)-Pecari tajacu                  -0.5424 1.0010 1398
(Intercept)-Priodontes maximus             -0.5061 1.0221  158
(Intercept)-Procyon cancrivorus            -0.6677 1.0219  240
(Intercept)-Puma concolor                  -0.8936 1.0410  201
(Intercept)-Tapirus terrestris             -0.5414 1.0163 1499
(Intercept)-Tayassu pecari                 -0.8835 1.0014 1010
scale(elev)-Atelocynus microtis             0.8159 1.0013 1780
scale(elev)-Cuniculus paca                  0.4823 1.0009 1609
scale(elev)-Dasyprocta punctata             0.5842 1.0028 1599
scale(elev)-Dasypus novemcinctus            0.8075 1.0029 1673
scale(elev)-Didelphis marsupialis           1.3508 1.0031 1646
scale(elev)-Eira barbara                    1.1688 1.0038 1646
scale(elev)-Leopardus pardalis              0.4770 1.0002 1816
scale(elev)-Leopardus wiedii                1.0232 1.0058 1425
scale(elev)-Mazama americana                0.7688 1.0020 1622
scale(elev)-Mazama gouazoubira              0.7787 1.0010 1903
scale(elev)-Myrmecophaga tridactyla         0.7126 1.0012 1501
scale(elev)-Nasua nasua                     1.0766 1.0062 1630
scale(elev)-Panthera onca                   1.1151 1.0114 1845
scale(elev)-Pecari tajacu                   0.6118 1.0001 1711
scale(elev)-Priodontes maximus              1.1695 1.0015 1344
scale(elev)-Procyon cancrivorus             0.7344 1.0042 1388
scale(elev)-Puma concolor                   1.3429 1.0039 1566
scale(elev)-Tapirus terrestris              1.1611 1.0040 1631
scale(elev)-Tayassu pecari                  0.6250 1.0009 1847
scale(border_dist)-Atelocynus microtis      0.4649 1.0031 1705
scale(border_dist)-Cuniculus paca           0.4806 1.0003 1853
scale(border_dist)-Dasyprocta punctata      0.8814 1.0077 1427
scale(border_dist)-Dasypus novemcinctus     1.0114 1.0061 1506
scale(border_dist)-Didelphis marsupialis    0.4371 1.0015 1732
scale(border_dist)-Eira barbara             0.8710 1.0029 1420
scale(border_dist)-Leopardus pardalis       0.4811 0.9997 1986
scale(border_dist)-Leopardus wiedii         0.8868 1.0020 2024
scale(border_dist)-Mazama americana         0.9871 1.0028 1601
scale(border_dist)-Mazama gouazoubira       0.9633 1.0081 1898
scale(border_dist)-Myrmecophaga tridactyla  1.4010 1.0016 1086
scale(border_dist)-Nasua nasua              0.8534 1.0043 1568
scale(border_dist)-Panthera onca            0.5465 1.0047 1550
scale(border_dist)-Pecari tajacu            1.1626 1.0033 1508
scale(border_dist)-Priodontes maximus       1.0351 1.0013 1357
scale(border_dist)-Procyon cancrivorus      1.0485 1.0024 1333
scale(border_dist)-Puma concolor            0.6760 0.9999 1913
scale(border_dist)-Tapirus terrestris       0.2727 1.0055 1748
scale(border_dist)-Tayassu pecari           0.2882 1.0013 2142
scale(FLII)-Atelocynus microtis             1.9010 1.0031 1446
scale(FLII)-Cuniculus paca                  1.2961 1.0024 1852
scale(FLII)-Dasyprocta punctata             1.5246 1.0070 1647
scale(FLII)-Dasypus novemcinctus            1.3185 1.0020 1332
scale(FLII)-Didelphis marsupialis           2.3530 1.0012 1433
scale(FLII)-Eira barbara                    1.8795 1.0112 1441
scale(FLII)-Leopardus pardalis              1.7301 0.9999 1810
scale(FLII)-Leopardus wiedii                2.0875 1.0029 1590
scale(FLII)-Mazama americana                1.4808 1.0008 1595
scale(FLII)-Mazama gouazoubira              1.2766 1.0066 1157
scale(FLII)-Myrmecophaga tridactyla         1.2610 1.0062 1125
scale(FLII)-Nasua nasua                     2.0207 1.0042 1447
scale(FLII)-Panthera onca                   2.0855 1.0055 1485
scale(FLII)-Pecari tajacu                   1.4836 1.0034 1980
scale(FLII)-Priodontes maximus              1.4263 1.0015 1447
scale(FLII)-Procyon cancrivorus             1.9068 1.0027 1249
scale(FLII)-Puma concolor                   1.8644 1.0024 1564
scale(FLII)-Tapirus terrestris              2.6018 1.0017 1295
scale(FLII)-Tayassu pecari                  1.9776 1.0005 1505

Detection (logit scale): 
                                         Mean     SD    2.5%     50%   97.5%
(Intercept)-Atelocynus microtis       -2.4490 0.7017 -3.7708 -2.4784 -1.1000
(Intercept)-Cuniculus paca            -1.5209 0.3427 -2.1896 -1.5203 -0.8852
(Intercept)-Dasyprocta punctata       -1.6274 0.2968 -2.2389 -1.6197 -1.0680
(Intercept)-Dasypus novemcinctus      -3.4240 0.6762 -4.7220 -3.4452 -1.9748
(Intercept)-Didelphis marsupialis     -2.3149 0.3969 -3.1013 -2.3067 -1.5804
(Intercept)-Eira barbara              -3.9677 1.0028 -5.8783 -4.0269 -1.7891
(Intercept)-Leopardus pardalis        -1.5363 0.2853 -2.1340 -1.5236 -1.0124
(Intercept)-Leopardus wiedii          -3.1563 0.6953 -4.4153 -3.1968 -1.7375
(Intercept)-Mazama americana          -1.2077 0.2968 -1.8012 -1.2016 -0.6383
(Intercept)-Mazama gouazoubira        -2.9011 0.6250 -4.0649 -2.9327 -1.6197
(Intercept)-Myrmecophaga tridactyla   -2.6588 0.6572 -3.8575 -2.7017 -1.2791
(Intercept)-Nasua nasua               -3.2327 0.7564 -4.6074 -3.2893 -1.6617
(Intercept)-Panthera onca             -2.9739 0.4646 -3.8463 -2.9718 -2.0245
(Intercept)-Pecari tajacu             -1.6325 0.3100 -2.2630 -1.6186 -1.0384
(Intercept)-Priodontes maximus        -3.5519 0.7693 -4.9753 -3.5939 -1.9334
(Intercept)-Procyon cancrivorus       -3.6960 0.8427 -5.2249 -3.7643 -1.9133
(Intercept)-Puma concolor             -3.1691 0.7757 -4.5788 -3.2209 -1.5613
(Intercept)-Tapirus terrestris        -1.3467 0.2614 -1.8714 -1.3393 -0.8532
(Intercept)-Tayassu pecari            -1.2188 0.2825 -1.8026 -1.2128 -0.6814
scale(effort)-Atelocynus microtis      0.7761 0.4064 -0.0537  0.7890  1.5566
scale(effort)-Cuniculus paca           1.0826 0.3542  0.4432  1.0543  1.8263
scale(effort)-Dasyprocta punctata      1.2949 0.4001  0.6518  1.2466  2.2309
scale(effort)-Dasypus novemcinctus     1.0534 0.4336  0.2205  1.0395  2.0063
scale(effort)-Didelphis marsupialis    1.2216 0.4172  0.5300  1.1822  2.1753
scale(effort)-Eira barbara             0.9418 0.4435  0.0269  0.9343  1.8512
scale(effort)-Leopardus pardalis       1.4124 0.4153  0.7697  1.3567  2.3931
scale(effort)-Leopardus wiedii         1.0841 0.4309  0.3029  1.0652  2.0157
scale(effort)-Mazama americana         1.1436 0.3339  0.5786  1.1055  1.9026
scale(effort)-Mazama gouazoubira       0.7427 0.4017 -0.0848  0.7514  1.5169
scale(effort)-Myrmecophaga tridactyla  0.8043 0.4047  0.0051  0.8150  1.5764
scale(effort)-Nasua nasua              1.0703 0.4322  0.2437  1.0460  2.0092
scale(effort)-Panthera onca            1.0945 0.4260  0.3259  1.0683  2.0353
scale(effort)-Pecari tajacu            1.3074 0.4054  0.6389  1.2622  2.2421
scale(effort)-Priodontes maximus       1.0604 0.4412  0.2105  1.0463  2.0156
scale(effort)-Procyon cancrivorus      0.9859 0.4367  0.1154  0.9728  1.8811
scale(effort)-Puma concolor            1.0631 0.4471  0.2262  1.0468  2.0154
scale(effort)-Tapirus terrestris       0.9515 0.2795  0.4430  0.9344  1.5384
scale(effort)-Tayassu pecari           1.0901 0.3106  0.5372  1.0704  1.7596
                                        Rhat  ESS
(Intercept)-Atelocynus microtis       1.0128  449
(Intercept)-Cuniculus paca            1.0062 2353
(Intercept)-Dasyprocta punctata       1.0004 2292
(Intercept)-Dasypus novemcinctus      1.0061  456
(Intercept)-Didelphis marsupialis     1.0051 1520
(Intercept)-Eira barbara              1.0230  208
(Intercept)-Leopardus pardalis        1.0052 1982
(Intercept)-Leopardus wiedii          1.0378  295
(Intercept)-Mazama americana          1.0025 2759
(Intercept)-Mazama gouazoubira        1.0278  219
(Intercept)-Myrmecophaga tridactyla   1.0127  444
(Intercept)-Nasua nasua               1.0205  261
(Intercept)-Panthera onca             1.0007 1125
(Intercept)-Pecari tajacu             1.0000 2344
(Intercept)-Priodontes maximus        1.0105  324
(Intercept)-Procyon cancrivorus       1.0080  318
(Intercept)-Puma concolor             1.0332  178
(Intercept)-Tapirus terrestris        1.0046 2598
(Intercept)-Tayassu pecari            0.9999 2688
scale(effort)-Atelocynus microtis     1.0071 2351
scale(effort)-Cuniculus paca          1.0008 2531
scale(effort)-Dasyprocta punctata     1.0027 1824
scale(effort)-Dasypus novemcinctus    1.0067 2085
scale(effort)-Didelphis marsupialis   1.0025 1868
scale(effort)-Eira barbara            1.0036 2210
scale(effort)-Leopardus pardalis      1.0123 1436
scale(effort)-Leopardus wiedii        1.0028 2911
scale(effort)-Mazama americana        1.0020 2454
scale(effort)-Mazama gouazoubira      1.0004 2413
scale(effort)-Myrmecophaga tridactyla 1.0005 2589
scale(effort)-Nasua nasua             1.0071 2108
scale(effort)-Panthera onca           1.0077 1882
scale(effort)-Pecari tajacu           1.0031 1521
scale(effort)-Priodontes maximus      1.0023 2058
scale(effort)-Procyon cancrivorus     0.9999 2441
scale(effort)-Puma concolor           1.0020 2388
scale(effort)-Tapirus terrestris      1.0027 2759
scale(effort)-Tayassu pecari          1.0088 3071

----------------------------------------
    Spatial Covariance
----------------------------------------
        Mean     SD  2.5%    50%  97.5%   Rhat  ESS
phi-1 0.0048 0.0033 7e-04 0.0039 0.0112 1.0035  770
phi-2 0.0051 0.0034 6e-04 0.0046 0.0113 1.0085  947
phi-3 0.0056 0.0033 7e-04 0.0054 0.0112 1.0136 1202
phi-4 0.0059 0.0033 8e-04 0.0058 0.0113 1.0039 1595
phi-5 0.0055 0.0034 3e-04 0.0054 0.0113 1.0376  346
Code
summary(out.sp, level = 'both')

Call:
sfMsPGOcc(occ.formula = ~scale(elev) + scale(border_dist) + scale(FLII), 
    det.formula = ~scale(effort), data = data_list, cov.model = "exponential", 
    NNGP = TRUE, n.neighbors = 15, n.factors = 5, n.batch = 600, 
    batch.length = 25, n.omp.threads = 6, n.report = 1000, n.burn = 5000, 
    n.thin = 10, n.chains = 3)

Samples per Chain: 15000
Burn-in: 5000
Thinning Rate: 10
Number of Chains: 3
Total Posterior Samples: 3000
Run Time (min): 7.374

----------------------------------------
    Community Level
----------------------------------------
Occurrence Means (logit scale): 
                      Mean     SD    2.5%     50%   97.5%   Rhat  ESS
(Intercept)        -1.8822 0.4398 -2.8707 -1.8307 -1.1459 1.0219  172
scale(elev)         0.0275 0.2356 -0.4364  0.0271  0.5007 1.0014  925
scale(border_dist) -0.1668 0.2510 -0.6461 -0.1717  0.3236 1.0075 1004
scale(FLII)         0.6698 0.2708  0.1372  0.6616  1.2407 1.0012  885

Occurrence Variances (logit scale): 
                     Mean     SD   2.5%    50%  97.5%   Rhat  ESS
(Intercept)        0.7568 0.7979 0.0543 0.4827 2.9515 1.0303  194
scale(elev)        0.2242 0.2158 0.0359 0.1607 0.7703 1.0236 1228
scale(border_dist) 0.2672 0.2244 0.0394 0.2022 0.8844 1.0001 1243
scale(FLII)        0.3318 0.3571 0.0392 0.2241 1.2539 1.0138  854

Detection Means (logit scale): 
                 Mean     SD    2.5%     50%   97.5%   Rhat  ESS
(Intercept)   -2.4411 0.3548 -3.1559 -2.4392 -1.7576 1.0217  298
scale(effort)  1.0623 0.2010  0.6941  1.0541  1.4869 1.0041 1454

Detection Variances (logit scale): 
                Mean     SD   2.5%    50%  97.5%   Rhat  ESS
(Intercept)   1.2981 0.7211 0.2960 1.1677 3.0346 1.0077  379
scale(effort) 0.2024 0.1750 0.0351 0.1494 0.6865 1.0033 1426

----------------------------------------
    Species Level
----------------------------------------
Occurrence (logit scale): 
                                              Mean     SD    2.5%     50%
(Intercept)-Atelocynus microtis            -2.4248 0.7888 -4.0237 -2.3635
(Intercept)-Cuniculus paca                 -1.6327 0.4637 -2.5541 -1.6271
(Intercept)-Dasyprocta punctata            -1.2489 0.5331 -2.2716 -1.2659
(Intercept)-Dasypus novemcinctus           -1.9086 0.8565 -3.7810 -1.8260
(Intercept)-Didelphis marsupialis          -1.7132 0.6312 -2.9455 -1.7112
(Intercept)-Eira barbara                   -2.4254 1.1651 -5.2279 -2.1226
(Intercept)-Leopardus pardalis             -1.0627 0.5527 -2.0721 -1.0940
(Intercept)-Leopardus wiedii               -2.1964 0.9194 -4.2625 -2.0650
(Intercept)-Mazama americana               -1.7172 0.4974 -2.7749 -1.6913
(Intercept)-Mazama gouazoubira             -2.0897 0.8736 -3.9795 -1.9982
(Intercept)-Myrmecophaga tridactyla        -2.2657 0.9198 -4.3058 -2.1433
(Intercept)-Nasua nasua                    -2.3442 1.0053 -4.7004 -2.1741
(Intercept)-Panthera onca                  -1.5283 0.7558 -3.0104 -1.5287
(Intercept)-Pecari tajacu                  -1.5730 0.5248 -2.6135 -1.5722
(Intercept)-Priodontes maximus             -2.1483 0.9805 -4.3693 -1.9739
(Intercept)-Procyon cancrivorus            -2.2675 1.0401 -4.6563 -2.0602
(Intercept)-Puma concolor                  -2.4844 1.0522 -4.8196 -2.2841
(Intercept)-Tapirus terrestris             -1.4783 0.4872 -2.4929 -1.4644
(Intercept)-Tayassu pecari                 -1.8036 0.5115 -2.9153 -1.7721
scale(elev)-Atelocynus microtis             0.0217 0.3896 -0.7290  0.0219
scale(elev)-Cuniculus paca                 -0.1911 0.3469 -0.9149 -0.1866
scale(elev)-Dasyprocta punctata            -0.1559 0.3905 -0.9281 -0.1479
scale(elev)-Dasypus novemcinctus           -0.0762 0.4609 -1.0367 -0.0612
scale(elev)-Didelphis marsupialis           0.3920 0.4376 -0.3590  0.3564
scale(elev)-Eira barbara                    0.1225 0.5200 -0.8644  0.1040
scale(elev)-Leopardus pardalis             -0.2509 0.3785 -1.0014 -0.2478
scale(elev)-Leopardus wiedii                0.0829 0.4557 -0.7738  0.0631
scale(elev)-Mazama americana                0.0342 0.3644 -0.6713  0.0265
scale(elev)-Mazama gouazoubira             -0.1024 0.4539 -1.0569 -0.0957
scale(elev)-Myrmecophaga tridactyla        -0.1184 0.4518 -1.0987 -0.0998
scale(elev)-Nasua nasua                     0.1241 0.4609 -0.7638  0.1114
scale(elev)-Panthera onca                   0.1788 0.4544 -0.6628  0.1614
scale(elev)-Pecari tajacu                  -0.1404 0.4055 -1.0040 -0.1274
scale(elev)-Priodontes maximus              0.1748 0.4771 -0.7195  0.1458
scale(elev)-Procyon cancrivorus            -0.1495 0.5050 -1.2394 -0.1047
scale(elev)-Puma concolor                   0.2895 0.4820 -0.5874  0.2529
scale(elev)-Tapirus terrestris              0.3653 0.3731 -0.3241  0.3510
scale(elev)-Tayassu pecari                 -0.0656 0.3590 -0.7560 -0.0662
scale(border_dist)-Atelocynus microtis     -0.3836 0.4812 -1.4422 -0.3615
scale(border_dist)-Cuniculus paca          -0.2510 0.3758 -1.0048 -0.2512
scale(border_dist)-Dasyprocta punctata      0.0391 0.4082 -0.7367  0.0288
scale(border_dist)-Dasypus novemcinctus    -0.0471 0.5023 -0.9945 -0.0641
scale(border_dist)-Didelphis marsupialis   -0.3917 0.4491 -1.3391 -0.3706
scale(border_dist)-Eira barbara            -0.1971 0.5255 -1.2911 -0.1999
scale(border_dist)-Leopardus pardalis      -0.2752 0.3900 -1.0571 -0.2666
scale(border_dist)-Leopardus wiedii        -0.1132 0.4785 -1.0685 -0.1269
scale(border_dist)-Mazama americana         0.1268 0.4106 -0.6237  0.1174
scale(border_dist)-Mazama gouazoubira      -0.0619 0.4878 -0.9675 -0.0791
scale(border_dist)-Myrmecophaga tridactyla  0.2139 0.5360 -0.7255  0.1734
scale(border_dist)-Nasua nasua             -0.1737 0.5107 -1.2326 -0.1816
scale(border_dist)-Panthera onca           -0.4358 0.5220 -1.5720 -0.4133
scale(border_dist)-Pecari tajacu            0.2000 0.4551 -0.6332  0.1712
scale(border_dist)-Priodontes maximus      -0.0654 0.5252 -1.0653 -0.0857
scale(border_dist)-Procyon cancrivorus     -0.0533 0.5027 -0.9925 -0.0845
scale(border_dist)-Puma concolor           -0.2925 0.5173 -1.4395 -0.2631
scale(border_dist)-Tapirus terrestris      -0.5179 0.4250 -1.4233 -0.4930
scale(border_dist)-Tayassu pecari          -0.4997 0.4132 -1.3823 -0.4875
scale(FLII)-Atelocynus microtis             0.7302 0.5343 -0.2619  0.6997
scale(FLII)-Cuniculus paca                  0.4940 0.3989 -0.3134  0.4962
scale(FLII)-Dasyprocta punctata             0.6604 0.4142 -0.1546  0.6504
scale(FLII)-Dasypus novemcinctus            0.3642 0.5306 -0.8186  0.3958
scale(FLII)-Didelphis marsupialis           0.9957 0.5714  0.0473  0.9312
scale(FLII)-Eira barbara                    0.6589 0.5901 -0.5587  0.6694
scale(FLII)-Leopardus pardalis              0.8372 0.4217  0.0635  0.8166
scale(FLII)-Leopardus wiedii                0.8183 0.5651 -0.1953  0.7778
scale(FLII)-Mazama americana                0.6656 0.3994 -0.0929  0.6584
scale(FLII)-Mazama gouazoubira              0.2770 0.5644 -0.9600  0.3173
scale(FLII)-Myrmecophaga tridactyla         0.3088 0.5514 -0.8757  0.3451
scale(FLII)-Nasua nasua                     0.7476 0.5910 -0.3370  0.7094
scale(FLII)-Panthera onca                   0.8266 0.5590 -0.1737  0.7839
scale(FLII)-Pecari tajacu                   0.6357 0.4297 -0.2473  0.6330
scale(FLII)-Priodontes maximus              0.3841 0.5630 -0.7816  0.4284
scale(FLII)-Procyon cancrivorus             0.6899 0.5852 -0.4162  0.6674
scale(FLII)-Puma concolor                   0.7091 0.5668 -0.3744  0.6876
scale(FLII)-Tapirus terrestris              1.2005 0.5824  0.2897  1.1126
scale(FLII)-Tayassu pecari                  0.9190 0.4822  0.0602  0.8762
                                             97.5%   Rhat  ESS
(Intercept)-Atelocynus microtis            -1.0709 1.0130  218
(Intercept)-Cuniculus paca                 -0.6946 1.0111 1008
(Intercept)-Dasyprocta punctata            -0.1639 1.0026  972
(Intercept)-Dasypus novemcinctus           -0.3423 1.0172  342
(Intercept)-Didelphis marsupialis          -0.4108 1.0070  867
(Intercept)-Eira barbara                   -0.7405 1.0110  172
(Intercept)-Leopardus pardalis              0.1107 1.0018 1042
(Intercept)-Leopardus wiedii               -0.6878 1.0199  220
(Intercept)-Mazama americana               -0.7736 1.0034  849
(Intercept)-Mazama gouazoubira             -0.5407 1.0356  310
(Intercept)-Myrmecophaga tridactyla        -0.7487 1.0205  270
(Intercept)-Nasua nasua                    -0.7363 1.0124  180
(Intercept)-Panthera onca                   0.0585 1.0119  643
(Intercept)-Pecari tajacu                  -0.5424 1.0010 1398
(Intercept)-Priodontes maximus             -0.5061 1.0221  158
(Intercept)-Procyon cancrivorus            -0.6677 1.0219  240
(Intercept)-Puma concolor                  -0.8936 1.0410  201
(Intercept)-Tapirus terrestris             -0.5414 1.0163 1499
(Intercept)-Tayassu pecari                 -0.8835 1.0014 1010
scale(elev)-Atelocynus microtis             0.8159 1.0013 1780
scale(elev)-Cuniculus paca                  0.4823 1.0009 1609
scale(elev)-Dasyprocta punctata             0.5842 1.0028 1599
scale(elev)-Dasypus novemcinctus            0.8075 1.0029 1673
scale(elev)-Didelphis marsupialis           1.3508 1.0031 1646
scale(elev)-Eira barbara                    1.1688 1.0038 1646
scale(elev)-Leopardus pardalis              0.4770 1.0002 1816
scale(elev)-Leopardus wiedii                1.0232 1.0058 1425
scale(elev)-Mazama americana                0.7688 1.0020 1622
scale(elev)-Mazama gouazoubira              0.7787 1.0010 1903
scale(elev)-Myrmecophaga tridactyla         0.7126 1.0012 1501
scale(elev)-Nasua nasua                     1.0766 1.0062 1630
scale(elev)-Panthera onca                   1.1151 1.0114 1845
scale(elev)-Pecari tajacu                   0.6118 1.0001 1711
scale(elev)-Priodontes maximus              1.1695 1.0015 1344
scale(elev)-Procyon cancrivorus             0.7344 1.0042 1388
scale(elev)-Puma concolor                   1.3429 1.0039 1566
scale(elev)-Tapirus terrestris              1.1611 1.0040 1631
scale(elev)-Tayassu pecari                  0.6250 1.0009 1847
scale(border_dist)-Atelocynus microtis      0.4649 1.0031 1705
scale(border_dist)-Cuniculus paca           0.4806 1.0003 1853
scale(border_dist)-Dasyprocta punctata      0.8814 1.0077 1427
scale(border_dist)-Dasypus novemcinctus     1.0114 1.0061 1506
scale(border_dist)-Didelphis marsupialis    0.4371 1.0015 1732
scale(border_dist)-Eira barbara             0.8710 1.0029 1420
scale(border_dist)-Leopardus pardalis       0.4811 0.9997 1986
scale(border_dist)-Leopardus wiedii         0.8868 1.0020 2024
scale(border_dist)-Mazama americana         0.9871 1.0028 1601
scale(border_dist)-Mazama gouazoubira       0.9633 1.0081 1898
scale(border_dist)-Myrmecophaga tridactyla  1.4010 1.0016 1086
scale(border_dist)-Nasua nasua              0.8534 1.0043 1568
scale(border_dist)-Panthera onca            0.5465 1.0047 1550
scale(border_dist)-Pecari tajacu            1.1626 1.0033 1508
scale(border_dist)-Priodontes maximus       1.0351 1.0013 1357
scale(border_dist)-Procyon cancrivorus      1.0485 1.0024 1333
scale(border_dist)-Puma concolor            0.6760 0.9999 1913
scale(border_dist)-Tapirus terrestris       0.2727 1.0055 1748
scale(border_dist)-Tayassu pecari           0.2882 1.0013 2142
scale(FLII)-Atelocynus microtis             1.9010 1.0031 1446
scale(FLII)-Cuniculus paca                  1.2961 1.0024 1852
scale(FLII)-Dasyprocta punctata             1.5246 1.0070 1647
scale(FLII)-Dasypus novemcinctus            1.3185 1.0020 1332
scale(FLII)-Didelphis marsupialis           2.3530 1.0012 1433
scale(FLII)-Eira barbara                    1.8795 1.0112 1441
scale(FLII)-Leopardus pardalis              1.7301 0.9999 1810
scale(FLII)-Leopardus wiedii                2.0875 1.0029 1590
scale(FLII)-Mazama americana                1.4808 1.0008 1595
scale(FLII)-Mazama gouazoubira              1.2766 1.0066 1157
scale(FLII)-Myrmecophaga tridactyla         1.2610 1.0062 1125
scale(FLII)-Nasua nasua                     2.0207 1.0042 1447
scale(FLII)-Panthera onca                   2.0855 1.0055 1485
scale(FLII)-Pecari tajacu                   1.4836 1.0034 1980
scale(FLII)-Priodontes maximus              1.4263 1.0015 1447
scale(FLII)-Procyon cancrivorus             1.9068 1.0027 1249
scale(FLII)-Puma concolor                   1.8644 1.0024 1564
scale(FLII)-Tapirus terrestris              2.6018 1.0017 1295
scale(FLII)-Tayassu pecari                  1.9776 1.0005 1505

Detection (logit scale): 
                                         Mean     SD    2.5%     50%   97.5%
(Intercept)-Atelocynus microtis       -2.4490 0.7017 -3.7708 -2.4784 -1.1000
(Intercept)-Cuniculus paca            -1.5209 0.3427 -2.1896 -1.5203 -0.8852
(Intercept)-Dasyprocta punctata       -1.6274 0.2968 -2.2389 -1.6197 -1.0680
(Intercept)-Dasypus novemcinctus      -3.4240 0.6762 -4.7220 -3.4452 -1.9748
(Intercept)-Didelphis marsupialis     -2.3149 0.3969 -3.1013 -2.3067 -1.5804
(Intercept)-Eira barbara              -3.9677 1.0028 -5.8783 -4.0269 -1.7891
(Intercept)-Leopardus pardalis        -1.5363 0.2853 -2.1340 -1.5236 -1.0124
(Intercept)-Leopardus wiedii          -3.1563 0.6953 -4.4153 -3.1968 -1.7375
(Intercept)-Mazama americana          -1.2077 0.2968 -1.8012 -1.2016 -0.6383
(Intercept)-Mazama gouazoubira        -2.9011 0.6250 -4.0649 -2.9327 -1.6197
(Intercept)-Myrmecophaga tridactyla   -2.6588 0.6572 -3.8575 -2.7017 -1.2791
(Intercept)-Nasua nasua               -3.2327 0.7564 -4.6074 -3.2893 -1.6617
(Intercept)-Panthera onca             -2.9739 0.4646 -3.8463 -2.9718 -2.0245
(Intercept)-Pecari tajacu             -1.6325 0.3100 -2.2630 -1.6186 -1.0384
(Intercept)-Priodontes maximus        -3.5519 0.7693 -4.9753 -3.5939 -1.9334
(Intercept)-Procyon cancrivorus       -3.6960 0.8427 -5.2249 -3.7643 -1.9133
(Intercept)-Puma concolor             -3.1691 0.7757 -4.5788 -3.2209 -1.5613
(Intercept)-Tapirus terrestris        -1.3467 0.2614 -1.8714 -1.3393 -0.8532
(Intercept)-Tayassu pecari            -1.2188 0.2825 -1.8026 -1.2128 -0.6814
scale(effort)-Atelocynus microtis      0.7761 0.4064 -0.0537  0.7890  1.5566
scale(effort)-Cuniculus paca           1.0826 0.3542  0.4432  1.0543  1.8263
scale(effort)-Dasyprocta punctata      1.2949 0.4001  0.6518  1.2466  2.2309
scale(effort)-Dasypus novemcinctus     1.0534 0.4336  0.2205  1.0395  2.0063
scale(effort)-Didelphis marsupialis    1.2216 0.4172  0.5300  1.1822  2.1753
scale(effort)-Eira barbara             0.9418 0.4435  0.0269  0.9343  1.8512
scale(effort)-Leopardus pardalis       1.4124 0.4153  0.7697  1.3567  2.3931
scale(effort)-Leopardus wiedii         1.0841 0.4309  0.3029  1.0652  2.0157
scale(effort)-Mazama americana         1.1436 0.3339  0.5786  1.1055  1.9026
scale(effort)-Mazama gouazoubira       0.7427 0.4017 -0.0848  0.7514  1.5169
scale(effort)-Myrmecophaga tridactyla  0.8043 0.4047  0.0051  0.8150  1.5764
scale(effort)-Nasua nasua              1.0703 0.4322  0.2437  1.0460  2.0092
scale(effort)-Panthera onca            1.0945 0.4260  0.3259  1.0683  2.0353
scale(effort)-Pecari tajacu            1.3074 0.4054  0.6389  1.2622  2.2421
scale(effort)-Priodontes maximus       1.0604 0.4412  0.2105  1.0463  2.0156
scale(effort)-Procyon cancrivorus      0.9859 0.4367  0.1154  0.9728  1.8811
scale(effort)-Puma concolor            1.0631 0.4471  0.2262  1.0468  2.0154
scale(effort)-Tapirus terrestris       0.9515 0.2795  0.4430  0.9344  1.5384
scale(effort)-Tayassu pecari           1.0901 0.3106  0.5372  1.0704  1.7596
                                        Rhat  ESS
(Intercept)-Atelocynus microtis       1.0128  449
(Intercept)-Cuniculus paca            1.0062 2353
(Intercept)-Dasyprocta punctata       1.0004 2292
(Intercept)-Dasypus novemcinctus      1.0061  456
(Intercept)-Didelphis marsupialis     1.0051 1520
(Intercept)-Eira barbara              1.0230  208
(Intercept)-Leopardus pardalis        1.0052 1982
(Intercept)-Leopardus wiedii          1.0378  295
(Intercept)-Mazama americana          1.0025 2759
(Intercept)-Mazama gouazoubira        1.0278  219
(Intercept)-Myrmecophaga tridactyla   1.0127  444
(Intercept)-Nasua nasua               1.0205  261
(Intercept)-Panthera onca             1.0007 1125
(Intercept)-Pecari tajacu             1.0000 2344
(Intercept)-Priodontes maximus        1.0105  324
(Intercept)-Procyon cancrivorus       1.0080  318
(Intercept)-Puma concolor             1.0332  178
(Intercept)-Tapirus terrestris        1.0046 2598
(Intercept)-Tayassu pecari            0.9999 2688
scale(effort)-Atelocynus microtis     1.0071 2351
scale(effort)-Cuniculus paca          1.0008 2531
scale(effort)-Dasyprocta punctata     1.0027 1824
scale(effort)-Dasypus novemcinctus    1.0067 2085
scale(effort)-Didelphis marsupialis   1.0025 1868
scale(effort)-Eira barbara            1.0036 2210
scale(effort)-Leopardus pardalis      1.0123 1436
scale(effort)-Leopardus wiedii        1.0028 2911
scale(effort)-Mazama americana        1.0020 2454
scale(effort)-Mazama gouazoubira      1.0004 2413
scale(effort)-Myrmecophaga tridactyla 1.0005 2589
scale(effort)-Nasua nasua             1.0071 2108
scale(effort)-Panthera onca           1.0077 1882
scale(effort)-Pecari tajacu           1.0031 1521
scale(effort)-Priodontes maximus      1.0023 2058
scale(effort)-Procyon cancrivorus     0.9999 2441
scale(effort)-Puma concolor           1.0020 2388
scale(effort)-Tapirus terrestris      1.0027 2759
scale(effort)-Tayassu pecari          1.0088 3071

----------------------------------------
    Spatial Covariance
----------------------------------------
        Mean     SD  2.5%    50%  97.5%   Rhat  ESS
phi-1 0.0048 0.0033 7e-04 0.0039 0.0112 1.0035  770
phi-2 0.0051 0.0034 6e-04 0.0046 0.0113 1.0085  947
phi-3 0.0056 0.0033 7e-04 0.0054 0.0112 1.0136 1202
phi-4 0.0059 0.0033 8e-04 0.0058 0.0113 1.0039 1595
phi-5 0.0055 0.0034 3e-04 0.0054 0.0113 1.0376  346

Bayesian p-values can be inspected to check for lack of fit (overall or by species). Lack of fit at significance level = 0.05 is indicated by Bayesian p-values below 0.025 or greater than 0.975. The overall Bayesian p-value (Bpvalue) indicates no problems with lack of fit. Likewise, species-level Bayesian p-values (Bpvalue_species) indicate no lack of fit for any species.

Gelman and Rubin’s convergence diagnostic: Approximate convergence is diagnosed when the upper limit is close to 1.

Convergence is diagnosed when the chains have ‘forgotten’ their initial values, and the output from all chains is indistinguishable. The gelman.diag diagnostic is applied to a single variable from the chain. It is based a comparison of within-chain and between-chain variances, and is similar to a classical analysis of variance.

Values substantially above 1 indicate lack of convergence.

Model Diagnostics

Code
#| eval: true
#| echo: true
#| code-fold: true
#| warning: false
#| message: false
# Extract posterior draws for later use
posterior1 <- as.array(out.sp)

# Trace plots to check chain mixing. Extract posterior samples and bind in a single matrix.
POSTERIOR.MATRIX <- cbind(out.sp$alpha.comm.samples, 
                          out.sp$beta.comm.samples,  
                          out.sp$alpha.samples, 
                          out.sp$beta.samples)

# Matrix output is all chains combined, split into 3 chains.
CHAIN.1 <- as.mcmc(POSTERIOR.MATRIX[1:1000,])
CHAIN.2 <- as.mcmc(POSTERIOR.MATRIX[1001:2000,])
CHAIN.3 <- as.mcmc(POSTERIOR.MATRIX[2001:3000,])
# CHAIN.4 <- as.mcmc(POSTERIOR.MATRIX[8001:10000,])

# Bind four chains as coda mcmc.list object.
POSTERIOR.CHAINS <- mcmc.list(CHAIN.1, CHAIN.2, CHAIN.3)#, CHAIN.4)

# Create an empty folder.
# dir.create ("Beetle_plots")

# Plot chain mixing of each parameter to a multi-panel plot and save to the new folder. ART 5 mins

######################################
#### SAVE Diagnostics at PDF
# MCMCtrace(POSTERIOR.CHAINS, params = "all", Rhat = TRUE, n.eff = TRUE)#, pdf = TRUE, filename = "Beetle_240909_traceplots.pdf", wd = "Beetle_plots")



#mcmc_trace(fit.commu, parms = c("beta.ranef.cont.border_dist.mean"))

#posterior2 <- extract(fit.commu, inc_warmup = TRUE, permuted = FALSE)

#color_scheme_set("mix-blue-pink")
#p <- mcmc_trace(posterior1,  pars = c("mu", "tau"), n_warmup = 300,
#                facet_args = list(nrow = 2, labeller = label_parsed))
#p + facet_text(size = 15)



#outMCMC <- fit.commu #Convert output to MCMC object
#diagnostics chains 

# all as pdf
# MCMCtrace(outMCMC)

# MCMCtrace(outMCMC, params = c("alpha0"), type = 'trace', Rhat = TRUE, n.eff = TRUE)

# MCMCtrace(outMCMC, params = c("beta0"), type = 'trace', Rhat = TRUE, n.eff = TRUE)

# MCMCtrace(outMCMC, params = c("beta.ranef.cont.border_dist"), type = 'trace', Rhat = TRUE, n.eff = TRUE)

# MCMCtrace(out.sp, params = c("beta.ranef.cont.border_dist.mean"), type = 'trace', pdf = F, Rhat = TRUE, n.eff = TRUE)

# MCMCtrace(outMCMC, params = c("beta.ranef.cont.elev"), type = 'trace', Rhat = TRUE, n.eff = TRUE)

# MCMCtrace(outMCMC, params = c("beta.ranef.cont.elev.mean"), type = 'trace', pdf = F, Rhat = TRUE, n.eff = TRUE)


### density
# MCMCtrace(outMCMC, params = c("Nspecies"), ISB = FALSE, pdf = F, exact = TRUE, post_zm = TRUE, type = 'density', Rhat = TRUE, n.eff = TRUE, ind = TRUE)

### density
# MCMCtrace(outMCMC, params = c("beta.ranef.cont.elev.mean"), ISB = FALSE, pdf = F, exact = TRUE, post_zm = TRUE, type = 'density', Rhat = TRUE, n.eff = TRUE, ind = TRUE)

### density
#MCMCtrace(outMCMC, params = c("beta.ranef.cont.border_dist.mean"), ISB = FALSE, pdf = F, exact = TRUE, post_zm = TRUE, type = 'density', Rhat = TRUE, n.eff = TRUE, ind = TRUE)

#coda::gelman.diag(outMCMC,  multivariate = FALSE, transform=FALSE)
                    
# coda::gelman.plot(outMCMC,  multivariate = FALSE)



# 
# mcmc_intervals(outMCMC, pars = c("Nspecies_in_AP[1]",
#                                  "Nspecies_in_AP[2]"),
#                point_est = "mean",
#                prob = 0.75, prob_outer = 0.95) +
#   ggtitle("Number of species") + 
#   scale_y_discrete(labels = c("Nspecies_in_AP[1]"=levels(sitecovs$in_AP)[1],
#              "Nspecies_in_AP[2]"=levels(sitecovs$in_AP)[2]))
# 
# #Continuous
# p <- mcmc_intervals(outMCMC, 
#                pars = c("beta.ranef.cont.border_dist.mean",
#                          #"beta.ranef.cont.elev.mean",
#                         "beta.ranef.categ.in_AP.mean[2]"))
# 
# # relabel parameters
# p + scale_y_discrete(
#   labels = c("beta.ranef.cont.border_dist.mean"="Dist_border",
#                          #"beta.ranef.cont.elev.mean"="Elevation",
#                         "beta.ranef.categ.in_AP.mean[2]"="in_AP")
# ) +
#   ggtitle("Treatment effect on all species")
# 

Posterior Summary (effect)

Community effects

Code
# Create simple plot summaries using MCMCvis package.
# Detection covariate effects --------- 
MCMCplot(out.sp$alpha.comm.samples, ref_ovl = TRUE, ci = c(50, 95))
# Occupancy community-level effects 
MCMCplot(out.sp$beta.comm.samples, ref_ovl = TRUE, ci = c(50, 95))
(a) Detection
(b) Occupancy
Figure 1: Community effects

Species effects

Code
# Occupancy species-level effects 
MCMCplot(out.sp$beta.samples[,19:36], ref_ovl = TRUE, ci = c(50, 95))

# Occupancy species-level effects 
MCMCplot(out.sp$beta.samples[,37:54], ref_ovl = TRUE, ci = c(50, 95))

# Occupancy species-level effects 
MCMCplot(out.sp$beta.samples[,55:72], ref_ovl = TRUE, ci = c(50, 95))
(a) elevation
(b) distance border
(c) FLII
Figure 2: Species effects

Species effects using bayesplot

Code
library(bayesplot)
#mcmc_areas(outMCMC, regex_pars = "Nspecies_in_AP")
# mcmc_areas(outMCMC, regex_pars = "Nspecies_in_AP")

mcmc_intervals(out.sp$beta.samples[,19:36] , point_est = "mean",
               prob = 0.75, prob_outer = 0.95) + 
  geom_vline(xintercept = 0, color = "red", linetype = "dashed", size = 0.5)
Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.

Code
mcmc_intervals(out.sp$beta.samples[,37:54] , point_est = "mean",
               prob = 0.75, prob_outer = 0.95) + 
  geom_vline(xintercept = 0, color = "red", linetype = "dashed", size = 0.5)

Code
mcmc_intervals(out.sp$beta.samples[,55:72] , point_est = "mean",
               prob = 0.75, prob_outer = 0.95) + 
  geom_vline(xintercept = 0, color = "red", linetype = "dashed", size = 0.5)

Prediction as graph

This prediction uses the non spatial model

Code
# 6. Prediction -----------------------------------------------------------
# Predict occupancy along a gradient of elev   
# Create a set of values across the range of observed elev values
elev.pred.vals <- seq(min(data_list$occ.covs$elev), 
                              max(data_list$occ.covs$elev), 
                              length.out = 100)
# Scale predicted values by mean and standard deviation used to fit the model
elev.pred.vals.scale <- (elev.pred.vals - mean(data_list$occ.covs$elev)) / 
                             sd(data_list$occ.covs$elev)
# Create a set of values across the range of observed elev values
border_dist.pred.vals <- seq(min(data_list$occ.covs$border_dist), 
                              max(data_list$occ.covs$border_dist), 
                              length.out = 100)
# Scale predicted values by mean and standard deviation used to fit the model
border_dist.pred.vals.scale <- (border_dist.pred.vals -
                                  mean(data_list$occ.covs$border_dist)) /
                                  sd(data_list$occ.covs$border_dist)

# Create a set of values across the range of observed FLII values
FLII.pred.vals <- seq(min(data_list$occ.covs$FLII), 
                              max(data_list$occ.covs$FLII), 
                              length.out = 100)
# Scale predicted values by mean and standard deviation used to fit the model
FLII.pred.vals.scale <- (FLII.pred.vals -
                                  mean(data_list$occ.covs$FLII)) /
                                  sd(data_list$occ.covs$FLII)

# Predict occupancy across elev  values at mean values of all other variables
pred.df1 <- as.matrix(data.frame(intercept = 1, 
                                 elev = elev.pred.vals.scale, 
                                 border_dist = 0,
                                 FLII=0))#, catchment = 0, density = 0, 
                         # slope = 0))
# Predict occupancy across elev  values at mean values of all other variables
pred.df2 <- as.matrix(data.frame(intercept = 1, elev = 0, 
                         border_dist = border_dist.pred.vals.scale,
                         FLII= 0 ))#, catchment = 0, density = 0, 
                         # slope = 0))
# Predict occupancy across elev  values at mean values of all other variables
pred.df3 <- as.matrix(data.frame(intercept = 1, elev = 0, 
                         border_dist = 0,
                         FLII= FLII.pred.vals.scale ))#, catchment = 0, density = 0, 
                         # slope = 0))

out.pred1 <- predict(out.null, pred.df1) # using non spatial
str(out.pred1)
List of 3
 $ psi.0.samples: num [1:1500, 1:19, 1:100] 0.0798 0.22 0.1425 0.177 0.2078 ...
 $ z.0.samples  : int [1:1500, 1:19, 1:100] 0 0 0 0 0 0 1 1 1 1 ...
 $ call         : language predict.msPGOcc(object = out.null, X.0 = pred.df1)
 - attr(*, "class")= chr "predict.msPGOcc"
Code
psi.0.quants <- apply(out.pred1$psi.0.samples, c(2, 3), quantile, 
                          prob = c(0.025, 0.5, 0.975))
sp.codes <- attr(data_list$y, "dimnames")[[1]]
psi.plot.dat <- data.frame(psi.med = c(t(psi.0.quants[2, , ])), 
                                 psi.low = c(t(psi.0.quants[1, , ])), 
                                 psi.high = c(t(psi.0.quants[3, , ])), 
                           elev = elev.pred.vals, 
                                 sp.codes = rep(sp.codes, 
                                                each = length(elev.pred.vals)))

ggplot(psi.plot.dat, aes(x = elev, y = psi.med)) + 
  geom_ribbon(aes(ymin = psi.low, ymax = psi.high), fill = 'grey70') +
  geom_line() + 
  facet_wrap(vars(sp.codes)) + 
  theme_bw() + 
  labs(x = 'elevation (m)', y = 'Occupancy Probability') 

Code
out.pred2 <- predict(out.null, pred.df2) # using non spatial
str(out.pred2)
List of 3
 $ psi.0.samples: num [1:1500, 1:19, 1:100] 0.086 0.121 0.26 0.315 0.217 ...
 $ z.0.samples  : int [1:1500, 1:19, 1:100] 0 0 0 0 1 0 1 0 1 0 ...
 $ call         : language predict.msPGOcc(object = out.null, X.0 = pred.df2)
 - attr(*, "class")= chr "predict.msPGOcc"
Code
psi.0.quants <- apply(out.pred2$psi.0.samples, c(2, 3), quantile, 
                          prob = c(0.025, 0.5, 0.975))
sp.codes <- attr(data_list$y, "dimnames")[[1]]
psi.plot.dat <- data.frame(psi.med = c(t(psi.0.quants[2, , ])), 
                                 psi.low = c(t(psi.0.quants[1, , ])), 
                                 psi.high = c(t(psi.0.quants[3, , ])), 
                           border_dist = border_dist.pred.vals, 
                                 sp.codes = rep(sp.codes, 
                                                each = length(border_dist.pred.vals)))

ggplot(psi.plot.dat, aes(x = border_dist/1000, y = psi.med)) + 
  geom_ribbon(aes(ymin = psi.low, ymax = psi.high), fill = 'grey70') +
  geom_line() + 
  facet_wrap(vars(sp.codes)) + 
  theme_bw() + 
  labs(x = 'border_dist (Km)', y = 'Occupancy Probability') 

Code
out.pred3 <- predict(out.null, pred.df3) # using non spatial
str(out.pred3)
List of 3
 $ psi.0.samples: num [1:1500, 1:19, 1:100] 0.0124 0.1798 0.0165 0.0675 0.0215 ...
 $ z.0.samples  : int [1:1500, 1:19, 1:100] 0 0 0 0 0 0 0 0 1 0 ...
 $ call         : language predict.msPGOcc(object = out.null, X.0 = pred.df3)
 - attr(*, "class")= chr "predict.msPGOcc"
Code
psi.0.quants <- apply(out.pred3$psi.0.samples, c(2, 3), quantile, 
                          prob = c(0.025, 0.5, 0.975))
sp.codes <- attr(data_list$y, "dimnames")[[1]]
psi.plot.dat <- data.frame(psi.med = c(t(psi.0.quants[2, , ])), 
                                 psi.low = c(t(psi.0.quants[1, , ])), 
                                 psi.high = c(t(psi.0.quants[3, , ])), 
                           FLII = FLII.pred.vals, 
                                 sp.codes = rep(sp.codes, 
                                                each = length(FLII.pred.vals)))

ggplot(psi.plot.dat, aes(x = FLII/1000, y = psi.med)) + 
  geom_ribbon(aes(ymin = psi.low, ymax = psi.high), fill = 'grey70') +
  geom_line() + 
  facet_wrap(vars(sp.codes)) + 
  theme_bw() + 
  labs(x = 'FLII', y = 'Occupancy Probability') 

Spatial Prediction in FLII

Code
#aggregate  resolution to (factor = 3)
#transform coord data to UTM
elevation_UTM <- project(elevation_17, "EPSG:10603")
elevation_17.aggregate <- aggregate(elevation_UTM, fact=10)
res(elevation_17.aggregate)
[1] 1485.008 1485.008
Code
FLII_UTM <- project(FLII2016, "EPSG:10603") |> crop(elevation_UTM)
# Calculate the min of non-NA values
# na.rm = TRUE is essential to ignore NAs when calculating the mean
min_val <- global(FLII_UTM, "min", na.rm = TRUE, na.policy = "only")[1, 1]
# Replace NA values with the calculated min
FLII_UTM[is.na(FLII_UTM)] <- min_val

FLII_UTM.aggregate <- aggregate(FLII_UTM, fact=10)
res(FLII_UTM.aggregate)
[1] 2935.846 2935.846
Code
# Convert the SpatRaster to a data frame with coordinates
df_coords <- as.data.frame(FLII_UTM.aggregate, xy = TRUE)
names(df_coords) <-c("X","Y","FLII")

FLII.pred <- (df_coords$FLII - mean(data_list$occ.covs$FLII)) / sd(data_list$occ.covs$FLII)


############### Predict new data ############### 
# we predict at one covariate varing and others at mean value = 0
# intercept = 1, elev = 0, border_dist = 0, FLII= 0
# in that order
################ ################ ################ 
predict_data <- cbind(1, 0, 0, FLII.pred)
colnames(predict_data) <- c("intercept",
                            "elev",
                            "border_dist",
                            "FLII" )

# X.0 <- cbind(1, 1, elev.pred)#, elev.pred^2)

# coords.0 <- as.matrix(hbefElev[, c('Easting', 'Northing')])
out.sp.ms.pred <- predict(out.sp, 
                          X.0=predict_data, 
                          df_coords[,1:2],
                          threads=4) #Warning :'threads' is not an argument
Warning in predict.sfMsPGOcc(out.sp, X.0 = predict_data, df_coords[, 1:2], :
'threads' is not an argument
----------------------------------------
    Prediction description
----------------------------------------
Spatial Factor NNGP Multispecies Occupancy model with Polya-Gamma latent
variable fit with 102 observations.

Number of covariates 4 (including intercept if specified).

Using the exponential spatial correlation model.

Using 15 nearest neighbors.
Using 5 latent spatial factors.

Number of MCMC samples 3000.

Predicting at 1404 non-sampled locations.


Source compiled with OpenMP support and model fit using 1 threads.
-------------------------------------------------
        Predicting
-------------------------------------------------
Location: 100 of 1404, 7.12%
Location: 200 of 1404, 14.25%
Location: 300 of 1404, 21.37%
Location: 400 of 1404, 28.49%
Location: 500 of 1404, 35.61%
Location: 600 of 1404, 42.74%
Location: 700 of 1404, 49.86%
Location: 800 of 1404, 56.98%
Location: 900 of 1404, 64.10%
Location: 1000 of 1404, 71.23%
Location: 1100 of 1404, 78.35%
Location: 1200 of 1404, 85.47%
Location: 1300 of 1404, 92.59%
Location: 1400 of 1404, 99.72%
Location: 1404 of 1404, 100.00%
Generating latent occupancy state
Code
# extract the array of interest= occupancy
predicted_array <- out.sp.ms.pred$psi.0.samples



dim(predicted_array)
[1] 3000   19 1404
Code
# df_plot <- NA # empty column
predicted_raster_list <- list() # rast(nrows = 52, ncols = 103,
                         #ext(elevation_17.aggregate), 
                         # crs = "EPSG:32717")

###################################################
# simpler way to make mean in the array by species
# array order: itera=3000, sp=22, pixels=5202
# we wan to keep index 2 and 3
library(plyr)
------------------------------------------------------------------------------
You have loaded plyr after dplyr - this is likely to cause problems.
If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
library(plyr); library(dplyr)
------------------------------------------------------------------------------

Adjuntando el paquete: 'plyr'
The following objects are masked from 'package:dplyr':

    arrange, count, desc, failwith, id, mutate, rename, summarise,
    summarize
The following object is masked from 'package:purrr':

    compact
The following object is masked from 'package:maps':

    ozone
Code
aresult = (plyr::aaply(predicted_array, # mean fo all iterations
                       c(2,3), 
                       mean))

##############################################
#### Loop to make rasters and put in a list
# array order: itera=3000, sp=22, pixels=5202
for (i in 1:dim(predicted_array)[2]){
 # Convert array slice to data frame
 # df_plot[i] <- as.data.frame(predicted_array[1, i, ]) # sp_i
 # df_plot[i] <- as.vector(aresult[i,]) # Extract sp
 # Producing an SDM for all (posterior mean)
 plot.dat <- data.frame(x = df_coords$X, 
                        y = df_coords$Y, 
                        psi.sp = as.vector(aresult[i,]))
 pred_rast <- rast(plot.dat, 
                   type = "xyz", 
                   crs = "EPSG:10603") # Replace EPSG:4326 with your CRS
 predicted_raster_list[[i]] <- pred_rast
}

# Convert the list to a SpatRaster stack
predictad_raster_stack <- rast(predicted_raster_list)
# put species names
names(predictad_raster_stack) <- selected.sp

plot(predictad_raster_stack)

Code
# get the mean
predicted_mean <- mean(predictad_raster_stack)

plot(predicted_mean, main="mean occupancy")

Code
mapview(predicted_mean) + mapview(AP_Madidi_UTM_line)
Code
# 

Package Citation

Code
pkgs <- cite_packages(output = "paragraph", pkgs="Session", out.dir = ".")
# knitr::kable(pkgs)
pkgs

We used R v. 4.4.2 (R Core Team 2024) and the following R packages: abind v. 1.4.8 (Plate and Heiberger 2024), bayesplot v. 1.14.0 (Gabry et al. 2019; Gabry and Mahr 2025), beepr v. 2.0 (Bååth 2024), camtrapR v. 3.0.0 (Niedballa et al. 2016), coda v. 0.19.4.1 (Plummer et al. 2006), DT v. 0.34.0 (Xie et al. 2025), elevatr v. 0.99.0 (Hollister et al. 2023), maps v. 3.4.3 (Becker et al. 2025), mapview v. 2.11.4 (Appelhans et al. 2025), MCMCvis v. 0.16.3 (Youngflesh 2018), plyr v. 1.8.9 (Wickham 2011), sf v. 1.0.21 (Pebesma 2018; Pebesma and Bivand 2023), snow v. 0.4.4 (Tierney et al. 2021), snowfall v. 1.84.6.3 (Knaus 2023), spOccupancy v. 0.8.0 (Doser et al. 2022, 2024; Doser, Finley, and Banerjee 2023), terra v. 1.8.70 (Hijmans 2025), tictoc v. 1.2.1 (Izrailev 2024), tidyverse v. 2.0.0 (Wickham et al. 2019), tmap v. 4.2 (Tennekes 2018).

Sesion info

Code
print(sessionInfo(), locale = FALSE)
R version 4.4.2 (2024-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64
Running under: Windows 10 x64 (build 19045)

Matrix products: internal


attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] plyr_1.8.9        abind_1.4-8       lubridate_1.9.4   forcats_1.0.0    
 [5] stringr_1.5.2     dplyr_1.1.4       purrr_1.1.0       readr_2.1.5      
 [9] tidyr_1.3.1       tibble_3.2.1      ggplot2_4.0.0     tidyverse_2.0.0  
[13] spOccupancy_0.8.0 camtrapR_3.0.0    snowfall_1.84-6.3 snow_0.4-4       
[17] beepr_2.0         coda_0.19-4.1     MCMCvis_0.16.3    tictoc_1.2.1     
[21] bayesplot_1.14.0  elevatr_0.99.0    terra_1.8-70      tmap_4.2         
[25] maps_3.4.3        mapview_2.11.4    sf_1.0-21         DT_0.34.0        
[29] readxl_1.4.3      grateful_0.3.0   

loaded via a namespace (and not attached):
  [1] RColorBrewer_1.1-3      tensorA_0.36.2.1        rstudioapi_0.17.1      
  [4] audio_0.1-11            jsonlite_2.0.0          wk_0.9.4               
  [7] magrittr_2.0.3          farver_2.1.2            nloptr_2.1.1           
 [10] rmarkdown_2.30          vctrs_0.6.5             minqa_1.2.8            
 [13] base64enc_0.1-3         RcppNumerical_0.6-0     progress_1.2.3         
 [16] htmltools_0.5.8.1       leafsync_0.1.0          distributional_0.5.0   
 [19] curl_7.0.0              raster_3.6-32           cellranger_1.1.0       
 [22] s2_1.1.9                sass_0.4.10             bslib_0.9.0            
 [25] slippymath_0.3.1        KernSmooth_2.23-24      htmlwidgets_1.6.4      
 [28] cachem_1.1.0            stars_0.6-8             uuid_1.2-1             
 [31] mime_0.13               lifecycle_1.0.4         iterators_1.0.14       
 [34] pkgconfig_2.0.3         cols4all_0.8-1          Matrix_1.7-1           
 [37] R6_2.6.1                fastmap_1.2.0           shiny_1.9.1            
 [40] digest_0.6.37           colorspace_2.1-1        leafem_0.2.4           
 [43] crosstalk_1.2.1         labeling_0.4.3          lwgeom_0.2-14          
 [46] progressr_0.15.0        spacesXYZ_1.6-0         timechange_0.3.0       
 [49] httr_1.4.7              mgcv_1.9-1              compiler_4.4.2         
 [52] microbenchmark_1.5.0    proxy_0.4-27            withr_3.0.2            
 [55] doParallel_1.0.17       backports_1.5.0         brew_1.0-10            
 [58] S7_0.2.0                DBI_1.2.3               logger_0.4.0           
 [61] MASS_7.3-61             maptiles_0.10.0         tmaptools_3.3          
 [64] leaflet_2.2.3           classInt_0.4-11         tools_4.4.2            
 [67] units_0.8-7             leaflegend_1.2.1        httpuv_1.6.16          
 [70] glue_1.8.0              satellite_1.0.5         nlme_3.1-166           
 [73] promises_1.3.3          grid_4.4.2              checkmate_2.3.2        
 [76] reshape2_1.4.4          generics_0.1.3          leaflet.providers_2.0.0
 [79] gtable_0.3.6            tzdb_0.4.0              shinyBS_0.61.1         
 [82] class_7.3-22            data.table_1.17.8       hms_1.1.3              
 [85] sp_2.2-0                RANN_2.6.2              foreach_1.5.2          
 [88] pillar_1.11.1           posterior_1.6.1         later_1.4.2            
 [91] splines_4.4.2           lattice_0.22-6          tidyselect_1.2.1       
 [94] knitr_1.50              svglite_2.1.3           stats4_4.4.2           
 [97] xfun_0.52               shinydashboard_0.7.3    leafpop_0.1.0          
[100] stringi_1.8.4           rematch_2.0.0           yaml_2.3.10            
[103] boot_1.3-31             evaluate_1.0.4          codetools_0.2-20       
[106] cli_3.6.5               RcppParallel_5.1.9      systemfonts_1.1.0      
[109] xtable_1.8-4            jquerylib_0.1.4         secr_5.1.0             
[112] dichromat_2.0-0.1       Rcpp_1.1.0              spAbundance_0.2.1      
[115] png_0.1-8               XML_3.99-0.18           parallel_4.4.2         
[118] prettyunits_1.2.0       lme4_1.1-35.5           mvtnorm_1.3-2          
[121] scales_1.4.0            e1071_1.7-16            crayon_1.5.3           
[124] rlang_1.1.6            

References

Appelhans, Tim, Florian Detsch, Christoph Reudenbach, and Stefan Woellauer. 2025. mapview: Interactive Viewing of Spatial Data in r. https://CRAN.R-project.org/package=mapview.
Bååth, Rasmus. 2024. beepr: Easily Play Notification Sounds on Any Platform. https://CRAN.R-project.org/package=beepr.
Becker, Richard A., Allan R. Wilks, Ray Brownrigg, Thomas P. Minka, and Alex Deckmyn. 2025. maps: Draw Geographical Maps. https://CRAN.R-project.org/package=maps.
Doser, Jeffrey W., Andrew O. Finley, and Sudipto Banerjee. 2023. “Joint Species Distribution Models with Imperfect Detection for High-Dimensional Spatial Data.” Ecology, e4137. https://doi.org/10.1002/ecy.4137.
Doser, Jeffrey W., Andrew O. Finley, Marc Kéry, and Elise F. Zipkin. 2022. spOccupancy: An r Package for Single-Species, Multi-Species, and Integrated Spatial Occupancy Models.” Methods in Ecology and Evolution 13: 1670–78. https://doi.org/10.1111/2041-210X.13897.
Doser, Jeffrey W., Andrew O. Finley, Sarah P. Saunders, Marc Kéry, Aaron S. Weed, and Elise F. Zipkin. 2024. “Modeling Complex Species-Environment Relationships Through Spatially-Varying Coefficient Occupancy Models.” Journal of Agricultural, Biological, and Environmental Statistics. https://doi.org/10.1007/s13253-023-00595-6.
Gabry, Jonah, and Tristan Mahr. 2025. bayesplot: Plotting for Bayesian Models.” https://mc-stan.org/bayesplot/.
Gabry, Jonah, Daniel Simpson, Aki Vehtari, Michael Betancourt, and Andrew Gelman. 2019. “Visualization in Bayesian Workflow.” J. R. Stat. Soc. A 182: 389–402. https://doi.org/10.1111/rssa.12378.
Hijmans, Robert J. 2025. terra: Spatial Data Analysis. https://CRAN.R-project.org/package=terra.
Hollister, Jeffrey, Tarak Shah, Jakub Nowosad, Alec L. Robitaille, Marcus W. Beck, and Mike Johnson. 2023. elevatr: Access Elevation Data from Various APIs. https://doi.org/10.5281/zenodo.8335450.
Izrailev, Sergei. 2024. tictoc: Functions for Timing r Scripts, as Well as Implementations of Stack and StackList Structures. https://CRAN.R-project.org/package=tictoc.
Knaus, Jochen. 2023. snowfall: Easier Cluster Computing (Based on snow). https://CRAN.R-project.org/package=snowfall.
Niedballa, Jürgen, Rahel Sollmann, Alexandre Courtiol, and Andreas Wilting. 2016. camtrapR: An r Package for Efficient Camera Trap Data Management.” Methods in Ecology and Evolution 7 (12): 1457–62. https://doi.org/10.1111/2041-210X.12600.
Pebesma, Edzer. 2018. Simple Features for R: Standardized Support for Spatial Vector Data.” The R Journal 10 (1): 439–46. https://doi.org/10.32614/RJ-2018-009.
Pebesma, Edzer, and Roger Bivand. 2023. Spatial Data Science: With applications in R. Chapman and Hall/CRC. https://doi.org/10.1201/9780429459016.
Plate, Tony, and Richard Heiberger. 2024. abind: Combine Multidimensional Arrays. https://CRAN.R-project.org/package=abind.
Plummer, Martyn, Nicky Best, Kate Cowles, and Karen Vines. 2006. CODA: Convergence Diagnosis and Output Analysis for MCMC.” R News 6 (1): 7–11. https://journal.r-project.org/archive/.
R Core Team. 2024. R: A Language and Environment for Statistical Computing. Vienna, Austria: R Foundation for Statistical Computing. https://www.R-project.org/.
Tennekes, Martijn. 2018. tmap: Thematic Maps in R.” Journal of Statistical Software 84 (6): 1–39. https://doi.org/10.18637/jss.v084.i06.
Tierney, Luke, A. J. Rossini, Na Li, and H. Sevcikova. 2021. snow: Simple Network of Workstations. https://CRAN.R-project.org/package=snow.
Wickham, Hadley. 2011. “The Split-Apply-Combine Strategy for Data Analysis.” Journal of Statistical Software 40 (1): 1–29. https://www.jstatsoft.org/v40/i01/.
Wickham, Hadley, Mara Averick, Jennifer Bryan, Winston Chang, Lucy D’Agostino McGowan, Romain François, Garrett Grolemund, et al. 2019. “Welcome to the tidyverse.” Journal of Open Source Software 4 (43): 1686. https://doi.org/10.21105/joss.01686.
Xie, Yihui, Joe Cheng, Xianying Tan, and Garrick Aden-Buie. 2025. DT: A Wrapper of the JavaScript Library DataTables. https://CRAN.R-project.org/package=DT.
Youngflesh, Casey. 2018. MCMCvis: Tools to Visualize, Manipulate, and Summarize MCMC Output.” Journal of Open Source Software 3 (24): 640. https://doi.org/10.21105/joss.00640.

Reuse

Citation

BibTeX citation:
@online{forero2025,
  author = {Forero, German and Wallace, Robert and Zapara-Rios, Galo and
    Isasi-Catalá, Emiliana and J. Lizcano, Diego},
  title = {Madidi {Spatial} {Factor} {Multi-Species} {Occupancy}
    {Model}},
  date = {2025-08-16},
  url = {https://dlizcano.github.io/Occu_APs_all/blog/2025-11-3-Madidi/},
  langid = {en}
}
For attribution, please cite this work as:
Forero, German, Robert Wallace, Galo Zapara-Rios, Emiliana Isasi-Catalá, and Diego J. Lizcano. 2025. “Madidi Spatial Factor Multi-Species Occupancy Model.” August 16, 2025. https://dlizcano.github.io/Occu_APs_all/blog/2025-11-3-Madidi/.