# Occupancy turnover and equilibrium
# https://tidyecology.com/posts/occupancy-turnover-and-equilibrium/
#
# 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-08

## ---- fit ----
set.seed(141)
R <- 300; Tn <- 8; K <- 4
psi1 <- 0.75; gamma <- 0.15; eps <- 0.25; p <- 0.40
z <- matrix(0L, R, Tn); z[, 1] <- rbinom(R, 1, psi1)
for (t in 2:Tn) z[, t] <- rbinom(R, 1, ifelse(z[, t - 1] == 1, 1 - eps, gamma))
d <- matrix(0L, R, Tn); for (t in 1:Tn) d[, t] <- rbinom(R, K, z[, t] * p)

emit <- function(dt, p, K) c(as.numeric(dt == 0), p^dt * (1 - p)^(K - dt))
site_ll <- function(dv, init, Phi, p, K) {
  a <- init * emit(dv[1], p, K); s <- sum(a); ll <- log(s); a <- a / s
  for (t in 2:length(dv)) {
    a <- as.vector(a %*% Phi) * emit(dv[t], p, K)
    s <- sum(a); ll <- ll + log(s); a <- a / s
  }
  ll
}
nll <- function(par, dat) {
  ps <- plogis(par[1]); ga <- plogis(par[2]); ep <- plogis(par[3]); pp <- plogis(par[4])
  Phi <- matrix(c(1 - ga, ga, ep, 1 - ep), 2, 2, byrow = TRUE)
  -sum(apply(dat, 1, site_ll, init = c(1 - ps, ps), Phi = Phi, p = pp, K = K))
}
fitfun <- function(dat) optim(c(0, qlogis(0.2), qlogis(0.2), qlogis(0.3)), nll,
                              dat = dat, method = "BFGS")
fit <- fitfun(d)
est <- plogis(fit$par); names(est) <- c("psi1", "gamma", "eps", "p")
round(est, 3)

## ---- derived ----
psi_eq <- unname(est["gamma"] / (est["gamma"] + est["eps"]))
psit <- numeric(Tn); psit[1] <- est["psi1"]
for (t in 2:Tn) psit[t] <- psit[t - 1] * (1 - est["eps"]) + (1 - psit[t - 1]) * est["gamma"]
lambda <- psit[-1] / psit[-Tn]
turnover_eq <- (1 - psi_eq) * est["gamma"] / psi_eq   # colonised share of occupied at equilibrium
round(c(equilibrium = psi_eq, turnover = turnover_eq,
        growth_first = lambda[1], growth_last = lambda[Tn - 1]), 3)

## ---- fig-trajectory-band ----
suppressMessages({library(ggplot2); library(dplyr)})
theme_te <- function(bs = 12) theme_minimal(base_size = bs) + theme(
  plot.background = element_rect(fill = "#f5f4ee", colour = NA),
  panel.background = element_rect(fill = "#f5f4ee", colour = NA),
  panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
  panel.grid.minor = element_blank(),
  axis.text = element_text(colour = "#2c3a31"), axis.title = element_text(colour = "#16241d"),
  plot.title = element_text(colour = "#16241d", face = "bold"),
  plot.subtitle = element_text(colour = "#46604a"),
  legend.text = element_text(colour = "#2c3a31"), legend.position = "top",
  legend.key = element_rect(fill = "#f5f4ee", colour = NA))

simdat <- function(pr) {
  zz <- matrix(0L, R, Tn); zz[, 1] <- rbinom(R, 1, pr[1])
  for (t in 2:Tn) zz[, t] <- rbinom(R, 1, ifelse(zz[, t - 1] == 1, 1 - pr[3], pr[2]))
  dd <- matrix(0L, R, Tn); for (t in 1:Tn) dd[, t] <- rbinom(R, K, zz[, t] * pr[4]); dd
}
set.seed(1411); B <- 200; trb <- matrix(NA, B, Tn); eqb <- numeric(B)
for (b in 1:B) {
  fb <- plogis(fitfun(simdat(est))$par)
  eqb[b] <- fb[2] / (fb[2] + fb[3])
  tt <- numeric(Tn); tt[1] <- fb[1]
  for (t in 2:Tn) tt[t] <- tt[t - 1] * (1 - fb[3]) + (1 - tt[t - 1]) * fb[2]
  trb[b, ] <- tt
}
band <- data.frame(season = 1:Tn, lo = apply(trb, 2, quantile, 0.025),
                   hi = apply(trb, 2, quantile, 0.975))
df1 <- data.frame(season = 1:Tn, psit = psit, naive = colMeans(d > 0))
ggplot() +
  geom_ribbon(data = band, aes(season, ymin = lo, ymax = hi), fill = "#93a87f", alpha = 0.35) +
  geom_hline(yintercept = psi_eq, linetype = "dashed", colour = "#1d5b4e", linewidth = 0.5) +
  annotate("text", x = 2.5, y = psi_eq + 0.02, label = "equilibrium 0.36",
           colour = "#1d5b4e", size = 3, hjust = 1, family = "mono") +
  geom_line(data = df1, aes(season, psit), colour = "#275139", linewidth = 0.9) +
  geom_point(data = df1, aes(season, psit), colour = "#275139", size = 2.4) +
  geom_point(data = df1, aes(season, naive), colour = "#cda23f", shape = 15, size = 2.2) +
  geom_line(data = df1, aes(season, naive), colour = "#cda23f", linewidth = 0.5, linetype = "dotted") +
  scale_x_continuous(breaks = 1:Tn) + coord_cartesian(ylim = c(0.25, 0.85)) +
  labs(x = "Primary period (season)", y = "Occupancy") +
  theme_te()

## ---- bootstrap-ci ----
round(c(equilibrium = psi_eq, lo = quantile(eqb, 0.025)[[1]], hi = quantile(eqb, 0.975)[[1]],
        season8 = psit[Tn], s8_lo = band$lo[Tn], s8_hi = band$hi[Tn]), 3)

## ---- fig-transient ----
proj <- function(p1, g, e, H) {
  v <- numeric(H); v[1] <- p1
  for (t in 2:H) v[t] <- v[t - 1] * (1 - e) + (1 - v[t - 1]) * g
  v
}
H <- 12
tr2 <- bind_rows(
  data.frame(season = 1:H, occ = proj(0.85, est["gamma"], est["eps"], H),
             start = "Start above equilibrium (0.85)"),
  data.frame(season = 1:H, occ = proj(0.20, est["gamma"], est["eps"], H),
             start = "Start below equilibrium (0.20)"))
ggplot(tr2, aes(season, occ, colour = start)) +
  geom_hline(yintercept = psi_eq, linetype = "dashed", colour = "#1d5b4e", linewidth = 0.5) +
  annotate("text", x = 11.5, y = psi_eq + 0.03, label = "equilibrium",
           colour = "#1d5b4e", size = 3, hjust = 1, family = "mono") +
  geom_line(linewidth = 1) + geom_point(size = 2) +
  scale_colour_manual(values = c("Start above equilibrium (0.85)" = "#b5534e",
    "Start below equilibrium (0.20)" = "#2f8f63")) +
  scale_x_continuous(breaks = seq(2, H, 2)) + coord_cartesian(ylim = c(0.1, 0.9)) +
  labs(x = "Primary period (season)", y = "Occupancy", colour = NULL) +
  theme_te() + guides(colour = guide_legend(nrow = 2))
