# Eviction and mesh size in an IPM
# https://tidyecology.com/posts/ipm-eviction-and-mesh/
#
# 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 ----
library(ggplot2)
library(dplyr)

te <- list(ink="#16241d", body="#2c3a31", forest="#275139", label="#46604a",
           sage="#93a87f", paper="#f5f4ee", line="#dad9ca", faint="#5d6b61", rust="#b5534e")
theme_te <- function(base_size = 11) {
  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.02)),
          plot.subtitle = element_text(colour = te$faint, size = rel(0.9)),
          axis.title = element_text(colour = te$label),
          axis.text = element_text(colour = te$faint),
          panel.grid.major = element_line(colour = te$line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          panel.background = element_rect(fill = te$paper, colour = NA),
          plot.background = element_rect(fill = te$paper, colour = NA),
          legend.key = element_rect(fill = te$paper, colour = NA),
          strip.text = element_text(colour = te$forest, face = "bold"))
}

pars <- list(a_s=-1.4, b_s=0.50, a_g=1.9, b_g=0.65, sig_g=0.90,
             a_f=-6.0, b_f=0.80, a_r=0.42, b_r=0.24, mu_r=2.2, sig_r=0.70)

## ---- kernel-builder ----
build_K <- function(L, U, m, correct = FALSE) {
  h    <- (U - L) / m
  mesh <- L + (1:m - 0.5) * h
  S  <- plogis(pars$a_s + pars$b_s * mesh)
  G  <- outer(mesh, mesh, function(zp, z) dnorm(zp, pars$a_g + pars$b_g * z, pars$sig_g))
  Cr <- dnorm(mesh, pars$mu_r, pars$sig_r)
  if (correct) {
    G  <- sweep(G, 2, colSums(G) * h, "/")   # each growth column integrates to 1
    Cr <- Cr / (sum(Cr) * h)                 # recruit-size density integrates to 1
  }
  P  <- sweep(G, 2, S, "*") * h
  Pf <- plogis(pars$a_f + pars$b_f * mesh)
  Rn <- exp(pars$a_r + pars$b_r * mesh)
  Fk <- outer(Cr, Pf * Rn) * h
  list(K = P + Fk, mesh = mesh, h = h, S = S, retained = colSums(P))
}

## ---- eviction ----
m <- 100
tight  <- build_K(0, 8,  m, correct = FALSE)   # upper edge cuts off growth of large plants
tightc <- build_K(0, 8,  m, correct = TRUE)    # same bounds, eviction corrected
wide   <- build_K(0, 14, m, correct = FALSE)   # bounds cover the kernel; little is lost

lam_evict <- Re(eigen(tight$K)$values[1])
lam_corr  <- Re(eigen(tightc$K)$values[1])
lam_wide  <- Re(eigen(wide$K)$values[1])

widec <- build_K(0, 14, m, correct = TRUE)         # reference for the size distribution
w_ssd <- Re(eigen(widec$K)$vectors[, 1]); w_ssd <- w_ssd / sum(w_ssd)
q99    <- widec$mesh[which.max(cumsum(w_ssd) >= 0.99)]
above8 <- sum(w_ssd[widec$mesh > 8])

c(evicting = lam_evict, corrected = lam_corr, wide_bounds = lam_wide)

## ---- fig-eviction ----
d1 <- data.frame(z = tight$mesh, frac = tight$retained / tight$S)
min_ret <- min(d1$frac); edge_z <- d1$z[which.min(d1$frac)]
ggplot(d1, aes(z, frac)) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = te$faint, linewidth = 0.4) +
  geom_line(colour = te$forest, linewidth = 1) +
  annotate("point", x = edge_z, y = min_ret, colour = te$rust, size = 2.4) +
  scale_y_continuous(limits = c(0.8, 1.02)) +
  labs(x = "Size z at time t", y = "Fraction of survival retained") +
  theme_te(11)

## ---- mesh-convergence ----
ms    <- c(5, 10, 15, 20, 30, 50, 75, 100, 200, 500)
lam_m <- sapply(ms, function(mm) Re(eigen(build_K(0, 14, mm, correct = TRUE)$K)$values[1]))
lam_ref <- lam_m[length(lam_m)]
data.frame(m = ms, lambda = round(lam_m, 5), error = signif(lam_m - lam_ref, 2))

## ---- fig-mesh ----
d2 <- data.frame(m = ms, lambda = lam_m)
ggplot(d2, aes(m, lambda)) +
  geom_hline(yintercept = lam_ref, linetype = "dashed", colour = te$faint, linewidth = 0.4) +
  geom_line(colour = te$sage, linewidth = 0.7) +
  geom_point(colour = te$forest, size = 2.2) +
  scale_x_log10(breaks = ms) +
  scale_y_continuous(breaks = sort(c(0.95, 0.975, 1.0, round(lam_ref, 3))),
                     expand = expansion(mult = c(0.04, 0.10))) +
  labs(x = "Mesh size m (number of bins, log scale)", y = "Dominant eigenvalue lambda") +
  theme_te(11)
