# Attributing one bad year to a warming trend
# https://tidyecology.com/posts/attributing-a-single-bad-year/
#
# 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-11-13

## ---- setup ----
library(ggplot2)
library(patchwork)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- design ----
n_yr    <- 40
yrs     <- seq_len(n_yr)
p_trig  <- 0.99
q_trig  <- qnorm(p_trig)

log_surv <- function(x, m, s) pnorm(x, m, s, lower.tail = FALSE, log.p = TRUE)

# least squares for every row of a matrix at once
ols_rows <- function(y_mat, tt) {
  t_c   <- tt - mean(tt)
  s_xx  <- sum(t_c^2)
  b_hat <- as.vector(y_mat %*% t_c) / s_xx
  a_hat <- rowMeans(y_mat) - b_hat * mean(tt)
  res   <- y_mat - a_hat - outer(b_hat, tt)
  s_hat <- sqrt(rowSums(res^2) / (length(tt) - 2))
  list(a = a_hat, b = b_hat, s = s_hat,
       tstat = b_hat / (s_hat / sqrt(s_xx)), dfree = length(tt) - 2)
}

t_cent   <- yrs - mean(yrs)
lever_w  <- t_cent[n_yr] / sum(t_cent^2)
trunc_mn <- dnorm(q_trig) / (1 - p_trig)
b_pred   <- lever_w * trunc_mn
shift_pred <- b_pred * (n_yr - 1)

## ---- example ----
set.seed(31907)
y_ex <- rnorm(n_yr)
y_ex[n_yr] <- qnorm(runif(1, p_trig, 1))
fit_in  <- ols_rows(matrix(y_ex, 1), yrs)
fit_out <- ols_rows(matrix(y_ex[-n_yr], 1), yrs[-n_yr])
ex_lpr <- function(f) log_surv(y_ex[n_yr], f$a + f$b * n_yr, f$s) -
  log_surv(y_ex[n_yr], f$a + f$b, f$s)
ex_pr_in  <- exp(ex_lpr(fit_in))
ex_pr_out <- exp(ex_lpr(fit_out))

## ---- mainsim ----
n_rep  <- 1000
n_boot <- 200
b_grid <- c(0, 0.01, 0.02, 0.04)
fit_sets <- list(all = yrs, before = yrs[-n_yr], last30 = (n_yr - 29):n_yr)

sim_main <- function(b_true) {
  mu_t  <- b_true * yrs
  y_mat <- matrix(rnorm(n_rep * n_yr), n_rep) + rep(mu_t, each = n_rep)
  y_mat[, n_yr] <- mu_t[n_yr] + qnorm(runif(n_rep, p_trig, 1))
  x_ev <- y_mat[, n_yr]
  lpr_true <- log_surv(x_ev, mu_t[n_yr], 1) - log_surv(x_ev, mu_t[1], 1)
  per_fit <- lapply(fit_sets, function(tt) {
    f <- ols_rows(y_mat[, tt, drop = FALSE], tt)
    lpr <- log_surv(x_ev, f$a + f$b * n_yr, f$s) - log_surv(x_ev, f$a + f$b, f$s)
    bnd <- vapply(seq_len(n_rep), function(i) {
      y_b <- matrix(rnorm(n_boot * length(tt), 0, f$s[i]), n_boot) +
        rep(f$a[i] + f$b[i] * tt, each = n_boot)
      g <- ols_rows(y_b, tt)
      quantile(log_surv(x_ev[i], g$a + g$b * n_yr, g$s) -
                 log_surv(x_ev[i], g$a + g$b, g$s), c(0.05, 0.95), names = FALSE)
    }, numeric(2))
    data.frame(lpr = lpr, err = lpr - lpr_true, a_hat = f$a, b_hat = f$b, s_hat = f$s,
               att_t = pt(f$tstat, f$dfree, lower.tail = FALSE) < 0.05,
               att_boot = bnd[1, ] > 0,
               cover = bnd[1, ] <= lpr_true & bnd[2, ] >= lpr_true)
  })
  list(fits = per_fit, lpr_true = lpr_true, x_ev = x_ev)
}

set.seed(40115)
sims <- lapply(b_grid, sim_main)

main_tab <- do.call(rbind, lapply(seq_along(b_grid), function(k) {
  do.call(rbind, lapply(names(fit_sets), function(nm) {
    d <- sims[[k]]$fits[[nm]]
    data.frame(b = b_grid[k], fit = nm, med_pr = exp(median(d$lpr)),
               true_pr = exp(median(sims[[k]]$lpr_true)),
               med_err = median(d$err), att_t = mean(d$att_t),
               att_boot = mean(d$att_boot), cover = mean(d$cover),
               mean_b = mean(d$b_hat), mean_s = mean(d$s_hat))
  }))
}))
get_v <- function(bv, nm, col) main_tab[main_tab$b == bv & main_tab$fit == nm, col]
mc_se <- function(p) sqrt(p * (1 - p) / n_rep)
b0_slope_se <- sd(sims[[1]]$fits$all$b_hat) / sqrt(n_rep)

## ---- fig-lever ----
ex_df <- data.frame(year = yrs, y = y_ex, trig = yrs == n_yr)
line_df <- rbind(
  data.frame(year = yrs, y = fit_in$a + fit_in$b * yrs, fit = "all forty years"),
  data.frame(year = yrs, y = fit_out$a + fit_out$b * yrs, fit = "trigger year left out"))
p_ex <- ggplot(ex_df, aes(year, y)) +
  geom_line(data = line_df, aes(colour = fit), linewidth = 0.9) +
  geom_point(aes(fill = trig), shape = 21, colour = te_ink, size = 2.2,
             show.legend = FALSE) +
  scale_fill_manual(values = c(te_line, te_rust)) +
  scale_colour_manual(values = c(te_rust, te_forest), name = NULL) +
  labs(x = "year of record", y = "July temperature (SD units)",
       title = "One record, two lines",
       subtitle = "red point: the summer that started the analysis") +
  theme_datasheet() + theme(legend.position = "bottom")

slope_df <- rbind(
  data.frame(b_hat = sims[[1]]$fits$all$b_hat, fit = "all forty years"),
  data.frame(b_hat = sims[[1]]$fits$before$b_hat, fit = "trigger year left out"))
p_sl <- ggplot(slope_df, aes(b_hat, colour = fit)) +
  geom_vline(xintercept = 0, colour = te_body, linewidth = 0.5) +
  geom_vline(xintercept = b_pred, colour = te_rust, linetype = "dashed",
             linewidth = 0.7) +
  stat_density(geom = "line", position = "identity", linewidth = 0.9) +
  scale_colour_manual(values = c(te_rust, te_forest), name = NULL) +
  labs(x = "fitted slope (SD per year)", y = "density",
       title = "The trigger tilts the line",
       subtitle = "dashed: lever weight times truncated mean") +
  theme_datasheet() + theme(legend.position = "bottom")

(p_ex | p_sl) + plot_annotation(theme = theme_datasheet())

## ---- trendsum ----
row_02 <- function(nm, col) get_v(0.02, nm, col)
fold_02 <- exp(row_02("all", "med_err"))
fold_04 <- exp(get_v(0.04, "all", "med_err"))
fold_01 <- exp(get_v(0.01, "all", "med_err"))
fold_02_before <- exp(row_02("before", "med_err"))
cover_rng <- range(main_tab$cover[main_tab$fit == "before"])
cover_all_rng <- range(main_tab$cover[main_tab$fit == "all"])

# split the log error of the all-years fit into two partial errors:
# fitted line with the true SD of one, and true line with the fitted SD
decomp_tab <- do.call(rbind, lapply(seq_along(b_grid), function(k) {
  mu_t <- b_grid[k] * yrs
  x_ev <- sims[[k]]$x_ev
  lt   <- sims[[k]]$lpr_true
  part <- function(d) c(
    line_only = median(log_surv(x_ev, d$a_hat + d$b_hat * n_yr, 1) -
                         log_surv(x_ev, d$a_hat + d$b_hat, 1) - lt),
    sd_only = median(log_surv(x_ev, mu_t[n_yr], d$s_hat) -
                       log_surv(x_ev, mu_t[1], d$s_hat) - lt),
    both = median(d$err))
  data.frame(b = b_grid[k], fit = c("all", "before"),
             rbind(part(sims[[k]]$fits$all), part(sims[[k]]$fits$before)))
}))
get_d <- function(bv, nm, col) decomp_tab[decomp_tab$b == bv & decomp_tab$fit == nm, col]
# Monte Carlo standard error of a median from the order statistics around it
med_se <- function(v) {
  v <- sort(v); n <- length(v); h <- 1.96 * sqrt(n) / 2
  (v[ceiling(n / 2 + h)] - v[floor(n / 2 - h)]) / (2 * 1.96)
}
line_only_se <- max(vapply(seq_along(b_grid), function(k) {
  d <- sims[[k]]$fits$all
  med_se(log_surv(sims[[k]]$x_ev, d$a_hat + d$b_hat * n_yr, 1) -
           log_surv(sims[[k]]$x_ev, d$a_hat + d$b_hat, 1) - sims[[k]]$lpr_true)
}, numeric(1)))

## ---- fig-trend ----
fit_lab <- c(all = "all forty years", before = "trigger year left out",
             last30 = "last thirty years")
plot_tab <- main_tab
plot_tab$fit <- factor(fit_lab[plot_tab$fit], levels = fit_lab)
true_tab <- main_tab[main_tab$fit == "all", c("b", "true_pr")]
fit_cols <- c(te_rust, te_forest, te_gold)

p_pr <- ggplot(plot_tab, aes(b, med_pr, colour = fit)) +
  geom_line(data = true_tab, aes(b, true_pr), inherit.aes = FALSE,
            colour = te_ink, linetype = "dashed", linewidth = 0.6) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.2) +
  scale_y_log10() +
  scale_colour_manual(values = fit_cols, name = NULL) +
  labs(x = "true trend (SD per year)", y = "median probability ratio (log scale)",
       title = "The ratio runs high",
       subtitle = "dashed: median true ratio") +
  theme_datasheet() + theme(legend.position = "bottom")

p_att <- ggplot(plot_tab, aes(b, att_t, colour = fit)) +
  geom_hline(yintercept = 0.05, colour = te_ink, linetype = "dashed",
             linewidth = 0.6) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.2) +
  scale_y_continuous(limits = c(0, 1)) +
  scale_colour_manual(values = fit_cols, name = NULL) +
  labs(x = "true trend (SD per year)", y = "share of records attributed",
       title = "Attribution by the slope test",
       subtitle = "dashed: the nominal five per cent") +
  theme_datasheet() + theme(legend.position = "bottom")

(p_pr | p_att) + plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet() + theme(legend.position = "bottom"))

## ---- stopsim ----
eta <- q_trig
n_rep_stop <- 1000
b_stop <- c(0, 0.02)

nll_trend <- function(par, y, tt, cond) {
  m_t <- par[1] + par[2] * tt
  s_t <- exp(par[3])
  ll <- dnorm(y, m_t, s_t, log = TRUE)
  if (cond) {
    pre <- tt < n_yr
    ll[pre]  <- ll[pre] - pnorm(eta, m_t[pre], s_t, log.p = TRUE)
    ll[!pre] <- ll[!pre] - log_surv(eta, m_t[!pre], s_t)
  }
  v <- -sum(ll)
  if (is.finite(v)) v else 1e10
}

fit_trend <- function(y, drop_last, cond) {
  tt <- if (drop_last) yrs[-n_yr] else yrs
  yy <- y[tt]
  par_start <- c(coef(lm(yy ~ tt)), log(sd(yy)))
  o <- optim(par_start, nll_trend, y = yy, tt = tt, cond = cond,
             method = "BFGS", hessian = TRUE)
  se_b <- tryCatch(sqrt(diag(solve(o$hessian)))[2], error = function(e) NA_real_)
  c(o$par[1], o$par[2], exp(o$par[3]), o$par[2] / se_b)
}

stop_fits <- list(naive_all = c(FALSE, FALSE), naive_before = c(TRUE, FALSE),
                  cond_all = c(FALSE, TRUE), cond_before = c(TRUE, TRUE))

sim_stop <- function(b_true) {
  mu_t <- b_true * yrs
  p_below <- pnorm(eta - mu_t)
  res <- replicate(n_rep_stop, {
    u_draw <- c(runif(n_yr - 1, 0, p_below[-n_yr]), runif(1, p_below[n_yr], 1))
    y <- mu_t + qnorm(u_draw)
    x_ev <- y[n_yr]
    lt <- log_surv(x_ev, mu_t[n_yr], 1) - log_surv(x_ev, mu_t[1], 1)
    vapply(stop_fits, function(sw) {
      f <- fit_trend(y, sw[1], sw[2])
      c(err = log_surv(x_ev, f[1] + f[2] * n_yr, f[3]) -
          log_surv(x_ev, f[1] + f[2], f[3]) - lt,
        b_hat = f[2], att = f[4] > qnorm(0.95), lt = lt, s_hat = f[3],
        err_line = log_surv(x_ev, f[1] + f[2] * n_yr, 1) -
          log_surv(x_ev, f[1] + f[2], 1) - lt,
        err_sd = log_surv(x_ev, mu_t[n_yr], f[3]) -
          log_surv(x_ev, mu_t[1], f[3]) - lt)
    }, numeric(7))
  })
  data.frame(b = b_true, fit = names(stop_fits),
             med_err = apply(res[1, , ], 1, median),
             mean_b = apply(res[2, , ], 1, mean),
             se_b = apply(res[2, , ], 1, sd) / sqrt(n_rep_stop),
             att = apply(res[3, , ], 1, mean, na.rm = TRUE),
             true_pr = exp(median(res[4, 1, ])),
             med_s = apply(res[5, , ], 1, median),
             med_err_line = apply(res[6, , ], 1, median),
             med_err_sd = apply(res[7, , ], 1, median))
}

set.seed(52203)
stop_tab <- do.call(rbind, lapply(b_stop, sim_stop))
get_s <- function(bv, nm, col) stop_tab[stop_tab$b == bv & stop_tab$fit == nm, col]

## ---- fig-stopping ----
stop_lab <- c(naive_all = "naive, all years", naive_before = "naive, trigger left out",
              cond_all = "conditional", cond_before = "conditional, trigger left out")
stop_plot <- stop_tab
stop_plot$fit <- factor(stop_lab[stop_plot$fit], levels = rev(stop_lab))
stop_plot$trend <- factor(sprintf("true trend %.2f", stop_plot$b))
stop_cols <- c(te_rust, te_forest)
p_sb <- ggplot(stop_plot, aes(mean_b, fit, colour = trend)) +
  geom_vline(xintercept = b_stop, colour = stop_cols, linetype = "dashed",
             linewidth = 0.6) +
  geom_point(size = 2.8) +
  scale_colour_manual(values = stop_cols, name = NULL) +
  labs(x = "mean fitted slope (SD per year)", y = NULL,
       title = "Slope", subtitle = "dashed: the true trends") +
  theme_datasheet() + theme(legend.position = "bottom")
p_sa <- ggplot(stop_plot, aes(att, fit, colour = trend)) +
  geom_vline(xintercept = 0.05, colour = te_ink, linetype = "dashed",
             linewidth = 0.6) +
  geom_point(size = 2.8) +
  scale_x_continuous(limits = c(0, 1)) +
  scale_colour_manual(values = stop_cols, name = NULL) +
  labs(x = "share of records attributed", y = NULL,
       title = "Attribution", subtitle = "dashed: five per cent") +
  theme_datasheet() + theme(legend.position = "bottom",
                            axis.text.y = element_blank())
(p_sb | p_sa) + plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet() + theme(legend.position = "bottom"))

## ---- memsim ----
phi_mem   <- c(0.3, 0.5)
n_rep_mem <- 1000
yrs_kept  <- yrs[-n_yr]

# stationary AR(1) anomalies with SD one, simulated backwards from the last year
sim_memory <- function(phi, selected) {
  z_mat <- matrix(0, n_rep_mem, n_yr)
  z_mat[, n_yr] <- if (selected) qnorm(runif(n_rep_mem, p_trig, 1)) else rnorm(n_rep_mem)
  for (k in (n_yr - 1):1)
    z_mat[, k] <- phi * z_mat[, k + 1] + rnorm(n_rep_mem, 0, sqrt(1 - phi^2))
  z_mat
}
# years 1-39, trigger dropped: exact AR(1) likelihood (Prais-Winsten transform)
drop_design <- function(phi, y) {
  x_k <- cbind(1, yrs_kept); w <- sqrt(1 - phi^2); m <- length(yrs_kept)
  list(ys = c(w * y[1], y[2:m] - phi * y[1:(m - 1)]),
       xs = rbind(w * x_k[1, ], x_k[2:m, ] - phi * x_k[1:(m - 1), ]), ljac = log(w))
}
# years 1-39 given the trigger year: each year regressed on the year after it
cond_design <- function(phi, y) {
  list(ys = y[yrs_kept] - phi * y[yrs_kept + 1],
       xs = cbind(1 - phi, yrs_kept - phi * (yrs_kept + 1)), ljac = 0)
}
# slope t statistic from the transformed regression at a given phi
slope_at <- function(design, y, phi, n_par) {
  d <- design(phi, y)
  f <- lm.fit(d$xs, d$ys)
  s2 <- sum(f$residuals^2) / (length(d$ys) - n_par)
  b <- unname(f$coefficients[2])
  c(b = b, tstat = b / sqrt(s2 * solve(crossprod(d$xs))[2, 2]), phi = phi)
}
# phi profiled by maximum likelihood, then the slope test at phi-hat
ar_slope <- function(design, y) {
  prof <- function(phi) {
    d <- design(phi, y)
    -length(d$ys) / 2 * log(sum(lm.fit(d$xs, d$ys)$residuals^2) / length(d$ys)) + d$ljac
  }
  slope_at(design, y, optimize(prof, c(-0.95, 0.99), maximum = TRUE)$maximum, 3)
}
crit_ols <- qt(0.95, length(yrs_kept) - 2)
crit_ar  <- qt(0.95, length(yrs_kept) - 3)

set.seed(71146)
mem_tab <- do.call(rbind, lapply(phi_mem, function(phi) {
  do.call(rbind, lapply(c(TRUE, FALSE), function(sel) {
    z_mat <- sim_memory(phi, sel)
    f_ols <- ols_rows(z_mat[, yrs_kept], yrs_kept)
    f_gls <- apply(z_mat[, yrs_kept], 1, function(y) ar_slope(drop_design, y))
    f_cnd <- apply(z_mat, 1, function(y) ar_slope(cond_design, y))
    f_kno <- apply(z_mat, 1, function(y) slope_at(cond_design, y, phi, 2))
    data.frame(phi = phi, selected = sel,
               arm = c("OLS drop", "GLS drop", "conditional", "phi known"),
               att = c(mean(f_ols$tstat > crit_ols), mean(f_gls["tstat", ] > crit_ar),
                       mean(f_cnd["tstat", ] > crit_ar), mean(f_kno["tstat", ] > crit_ols)),
               mean_b = c(mean(f_ols$b), mean(f_gls["b", ]), mean(f_cnd["b", ]),
                          mean(f_kno["b", ])),
               se_b = c(sd(f_ols$b), sd(f_gls["b", ]), sd(f_cnd["b", ]),
                        sd(f_kno["b", ])) / sqrt(n_rep_mem),
               mean_phi = c(NA, mean(f_gls["phi", ]), mean(f_cnd["phi", ]), phi))
  }))
}))
get_m <- function(ph, sel, arm_nm, col)
  mem_tab[mem_tab$phi == ph & mem_tab$selected == sel & mem_tab$arm == arm_nm, col]

# the mean leak into the kept years: E[z_t | z_40] = phi^(40 - t) z_40
kept_c <- yrs_kept - mean(yrs_kept)
leak_pred <- vapply(phi_mem, function(phi)
  sum(kept_c * phi^(n_yr - yrs_kept)) * trunc_mn / sum(kept_c^2), numeric(1))

rate_mat <- tapply(mem_tab$att,
                   list(record = sprintf("phi %.1f %s", mem_tab$phi,
                                         ifelse(mem_tab$selected, "selected", "unselected")),
                        fit = factor(mem_tab$arm, levels = unique(mem_tab$arm))),
                   identity)
mem_se  <- function(p) sqrt(p * (1 - p) / n_rep_mem)
ols_sel <- mem_tab$arm == "OLS drop" & mem_tab$selected
leak_z  <- (mem_tab$mean_b[ols_sel] - leak_pred) / mem_tab$se_b[ols_sel]
known_z <- (mem_tab$att[mem_tab$arm == "phi known"] - 0.05) / mem_se(0.05)
print(round(rate_mat, 3))

## ---- gevsim ----
xi_true <- 0.1
g_one <- gamma(1 - xi_true)
g_two <- gamma(1 - 2 * xi_true)
sg_true <- xi_true / sqrt(g_two - g_one^2)
n_rep_gev <- 600
b_gev <- c(0, 0.02)

qgev <- function(p, mu, sg, xi) mu + sg * ((-log(p))^(-xi) - 1) / xi
log_surv_gev <- function(x, mu, sg, xi) {
  z_s <- 1 + xi * (x - mu) / sg
  if (z_s <= 0) return(if (xi < 0) -Inf else 0)
  w_s <- z_s^(-1 / xi)
  if (w_s < 1e-8) log(w_s) else log(-expm1(-w_s))
}
nll_gev <- function(par, y, tt) {
  m_t <- par[1] + par[2] * tt
  s_g <- exp(par[3])
  xi  <- par[4]
  z_s <- 1 + xi * (y - m_t) / s_g
  if (any(z_s <= 0) || abs(xi) < 1e-6) return(1e10)
  v <- sum(log(s_g) + (1 / xi + 1) * log(z_s) + z_s^(-1 / xi))
  if (is.finite(v)) v else 1e10
}
fit_gev <- function(y, tt) {
  yy <- y[tt]
  st <- coef(lm(yy ~ tt))
  s0 <- sqrt(6) * sd(yy) / pi
  o1 <- optim(c(st[1] - 0.5772 * s0, st[2], log(s0), 0.1), nll_gev,
              y = yy, tt = tt, method = "BFGS")
  nll_flat <- function(p3) nll_gev(c(p3[1], 0, p3[2], p3[3]), yy, tt)
  o0 <- optim(o1$par[-2], nll_flat, method = "BFGS")
  c(o1$par[1], o1$par[2], exp(o1$par[3]), o1$par[4],
    sign(o1$par[2]) * sqrt(max(0, 2 * (o0$value - o1$value))))
}

sim_gev <- function(b_true) {
  mu_t <- b_true * yrs
  res <- replicate(n_rep_gev, {
    y <- qgev(runif(n_yr), mu_t, sg_true, xi_true)
    y[n_yr] <- qgev(runif(1, p_trig, 1), mu_t[n_yr], sg_true, xi_true)
    x_ev <- y[n_yr]
    ls_end <- log_surv_gev(x_ev, mu_t[n_yr], sg_true, xi_true)
    lt <- ls_end - log_surv_gev(x_ev, mu_t[1], sg_true, xi_true)
    vapply(list(all = yrs, before = yrs[-n_yr]), function(tt) {
      f <- fit_gev(y, tt)
      l_end <- log_surv_gev(x_ev, f[1] + f[2] * n_yr, f[3], f[4])
      c(err = l_end - log_surv_gev(x_ev, f[1] + f[2], f[3], f[4]) - lt,
        p_err = l_end - ls_end, b_hat = f[2], xi_hat = f[4],
        att = f[5] > qnorm(0.95))
    }, numeric(5))
  })
  data.frame(b = b_true, fit = c("all", "before"),
             med_err = apply(res[1, , ], 1, function(v) median(v[is.finite(v)])),
             n_inf = apply(res[2, , ], 1, function(v) sum(!is.finite(v))),
             n_inf_pr = apply(res[1, , ], 1, function(v) sum(!is.finite(v))),
             med_p_err = apply(res[2, , ], 1, median),
             mean_b = apply(res[3, , ], 1, mean),
             med_xi = apply(res[4, , ], 1, median),
             att = apply(res[5, , ], 1, mean),
             xi_all = I(list(res[4, 1, ], res[4, 2, ])),
             att_rec = I(list(res[5, 1, ], res[5, 2, ])))
}

set.seed(63319)
gev_tab <- do.call(rbind, lapply(b_gev, sim_gev))
get_g <- function(bv, nm, col) gev_tab[gev_tab$b == bv & gev_tab$fit == nm, col]
mc_se_gev <- function(p) sqrt(p * (1 - p) / n_rep_gev)
gev_eff <- pi^2 / 6
n_inf_before <- sum(gev_tab$n_inf[gev_tab$fit == "before"])
n_inf_all    <- sum(gev_tab$n_inf[gev_tab$fit == "all"])
n_pr_before  <- sum(gev_tab$n_inf_pr[gev_tab$fit == "before"])
n_pr_all     <- sum(gev_tab$n_inf_pr[gev_tab$fit == "all"])
z_gev_all    <- (get_g(0, "all", "att") - 0.05) / mc_se_gev(get_g(0, "all", "att"))
z_gev_before <- (get_g(0, "before", "att") - 0.05) / mc_se_gev(get_g(0, "before", "att"))
# the two fits are run on the same records, so the difference is paired
att_pair     <- gev_tab$att_rec[[1]] - gev_tab$att_rec[[2]]
att_gap_se   <- mean(att_pair) / (sd(att_pair) / sqrt(n_rep_gev))

## ---- fig-gev ----
xi_df <- rbind(
  data.frame(xi_hat = gev_tab$xi_all[[1]], fit = "all forty years"),
  data.frame(xi_hat = gev_tab$xi_all[[2]], fit = "trigger year left out"))
ggplot(xi_df, aes(xi_hat, colour = fit)) +
  geom_vline(xintercept = xi_true, colour = te_ink, linetype = "dashed",
             linewidth = 0.6) +
  stat_density(geom = "line", position = "identity", linewidth = 0.9) +
  scale_colour_manual(values = c(te_rust, te_forest), name = NULL) +
  labs(x = "fitted shape", y = "density",
       title = "The trigger fattens the tail",
       subtitle = "no trend; dashed: the true shape of 0.1") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- reportnums ----
far <- function(pr) 1 - 1 / pr
far_0_all    <- far(get_v(0, "all", "med_pr"))
far_0_before <- far(get_v(0, "before", "med_pr"))
far_4_all    <- far(get_v(0.04, "all", "med_pr"))
far_4_before <- far(get_v(0.04, "before", "med_pr"))
