# False positives in occupancy models
# https://tidyecology.com/posts/false-positive-occupancy-models/
#
# 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-01

## ---- setup ----
library(ggplot2)
library(grid)

te_ink <- "#16241d"; te_forest <- "#275139"; te_gold <- "#c9b458"
te_rust <- "#b5534e"; te_sage <- "#93a87f"

theme_te <- function() {
  theme_minimal(base_size = 11) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "grey90", linewidth = 0.3),
          plot.title = element_text(colour = te_ink, face = "bold", size = 11),
          plot.subtitle = element_text(colour = "grey35", size = 9),
          axis.title = element_text(colour = te_ink, size = 9),
          axis.text = element_text(colour = "grey30", size = 8),
          legend.position = "bottom",
          legend.title = element_blank(),
          legend.text = element_text(size = 8))
}
two_panel <- function(p1, p2) {
  grid.newpage()
  pushViewport(viewport(layout = grid.layout(1, 2)))
  print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
  print(p2, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- data ----
set.seed(4274)
R <- 250L; K <- 5L
psi_t <- 0.10; p11_t <- 0.35; p10_t <- 0.05
z <- rbinom(R, 1L, psi_t)
Y <- matrix(rbinom(R * K, 1L, ifelse(rep(z, K) == 1, p11_t, p10_t)), R, K)
d <- rowSums(Y)

occupied <- sum(z)
detected <- sum(d > 0)
false_sites <- sum(d > 0 & z == 0)
naive <- mean(d > 0)

## ---- models ----
ct <- list(maxit = 8000, reltol = 1e-12)
fit_nm <- function(nll, start, se = TRUE, ...) {
  o <- optim(start, nll, ..., method = "Nelder-Mead", control = ct)
  o <- optim(o$par, nll, ..., method = "Nelder-Mead", control = ct)
  s <- rep(NA_real_, length(o$par))
  if (se) {
    H <- optimHess(o$par, nll, ...)
    s <- tryCatch(sqrt(diag(solve(H))),
                  error = function(e) rep(NA_real_, length(o$par)))
  }
  list(par = o$par, se = s, nll = o$value,
       aic = 2 * o$value + 2 * length(o$par))
}
occ_nll <- function(par, d, K) {
  psi <- plogis(par[1]); p <- plogis(par[2])
  pd <- psi * dbinom(0:K, K, p) + c(1 - psi, rep(0, K))
  -sum(log(pmax(pd[d + 1], 1e-300)))
}
fp_nll <- function(par, d, K) {
  psi <- plogis(par[1]); p11 <- plogis(par[2]); p10 <- plogis(par[3])
  pd <- psi * dbinom(0:K, K, p11) + (1 - psi) * dbinom(0:K, K, p10)
  -sum(log(pmax(pd[d + 1], 1e-300)))
}
f_occ <- fit_nm(occ_nll, c(0, 0), d = d, K = K)
f_fp <- fit_nm(fp_nll, c(0, qlogis(0.4), qlogis(0.05)), d = d, K = K)

psi_occ <- plogis(f_occ$par[1])
ci_occ <- plogis(f_occ$par[1] + c(-1.96, 1.96) * f_occ$se[1])
psi_fp <- plogis(f_fp$par[1])
ci_fp <- plogis(f_fp$par[1] + c(-1.96, 1.96) * f_fp$se[1])
implied_missed <- R * psi_occ - detected

## ---- fp-fit ----
p11_hat <- plogis(f_fp$par[2]); p10_hat <- plogis(f_fp$par[3])

## ---- swap ----
mirror <- c(-f_fp$par[1], f_fp$par[3], f_fp$par[2])
nll_mle <- fp_nll(f_fp$par, d, K)
nll_mirror <- fp_nll(mirror, d, K)
gap <- abs(nll_mle - nll_mirror)

## ---- fp-guard-1 ----
stopifnot(gap / abs(nll_mle) < 1e-10)

## ---- profile ----
prof_fp <- function(psi_fix, d, K, starts) {
  f <- function(q) {
    pd <- psi_fix * dbinom(0:K, K, plogis(q[1])) +
          (1 - psi_fix) * dbinom(0:K, K, plogis(q[2]))
    -sum(log(pmax(pd[d + 1], 1e-300)))
  }
  min(sapply(starts, function(s) {
    o <- optim(s, f, method = "Nelder-Mead", control = ct)
    optim(o$par, f, method = "Nelder-Mead", control = ct)$value
  }))
}
psi_g <- seq(0.02, 0.98, length.out = 49)
lo_hi <- c(qlogis(0.4), qlogis(0.05)); hi_lo <- c(qlogis(0.05), qlogis(0.4))
prof <- sapply(psi_g, prof_fp, d = d, K = K, starts = list(lo_hi, hi_lo))
prof_one <- sapply(psi_g, prof_fp, d = d, K = K, starts = list(lo_hi))
dev_fp <- 2 * (prof - min(prof))
dev_one <- 2 * (prof_one - min(prof_one))
sym_gap <- max(abs(dev_fp - rev(dev_fp)))
sym_one <- max(abs(dev_one - rev(dev_one)))

## ---- fig-swap ----
obs <- as.numeric(table(factor(d, levels = 0:K)))
e_occ <- R * (psi_occ * dbinom(0:K, K, plogis(f_occ$par[2])) +
              c(1 - psi_occ, rep(0, K)))
e_fp <- R * (psi_fp * dbinom(0:K, K, p11_hat) + (1 - psi_fp) * dbinom(0:K, K, p10_hat))
dfa <- data.frame(d = rep(0:K, 2), count = c(e_occ, e_fp),
                  model = rep(c("standard occupancy", "false-positive model"),
                              each = K + 1))
pa <- ggplot() +
  geom_col(data = data.frame(d = 0:K, count = obs), aes(d, count),
           fill = te_sage, alpha = 0.55, width = 0.75) +
  geom_line(data = dfa, aes(d, count, colour = model), linewidth = 0.7) +
  geom_point(data = dfa, aes(d, count, colour = model), size = 1.6) +
  scale_colour_manual(values = c("standard occupancy" = te_rust,
                                 "false-positive model" = te_forest)) +
  scale_x_continuous(breaks = 0:K) +
  labs(title = "Observed and fitted detection frequencies", x = "detections out of five", y = "sites",
       subtitle = "bars: observed") +
  theme_te()

pb <- ggplot(data.frame(psi = psi_g, dev = dev_fp), aes(psi, dev)) +
  geom_vline(xintercept = 0.5, linetype = "dotted", colour = "grey45") +
  geom_line(linewidth = 0.8, colour = te_forest) +
  geom_vline(xintercept = psi_t, linetype = "dashed", colour = te_ink,
             linewidth = 0.3) +
  labs(title = "The likelihood has two answers", x = "occupancy",
       y = "profile deviance",
       subtitle = "dashed: truth. dotted: the axis of symmetry") +
  theme_te()
two_panel(pa, pb)

## ---- sweep ----
psi_seq <- c(0.05, 0.10, 0.20, 0.30, 0.45, 0.60)
M <- 120L
sweep <- do.call(rbind, lapply(psi_seq, function(ps) {
  est <- t(sapply(1:M, function(m) {
    set.seed(70000L + m + round(ps * 1000))
    zz <- rbinom(R, 1L, ps)
    dd <- rowSums(matrix(rbinom(R * K, 1L,
      ifelse(rep(zz, K) == 1, p11_t, p10_t)), R, K))
    f_a <- fit_nm(fp_nll, c(0, qlogis(0.4), qlogis(0.05)), se = FALSE, d = dd, K = K)
    f_b <- fit_nm(fp_nll, c(0, qlogis(0.05), qlogis(0.4)), se = FALSE, d = dd, K = K)
    f_f <- if (f_b$nll < f_a$nll) f_b else f_a          # one start in each well
    c(occ = plogis(fit_nm(occ_nll, c(0, 0), se = FALSE, d = dd, K = K)$par[1]),
      fp = plogis(if (f_f$par[2] > f_f$par[3]) f_f$par[1] else -f_f$par[1]))  # label by p11 > p10
  }))
  data.frame(psi = ps, model = c("standard occupancy", "false-positive model"),
             bias = c(mean(est[, "occ"]) - ps, mean(est[, "fp"]) - ps))
}))
b_low <- sweep$bias[sweep$psi == 0.05 & sweep$model == "standard occupancy"]
b_high <- sweep$bias[sweep$psi == 0.60 & sweep$model == "standard occupancy"]

## ---- fig-bias ----
lv <- c("naive", "standard occupancy", "false-positive model")
df1 <- data.frame(what = factor(lv, levels = lv), est = c(naive, psi_occ, psi_fp))
df_ci <- data.frame(what = factor(lv[-1], levels = lv),
                    lo = c(ci_occ[1], ci_fp[1]), hi = c(ci_occ[2], ci_fp[2]))
p1 <- ggplot(df1, aes(est, what)) +
  geom_vline(xintercept = psi_t, linetype = "dashed", colour = te_ink,
             linewidth = 0.4) +
  geom_errorbar(data = df_ci, aes(y = what, xmin = lo, xmax = hi),
                inherit.aes = FALSE, orientation = "y", width = 0.12, colour = te_forest,
                linewidth = 0.7) +
  geom_point(size = 2.6, colour = te_rust) +
  labs(title = "One in twenty visits was wrong", x = "estimated occupancy", y = NULL,
       subtitle = "dashed: the truth, 0.10") +
  theme_te()

p2 <- ggplot(sweep, aes(psi, bias, colour = model)) +
  geom_hline(yintercept = 0, linetype = "dashed", colour = te_ink, linewidth = 0.3) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 1.7) +
  scale_colour_manual(values = c("standard occupancy" = te_rust,
                                 "false-positive model" = te_forest)) +
  labs(title = "The rarer the species, the worse", x = "true occupancy",
       y = "mean bias in estimated occupancy",
       subtitle = "120 replicates per point") +
  theme_te()
two_panel(p1, p2)

## ---- miller ----
set.seed(4275)
b_t <- 0.40
W <- matrix(0L, R, K)
for (i in 1:R) for (k in 1:K) {
  if (Y[i, k] == 1) {
    W[i, k] <- if (z[i] == 1 && rbinom(1, 1, b_t) == 1) 2L else 1L
  }
}
n1 <- rowSums(W == 1); n2 <- rowSums(W == 2); n0 <- K - n1 - n2

mil_nll <- function(par, n0, n1, n2, K) {
  psi <- plogis(par[1]); p11 <- plogis(par[2])
  p10 <- plogis(par[3]); b <- plogis(par[4])
  occ <- (1 - p11)^n0 * (p11 * (1 - b))^n1 * (p11 * b)^n2
  unocc <- ifelse(n2 > 0, 0, (1 - p10)^n0 * p10^n1)
  -sum(log(pmax(psi * occ + (1 - psi) * unocc, 1e-300)))
}
f_mil <- fit_nm(mil_nll, c(0, qlogis(0.4), qlogis(0.05), 0),
                n0 = n0, n1 = n1, n2 = n2, K = K)
psi_mil <- plogis(f_mil$par[1])
ci_mil <- plogis(f_mil$par[1] + c(-1.96, 1.96) * f_mil$se[1])
certain_sites <- sum(n2 > 0)
