# How many visits? Occupancy survey design
# https://tidyecology.com/posts/survey-design-detection-visits/
#
# 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-10-07

## ---- 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))
}

## ---- fig-cumdet ----
K_seq <- 1:10; ps <- c(0.2, 0.3, 0.4, 0.5)
cd <- expand.grid(K = K_seq, p = ps)
cd$cum <- 1 - (1 - cd$p)^cd$K
cd$plab <- factor(sprintf("p = %.1f", cd$p))
ggplot(cd, aes(K, cum, colour = plab)) +
  geom_hline(yintercept = 0.95, colour = te_red, linewidth = 0.5, linetype = "22") +
  annotate("text", x = 1, y = 0.985, label = "95% target", hjust = 0, colour = te_red, size = 3.2) +
  geom_line(linewidth = 0.9) + geom_point(size = 1.6) +
  scale_colour_manual(values = c("p = 0.2"=te_gold, "p = 0.3"=te_green,
                                 "p = 0.4"=te_sage, "p = 0.5"=te_deep), name = NULL) +
  scale_x_continuous(breaks = 1:10) +
  scale_y_continuous(limits = c(0, 1), labels = scales::percent_format(1)) +
  labs(title = "How many visits to be sure you would detect it?",
       subtitle = "Cumulative detection at an occupied site: 1 - (1 - p) to the power K",
       x = "Visits per site (K)", y = "Probability of at least one detection") +
  theme_te(13)

## ---- min-visits ----
p_grid <- c(0.15, 0.20, 0.30, 0.40, 0.50)
data.frame(p = p_grid,
           visits_for_95 = ceiling(log(0.05) / log(1 - p_grid)))

## ---- fisher ----
asymp_se_psi <- function(psi, p, K, R) {
  d  <- 0:K
  Pd <- ifelse(d >= 1, psi * choose(K, d) * p^d * (1 - p)^(K - d),
               psi * (1 - p)^K + (1 - psi))
  A0 <- psi * (1 - p)^K + (1 - psi)
  s_psi <- ifelse(d >= 1, 1 / psi, ((1 - p)^K - 1) / A0)
  s_p   <- ifelse(d >= 1, d / p - (K - d) / (1 - p), psi * (-K) * (1 - p)^(K - 1) / A0)
  I <- matrix(c(sum(Pd * s_psi^2), sum(Pd * s_psi * s_p),
                sum(Pd * s_psi * s_p), sum(Pd * s_p^2)), 2, 2)
  sqrt(solve(I)[1, 1] / R)
}

## ---- fig-design ----
B <- 600; psi0 <- 0.6; p0 <- 0.3
dd <- data.frame(K = 2:12)
dd$R  <- B / dd$K
dd$se <- mapply(function(k, r) asymp_se_psi(psi0, p0, k, r), dd$K, dd$R)
kmin <- dd$K[which.min(dd$se)]
ggplot(dd, aes(K, se)) +
  geom_line(colour = te_forest, linewidth = 1) +
  geom_point(size = 2, colour = te_forest) +
  geom_point(data = subset(dd, K == kmin), colour = te_gold, size = 3.6) +
  annotate("text", x = kmin, y = min(dd$se),
           label = sprintf(" best: %d visits, %d sites", kmin, B / kmin),
           hjust = 0, vjust = 2.1, colour = te_ink, size = 3.3) +
  scale_x_continuous(breaks = 2:12) +
  scale_y_continuous(expand = expansion(mult = c(0.12, 0.05))) +
  labs(title = "A fixed budget has an optimal visits-per-site",
       subtitle = "Asymptotic standard error of occupancy under 600 total surveys (psi = 0.6, p = 0.3)",
       x = "Visits per site K (sites = 600 / K)", y = "Standard error of occupancy estimate") +
  theme_te(12)

## ---- se-table ----
dd$se <- round(dd$se, 4)
dd[, c("K", "R", "se")]
