# Fitting single-season occupancy models in R
# https://tidyecology.com/posts/single-season-occupancy-model/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-05-11

## ---- setup ----
suppressMessages({library(ggplot2)})
te_ink<-"#16241d"; te_body<-"#2c3a31"; te_forest<-"#275139"; te_paper<-"#f5f4ee"
te_line<-"#dad9ca"; te_faint<-"#5d6b61"; te_gold<-"#c9b458"; te_deep<-"#1d5b4e"
te_red<-"#b5534e"; te_sage<-"#93a87f"; te_green<-"#2f8f63"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(text=element_text(colour=te_body),
      plot.title=element_text(colour=te_ink, face="bold", size=rel(1.05)),
      plot.subtitle=element_text(colour=te_faint, size=rel(0.9)),
      axis.title=element_text(colour=te_ink), axis.text=element_text(colour=te_body),
      panel.grid.minor=element_blank(),
      panel.grid.major=element_line(colour=te_line, linewidth=0.3),
      plot.background=element_rect(fill=te_paper, colour=NA),
      panel.background=element_rect(fill=te_paper, colour=NA),
      legend.key=element_blank(), legend.position="bottom",
      plot.margin=margin(10,12,10,10))
}

## ---- data ----
set.seed(2026)
R <- 200L; K <- 4L; psi_true <- 0.55; p_true <- 0.30
z <- rbinom(R, 1, psi_true)
y <- matrix(rbinom(R * K, 1, z * p_true), nrow = R, ncol = K)
d <- rowSums(y)                # detections per site
mean(d >= 1)                   # naive occupancy

## ---- nll ----
nll <- function(par, y, K) {
  psi <- plogis(par[1]); p <- plogis(par[2])
  d <- rowSums(y)
  lik <- ifelse(d > 0,
                psi * p^d * (1 - p)^(K - d),
                psi * (1 - p)^K + (1 - psi))
  -sum(log(lik))
}
fit <- optim(c(0, 0), nll, y = y, K = K, method = "BFGS", hessian = TRUE)
psi_hat <- plogis(fit$par[1])
p_hat   <- plogis(fit$par[2])
c(psi_hat = round(psi_hat, 3), p_hat = round(p_hat, 3))

## ---- fig-compare ----
V <- solve(fit$hessian); sl <- sqrt(diag(V))
psi_ci <- plogis(fit$par[1] + c(-1.96, 1.96) * sl[1])
est <- data.frame(
  what = factor(c("Naive\n(>=1 detection)", "Occupancy\nmodel", "True\noccupancy"),
                levels = c("Naive\n(>=1 detection)", "Occupancy\nmodel", "True\noccupancy")),
  val  = c(mean(d >= 1), psi_hat, mean(z)),
  lo   = c(NA, psi_ci[1], NA), hi = c(NA, psi_ci[2], NA),
  kind = c("naive", "model", "truth"))
ggplot(est, aes(what, val, colour = kind)) +
  geom_hline(yintercept = mean(z), colour = te_line, linewidth = 0.5, linetype = "22") +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.12, linewidth = 0.8, na.rm = TRUE) +
  geom_point(size = 4) +
  geom_text(aes(label = sprintf("%.2f", val)), hjust = 0, nudge_x = 0.1, vjust = 0.5,
            size = 3.6, colour = te_ink) +
  scale_colour_manual(values = c(naive = te_red, model = te_forest, truth = te_gold), guide = "none") +
  scale_y_continuous(limits = c(0, 0.8)) +
  labs(title = "Occupancy model recovers what naive counting misses",
       subtitle = "200 sites, 4 visits, true detection p = 0.30",
       x = NULL, y = "Occupancy probability") +
  theme_te(13)

## ---- se ----
se_logit <- sqrt(diag(V))
se_psi <- se_logit[1] * psi_hat * (1 - psi_hat)
se_p   <- se_logit[2] * p_hat   * (1 - p_hat)
round(c(se_psi = se_psi, se_p = se_p), 3)
plogis(fit$par[1] + c(-1.96, 1.96) * se_logit[1])   # 95% CI for psi
plogis(fit$par[2] + c(-1.96, 1.96) * se_logit[2])   # 95% CI for p

## ---- fig-surface ----
gp <- seq(0.30, 0.90, length.out = 120); gq <- seq(0.10, 0.55, length.out = 120)
Z <- outer(gp, gq, Vectorize(function(P, Q) nll(c(qlogis(P), qlogis(Q)), y, K)))
dfz <- expand.grid(psi = gp, p = gq); dfz$nll <- as.vector(Z)
ggplot(dfz, aes(psi, p, z = nll)) +
  geom_raster(aes(fill = nll)) +
  geom_contour(colour = "#ffffff", alpha = 0.35, linewidth = 0.25, bins = 14) +
  scale_fill_gradient(low = te_deep, high = te_paper, name = "-log L") +
  annotate("point", x = psi_hat, y = p_hat, colour = te_gold, size = 3.2) +
  annotate("point", x = mean(z), y = p_true, colour = te_red, shape = 4, size = 3, stroke = 1.1) +
  annotate("text", x = psi_hat, y = p_hat, label = "  MLE", hjust = 0, colour = te_ink, size = 3.3) +
  labs(title = "Occupancy and detection are estimated jointly",
       subtitle = "Gold point: maximum-likelihood estimate; red cross: realised occupancy and true detection",
       x = "Occupancy psi", y = "Detection p") +
  theme_te(12)

## ---- k8 ----
set.seed(2026)
K8 <- 8L
z8 <- rbinom(R, 1, psi_true)
y8 <- matrix(rbinom(R * K8, 1, z8 * p_true), R, K8)
fit8 <- optim(c(0, 0), nll, y = y8, K = K8, method = "BFGS", hessian = TRUE)
stopifnot(fit8$convergence == 0)   # check before inverting the Hessian
se8 <- sqrt(diag(solve(fit8$hessian)))[1] * plogis(fit8$par[1]) * (1 - plogis(fit8$par[1]))
c(psi_hat = round(plogis(fit8$par[1]), 3),
  p_hat   = round(plogis(fit8$par[2]), 3),
  se_psi  = round(se8, 3))
