# Nest survival with logistic exposure in R
# https://tidyecology.com/posts/nest-survival-logistic-exposure/
#
# 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

## ---- setup ----
library(ggplot2)
library(dplyr)

## ---- theme ----
te_ink <- "#16241d"; te_body <- "#2c3a31"; te_forest <- "#275139"
te_label <- "#46604a"; te_sage <- "#93a87f"; te_paper <- "#f5f4ee"
te_line <- "#dad9ca"; te_gold <- "#c9b458"; te_deep <- "#1d5b4e"
te_brick <- "#b5534e"; te_faint <- "#5d6b61"
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"),
          plot.subtitle = element_text(colour = te_faint),
          axis.title = element_text(colour = te_label),
          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.background = element_rect(fill = te_paper, colour = NA),
          legend.position = "none")
}

## ---- link ----
logexp <- function(exposure = 1) {
  linkfun <- function(mu) qlogis(mu^(1 / exposure))
  linkinv <- function(eta) plogis(eta)^exposure
  mu.eta  <- function(eta) exposure * plogis(eta)^(exposure - 1) *
                           plogis(eta) * (1 - plogis(eta))
  valideta <- function(eta) TRUE
  structure(list(linkfun = linkfun, linkinv = linkinv, mu.eta = mu.eta,
                 valideta = valideta, name = "logexp"), class = "link-glm")
}

## ---- data ----
set.seed(430)
period <- 28
dsr_true <- function(age) plogis(2.2 + 0.045 * age)     # daily survival rises with age
n_nests <- 220
rows <- list(); fledged <- 0
for (i in seq_len(n_nests)) {
  age <- sample(0:6, 1)                                  # age when found
  alive <- TRUE
  while (age < period && alive) {
    interval <- min(sample(3:5, 1), period - age)
    survived <- 1L
    for (dd in seq_len(interval)) {
      if (runif(1) > dsr_true(age + dd - 1)) { survived <- 0L; break }
    }
    # the observer only sees the visit dates, so a failed interval still
    # carries its full length as exposure: the fate day is unknown;
    # age_mid is the middle of the days at risk, age to age + interval - 1
    rows[[length(rows) + 1]] <- data.frame(nest = i, age_mid = age + (interval - 1) / 2,
                                           exposure = interval, survive = survived)
    if (survived == 0L) alive <- FALSE else age <- age + interval
  }
  if (alive) fledged <- fledged + 1
}
d <- do.call(rbind, rows)
c(nests = n_nests, intervals = nrow(d), failures = sum(d$survive == 0),
  exposure_days = sum(d$exposure))

## ---- naive-mayfield ----
naive_success <- fledged / n_nests
may_exposure <- ifelse(d$survive == 1L, d$exposure, d$exposure / 2)
mayfield_dsr <- 1 - sum(d$survive == 0) / sum(may_exposure)
c(naive_apparent_success = round(naive_success, 3),
  mayfield_daily_survival = round(mayfield_dsr, 4),
  mayfield_period_survival = round(mayfield_dsr^period, 3))

## ---- fit ----
m0 <- glm(survive ~ 1,       family = binomial(link = logexp(d$exposure)), data = d)
m1 <- glm(survive ~ age_mid, family = binomial(link = logexp(d$exposure)), data = d)
round(summary(m1)$coefficients, 4)
c(AIC_constant = round(AIC(m0), 1), AIC_age = round(AIC(m1), 1),
  delta_AIC = round(AIC(m0) - AIC(m1), 1))

## ---- dsr-by-age ----
b <- coef(m1)
ages <- c(2, 14, 26)
data.frame(age = ages,
           fitted_DSR = round(plogis(b[1] + b[2] * ages), 3),
           true_DSR = round(dsr_true(ages), 3))

## ---- fig-dsr ----
nd <- data.frame(age_mid = seq(0, period, by = 0.5))
pr <- predict(m1, nd, type = "link", se.fit = TRUE)
nd$dsr <- plogis(pr$fit)
nd$lo <- plogis(pr$fit - 1.96 * pr$se.fit)
nd$hi <- plogis(pr$fit + 1.96 * pr$se.fit)

ggplot(nd, aes(age_mid, dsr)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = te_forest, alpha = 0.16) +
  geom_hline(yintercept = mayfield_dsr, colour = te_gold, linetype = "42", linewidth = 0.8) +
  geom_line(colour = te_forest, linewidth = 1.0) +
  annotate("text", x = 1, y = mayfield_dsr - 0.012, label = "constant Mayfield rate",
           colour = "#8a7a30", hjust = 0, size = 3.1) +
  annotate("text", x = 20, y = 0.945, label = "logistic-exposure fit",
           colour = te_forest, hjust = 0, size = 3.1) +
  labs(title = "Daily nest survival rises with age",
       subtitle = "The exposure model recovers a gradient the constant rate cannot show",
       x = "Nest age (days)", y = "Daily survival rate") +
  theme_te()

## ---- fig-period ----
day <- 0:period
surv_age  <- c(1, cumprod(plogis(b[1] + b[2] * (0:(period - 1)))))
surv_const <- mayfield_dsr^day
pdf <- bind_rows(
  data.frame(day = day, S = surv_age,  model = "Age-varying (logistic exposure)"),
  data.frame(day = day, S = surv_const, model = "Constant (Mayfield)"))

ggplot(pdf, aes(day, S, colour = model)) +
  geom_line(linewidth = 0.95) +
  scale_colour_manual(values = c("Age-varying (logistic exposure)" = te_forest,
                                 "Constant (Mayfield)" = te_gold)) +
  annotate("text", x = 28, y = surv_age[period + 1] + 0.05, label = "age-varying",
           colour = te_forest, hjust = 1, size = 3.1) +
  annotate("text", x = 20, y = 0.24, label = "constant", colour = "#8a7a30", hjust = 0, size = 3.1) +
  coord_cartesian(ylim = c(0, 1)) +
  labs(title = "Survival across the nesting cycle",
       subtitle = "Age-specific daily rates compound differently from a single pooled rate",
       x = "Day of cycle", y = "Cumulative survival") +
  theme_te()
