# The incidence function model
# https://tidyecology.com/posts/incidence-function-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-10-14

## ---- landscape ----
Efun <- function(A, mu, x) pmin(1, mu / A^x)
conn <- function(o, D, A, alpha) {
  M <- exp(-alpha * D) * outer(rep(1, length(A)), A)
  diag(M) <- 0
  as.numeric(M %*% o)
}
Cfun <- function(S, y) S^2 / (S^2 + y^2)

set.seed(2024)
K <- 6; per <- 26
centres <- cbind(runif(K, 3, 25), runif(K, 3, 25))
clus <- do.call(rbind, lapply(1:K, function(k)
  cbind(rnorm(per, centres[k, 1], 1.3), rnorm(per, centres[k, 2], 1.3))))
iso <- cbind(runif(44, 1, 27), runif(44, 1, 27))
patch <- rbind(clus, iso)
n <- nrow(patch)
A <- rlnorm(n, meanlog = 0, sdlog = 0.9)   # patch areas
D <- as.matrix(dist(patch))
n

## ---- 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)), "}$")
}

## ---- snapshot ----
mu_t <- 0.8; x_t <- 1.0; y_t <- 2.5; alpha_t <- 0.6
Etrue <- Efun(A, mu_t, x_t)
o <- as.integer(runif(n) < 0.5)
set.seed(303)
for (t in 1:2000) {
  S <- conn(o, D, A, alpha_t); C <- Cfun(S, y_t)
  new <- o; emp <- o == 0L; occ <- o == 1L
  new[emp]  <- as.integer(runif(sum(emp))  < C[emp])
  new[occ]  <- as.integer(runif(sum(occ)) >= Etrue[occ])
  o <- new
}
n_occ <- sum(o)
n_occ

## ---- fig-map ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
dfm <- data.frame(x = patch[, 1], y = patch[, 2], area = A,
                  state = ifelse(o == 1L, "occupied", "empty"))
ggplot(dfm, aes(x, y, size = area, fill = state)) +
  geom_point(shape = 21, colour = "#46604a", stroke = 0.4, alpha = 0.85) +
  scale_size_area(max_size = 7, guide = "none") +
  scale_fill_manual(values = c(occupied = "#275139", empty = "#f5f4ee"), name = NULL) +
  coord_equal() +
  labs(x = "east", y = "north") +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top")

## ---- fit ----
af <- 0.6
S_obs <- conn(o, D, A, af)
nll <- function(p) {
  mu <- exp(p[1]); x <- exp(p[2]); y <- exp(p[3])
  C <- Cfun(S_obs, y); E <- Efun(A, mu, x)
  J <- pmin(pmax(C / (C + E), 1e-9), 1 - 1e-9)
  -sum(dbinom(o, 1, J, log = TRUE))
}
fit <- optim(log(c(0.5, 1, 2)), nll, method = "Nelder-Mead",
             control = list(maxit = 4000, reltol = 1e-12))
fit <- optim(fit$par, nll, method = "BFGS")
ph <- exp(fit$par)
mle <- -fit$value
setNames(round(ph, 3), c("mu", "x", "y"))

## ---- profile ----
prof <- function(idx) {
  g <- seq(log(0.05), log(30), length = 200)
  starts <- c(list(fit$par[-idx]),   # the fit, then a spread of starts for the other two
              asplit(as.matrix(expand.grid(log(c(0.2, 1, 5)), log(c(0.2, 1, 5)))), 1))
  pll <- function(v) {
    f <- function(q) { pp <- numeric(3); pp[idx] <- v; pp[-idx] <- q; nll(pp) }
    -min(sapply(starts, function(s) optim(optim(s, f)$par, f, method = "BFGS")$value))
  }
  ll <- sapply(g, pll)
  ok <- which(ll >= mle - 1.92)
  cross <- function(v) pll(v) - (mle - 1.92)   # each end lies between two grid points
  c(exp(uniroot(cross, g[c(min(ok) - 1, min(ok))], tol = 1e-8)$root),
    exp(uniroot(cross, g[c(max(ok), max(ok) + 1)], tol = 1e-8)$root))
}
ci <- t(sapply(1:3, prof))
rownames(ci) <- c("mu", "x", "y"); colnames(ci) <- c("lower", "upper")
round(ci, 3)

## ---- lrt ----
nll_area <- function(p) {
  mu <- exp(p[1]); x <- exp(p[2])
  E <- Efun(A, mu, x)
  J <- pmin(pmax(1 / (1 + E), 1e-9), 1 - 1e-9)
  -sum(dbinom(o, 1, J, log = TRUE))
}
starts0 <- list(log(c(0.5, 1)), log(c(2, 2)), log(c(10, 4)))
fits0 <- lapply(starts0, function(s) optim(s, nll_area, method = "BFGS"))
fit0 <- fits0[[which.min(sapply(fits0, `[[`, "value"))]]
dev <- 2 * (fit0$value - (-mle))
p_lrt <- pchisq(dev, df = 1, lower.tail = FALSE)
c(deviance = dev, p_value = p_lrt)

## ---- incidence ----
mu <- ph[1]; x <- ph[2]; y <- ph[3]
S <- conn(o, D, A, af)
C <- Cfun(S, y); E <- Efun(A, mu, x)
J <- C / (C + E)
acc <- mean((J > 0.5) == o)
c(mean_J_occupied = mean(J[o == 1]), mean_J_empty = mean(J[o == 0]), accuracy = acc)

## ---- fig-incidence ----
dfi <- data.frame(area = A, J = J, conn = S, occ = o)
ggplot(dfi, aes(log(area), J)) +
  geom_point(aes(colour = log1p(conn)), size = 2, alpha = 0.85) +
  scale_colour_gradient(low = "#c9b458", high = "#1d5b4e", name = "log connectivity") +
  geom_rug(data = subset(dfi, occ == 1), sides = "t", colour = "#275139", alpha = 0.5) +
  geom_rug(data = subset(dfi, occ == 0), sides = "b", colour = "#b5534e", alpha = 0.5) +
  labs(x = "log patch area", y = "fitted incidence (probability occupied)") +
  theme_minimal(base_size = 13) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "top")
