# Fishing, age truncation and spawning variability
# https://tidyecology.com/posts/fishing-and-age-truncation/
#
# 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

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

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))
}

## ---- model ----
n_age   <- 25
m_nat   <- 0.2
sd_rec  <- 0.5
cv_rec  <- sqrt(exp(sd_rec^2) - 1)
lag_max <- 600

make_stock <- function(age_mat = 5, h_steep = 0.7) {
  ages <- seq_len(n_age)
  fec  <- (1 - exp(-0.25 * ages))^3 * (ages >= age_mat)
  stk  <- list(ages = ages, fec = fec, mature = as.numeric(ages >= age_mat),
               h = h_steep, age_mat = age_mat)
  stk$e0 <- eggs_per_recruit(stk, rep(0, n_age))
  stk
}

surv_to_age <- function(f_vec) {
  z_vec <- m_nat + f_vec
  c(1, exp(-cumsum(z_vec[-n_age])))
}

eggs_per_recruit <- function(stk, f_vec, fec_mult = 1) {
  z_vec <- m_nat + f_vec
  l_vec <- surv_to_age(f_vec)
  l_vec[n_age] <- l_vec[n_age] / (1 - exp(-z_vec[n_age]))
  sum(l_vec * stk$fec * fec_mult)
}

spr_of <- function(stk, f_vec, fec_mult = 1) {
  eggs_per_recruit(stk, f_vec, fec_mult) / stk$e0
}

f_for_spr <- function(stk, spr, sel) {
  if (spr == 1) return(0)
  uniroot(function(f_val) spr_of(stk, f_val * sel) - spr,
          c(0, 10), tol = 1e-12)$root
}

lag_weights <- function(stk, f_vec, fec_mult = 1) {
  z_vec <- m_nat + f_vec
  l_vec <- surv_to_age(f_vec)
  lags  <- seq_len(lag_max)
  w_vec <- numeric(lag_max)
  young <- seq_len(n_age - 1)
  w_vec[young] <- stk$fec[young] * l_vec[young]
  old <- n_age:lag_max
  w_vec[old] <- stk$fec[n_age] * l_vec[n_age] * exp(-z_vec[n_age] * (old - n_age))
  w_vec * fec_mult
}

base_stock <- make_stock()
h_base     <- base_stock$h
spr_crash  <- (1 - h_base) / (4 * h_base)
spr_grid   <- c(1, 0.6, 0.45, 0.3, 0.2, 0.15)
f_mature   <- vapply(spr_grid, function(s) f_for_spr(base_stock, s, base_stock$mature), 0)
f_all      <- vapply(spr_grid, function(s) f_for_spr(base_stock, s, rep(1, n_age)), 0)
row_30     <- which(spr_grid == 0.3)
row_15     <- which(spr_grid == 0.15)

## ---- filtercheck ----
run_stock <- function(stk, f_mat, fec_mult, feedback, eps, burn) {
  n_col  <- ncol(f_mat)
  n_step <- if (is.matrix(eps)) nrow(eps) else length(eps)
  z_mat  <- m_nat + f_mat
  s_mat  <- exp(-z_mat)
  h_s    <- stk$h
  spr_c  <- vapply(seq_len(n_col), function(k) spr_of(stk, f_mat[, k], fec_mult[k]), 0)
  r_eq   <- (4 * h_s * spr_c - (1 - h_s)) / ((5 * h_s - 1) * spr_c)
  n_mat  <- vapply(seq_len(n_col), function(k) {
    l_vec <- surv_to_age(f_mat[, k])
    l_vec[n_age] <- l_vec[n_age] / (1 - exp(-z_mat[n_age, k]))
    l_vec * r_eq[k]
  }, numeric(n_age))
  fec_mat <- stk$fec %o% fec_mult
  out <- matrix(0, n_step - burn, n_col)
  for (i in seq_len(n_step)) {
    e_now <- colSums(n_mat * fec_mat)
    if (i > burn) out[i - burn, ] <- e_now
    dev_i <- if (is.matrix(eps)) exp(eps[i, ]) else exp(eps[i])
    r_bh  <- 4 * h_s * e_now / (stk$e0 * (1 - h_s) + (5 * h_s - 1) * e_now)
    r_new <- ifelse(feedback, r_bh, r_eq) * dev_i
    plus  <- n_mat[n_age, ] * s_mat[n_age, ]
    n_mat[2:n_age, ] <- n_mat[1:(n_age - 1), ] * s_mat[1:(n_age - 1), ]
    n_mat[n_age, ]   <- n_mat[n_age, ] + plus
    n_mat[1, ]       <- r_new
  }
  list(e_out = out, r_eq = r_eq)
}

long_len  <- 20000
long_burn <- 700
set.seed(4417)
eps_long <- rnorm(long_len + long_burn, -sd_rec^2 / 2, sd_rec)

n_spr   <- length(spr_grid)
scen    <- expand.grid(spr_i = seq_len(n_spr),
                       kind = c("mature", "all ages", "fecundity cut"),
                       feedback = c(FALSE, TRUE), stringsAsFactors = FALSE)
f_cols  <- vapply(seq_len(nrow(scen)), function(k) {
  i_s <- scen$spr_i[k]
  switch(scen$kind[k],
         "mature"        = f_mature[i_s] * base_stock$mature,
         "all ages"      = rep(f_all[i_s], n_age),
         "fecundity cut" = rep(0, n_age))
}, numeric(n_age))
fm_cols <- ifelse(scen$kind == "fecundity cut", spr_grid[scen$spr_i], 1)

t_long   <- system.time(
  long_run <- run_stock(base_stock, f_cols, fm_cols, scen$feedback, eps_long, long_burn)
)[["elapsed"]]

rec_long <- exp(eps_long)
id_err <- vapply(which(!scen$feedback), function(k) {
  w_k    <- lag_weights(base_stock, f_cols[, k], fm_cols[k])
  r_ser  <- long_run$r_eq[k] * rec_long
  e_filt <- stats::filter(r_ser, c(0, w_k), sides = 1)
  e_filt <- as.numeric(e_filt)[(long_burn + 1):(long_len + long_burn)]
  max(abs(e_filt - long_run$e_out[, k]) / long_run$e_out[, k])
}, 0)
id_max <- max(id_err)

cv_of <- function(x) sd(x) / mean(x)
n_block <- 10
block_id <- rep(seq_len(n_block), each = long_len / n_block)
scen$cv_sim <- apply(long_run$e_out, 2, cv_of)
scen$cv_se  <- apply(long_run$e_out, 2, function(x)
  sd(tapply(x, block_id, cv_of)) / sqrt(n_block))
scen$cv_formula <- vapply(seq_len(nrow(scen)), function(k) {
  w_k <- lag_weights(base_stock, f_cols[, k], fm_cols[k])
  cv_rec * sqrt(sum(w_k^2)) / sum(w_k)
}, 0)
scen$n_cohort <- vapply(seq_len(nrow(scen)), function(k) {
  w_k <- lag_weights(base_stock, f_cols[, k], fm_cols[k])
  sum(w_k)^2 / sum(w_k^2)
}, 0)
scen$gen_time <- vapply(seq_len(nrow(scen)), function(k) {
  w_k <- lag_weights(base_stock, f_cols[, k], fm_cols[k])
  sum(seq_len(lag_max) * w_k) / sum(w_k)
}, 0)

pick <- function(i_s, kind, fb) which(scen$spr_i == i_s & scen$kind == kind & scen$feedback == fb)
nofb_rows <- which(!scen$feedback)
z_gap     <- abs(scen$cv_sim[nofb_rows] - scen$cv_formula[nofb_rows]) / scen$cv_se[nofb_rows]
z_gap_max <- max(z_gap)
gap_max   <- max(abs(scen$cv_sim[nofb_rows] - scen$cv_formula[nofb_rows]))

cv_un   <- scen$cv_formula[pick(1, "mature", FALSE)]
cv_m30  <- scen$cv_formula[pick(row_30, "mature", FALSE)]
cv_a30  <- scen$cv_formula[pick(row_30, "all ages", FALSE)]
cv_c30  <- scen$cv_formula[pick(row_30, "fecundity cut", FALSE)]
nc_un   <- scen$n_cohort[pick(1, "mature", FALSE)]
nc_m30  <- scen$n_cohort[pick(row_30, "mature", FALSE)]
nc_a30  <- scen$n_cohort[pick(row_30, "all ages", FALSE)]
gt_un   <- scen$gen_time[pick(1, "mature", FALSE)]
gt_m30  <- scen$gen_time[pick(row_30, "mature", FALSE)]
gt_a30  <- scen$gen_time[pick(row_30, "all ages", FALSE)]

## ---- fp-guard-1 ----
stopifnot(id_max < 1e-10)

## ---- fig-weights ----
w_show <- 20
w_df <- do.call(rbind, lapply(list(
  list(k = pick(1, "mature", FALSE), lab = "unfished"),
  list(k = pick(row_30, "mature", FALSE), lab = "SPR 0.3, mature ages fished"),
  list(k = pick(row_30, "all ages", FALSE), lab = "SPR 0.3, all ages fished"),
  list(k = pick(row_30, "fecundity cut", FALSE), lab = "SPR 0.3, fecundity cut")), function(el) {
    w_k <- lag_weights(base_stock, f_cols[, el$k], fm_cols[el$k])
    data.frame(age = seq_len(w_show), share = (w_k / sum(w_k))[seq_len(w_show)],
               case = el$lab)
  }))
w_df$case <- factor(w_df$case, levels = unique(w_df$case))

ggplot(w_df, aes(age, share, colour = case, linetype = case)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 1.6) +
  scale_colour_manual(values = c(te_ink, te_rust, te_gold, te_forest), name = NULL) +
  scale_linetype_manual(values = c("solid", "solid", "solid", "dashed"), name = NULL) +
  labs(x = "age (years)", y = "share of spawning output",
       title = "Fishing moves spawning onto the youngest mature ages",
       subtitle = "the fecundity cut has the unfished shape exactly (dashed)") +
  guides(colour = guide_legend(nrow = 2), linetype = guide_legend(nrow = 2)) +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- feedback ----
n_freq  <- 4000
freq_mid <- (seq_len(n_freq) - 0.5) / (2 * n_freq)
lag_seq  <- seq_len(lag_max)
transfer <- function(w_vec, freqs) {
  w_n <- w_vec / sum(w_vec)
  as.vector(exp(-2i * pi * outer(freqs, lag_seq)) %*% w_n)
}
lin_cv <- function(w_vec, beta) {
  w_f <- transfer(w_vec, freq_mid)
  cv_rec * sqrt(mean(Mod(w_f / (1 - beta * w_f))^2))
}

scen$beta   <- ifelse(scen$feedback, spr_crash / spr_grid[scen$spr_i], 0)
scen$cv_lin <- vapply(seq_len(nrow(scen)), function(k) {
  lin_cv(lag_weights(base_stock, f_cols[, k], fm_cols[k]), scen$beta[k])
}, 0)

parseval_gap <- max(abs(scen$cv_lin[nofb_rows] - scen$cv_formula[nofb_rows]))

fb_tab <- data.frame(spr = spr_grid,
  beta    = spr_crash / spr_grid,
  nofb    = scen$cv_formula[scen$kind == "mature" & !scen$feedback],
  fb_sim  = scen$cv_sim[scen$kind == "mature" & scen$feedback],
  fb_se   = scen$cv_se[scen$kind == "mature" & scen$feedback],
  fb_lin  = scen$cv_lin[scen$kind == "mature" & scen$feedback],
  cut_sim = scen$cv_sim[scen$kind == "fecundity cut" & scen$feedback],
  cut_lin = scen$cv_lin[scen$kind == "fecundity cut" & scen$feedback])
fb_tab$gain_sim <- fb_tab$fb_sim / fb_tab$nofb - 1
fb_tab$gain_lin <- fb_tab$fb_lin / fb_tab$nofb - 1
fb_tab$lin_err  <- fb_tab$fb_sim / fb_tab$fb_lin - 1
lin_err_mid <- max(abs(fb_tab$lin_err[fb_tab$spr >= 0.3]))

## ---- fp-guard-2 ----
stopifnot(parseval_gap / max(scen$cv_formula[nofb_rows]) < 1e-10)

## ---- fig-cv ----
cv_df <- scen
cv_df$spr <- spr_grid[cv_df$spr_i]
cv_df$model <- ifelse(cv_df$feedback, "with feedback", "no feedback")

ggplot(cv_df, aes(spr, colour = kind)) +
  geom_vline(xintercept = spr_crash, linetype = "dotted", colour = te_body, linewidth = 0.6) +
  geom_line(aes(y = cv_lin), linewidth = 0.8) +
  geom_point(aes(y = cv_sim), size = 2.2) +
  facet_wrap(~ model) +
  scale_x_reverse(breaks = c(1, 0.6, 0.45, 0.3, 0.15)) +
  scale_colour_manual(values = c("all ages" = te_gold, "fecundity cut" = te_forest,
                                 "mature" = te_rust), name = NULL) +
  labs(x = "spawning potential ratio (fishing increases to the right)",
       y = "CV of spawning output",
       title = "Truncation carries the rise; feedback adds to it near the crash",
       subtitle = "dotted line: crash SPR for steepness 0.7") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- spectrum ----
spec_rows <- c(pick(1, "mature", FALSE), pick(row_30, "mature", FALSE),
               pick(1, "mature", TRUE), pick(row_30, "mature", TRUE),
               pick(row_15, "mature", TRUE))
spec_lab  <- c("unfished", "SPR 0.3, mature ages fished",
               "unfished", "SPR 0.3, mature ages fished",
               "SPR 0.15, mature ages fished")
low_cut   <- 1 / 8
spec_df <- do.call(rbind, lapply(seq_along(spec_rows), function(j) {
  k   <- spec_rows[j]
  s_p <- spec.pgram(long_run$e_out[, k], spans = c(51, 51), taper = 0,
                    detrend = FALSE, plot = FALSE)
  w_k <- lag_weights(base_stock, f_cols[, k], fm_cols[k])
  w_f <- transfer(w_k, s_p$freq)
  s_c <- Mod(w_f / (1 - scen$beta[k] * w_f))^2
  data.frame(freq = s_p$freq, periodogram = s_p$spec / mean(s_p$spec),
             closed = s_c / mean(s_c), case = spec_lab[j],
             model = ifelse(scen$feedback[k], "with feedback", "no feedback"))
}))

low_share <- function(case_lab, mod_lab, col) {
  d_c <- spec_df[spec_df$case == case_lab & spec_df$model == mod_lab, ]
  sum(d_c[[col]][d_c$freq < low_cut]) / sum(d_c[[col]])
}
low_un_c  <- low_share(spec_lab[1], "no feedback", "closed")
low_un_p  <- low_share(spec_lab[1], "no feedback", "periodogram")
low_30_c  <- low_share(spec_lab[2], "no feedback", "closed")
low_30_p  <- low_share(spec_lab[2], "no feedback", "periodogram")
low_un_fb <- low_share(spec_lab[1], "with feedback", "closed")
low_30_fb <- low_share(spec_lab[2], "with feedback", "closed")
low_15_fb <- low_share(spec_lab[5], "with feedback", "closed")

nofb_un <- spec_df[spec_df$case == spec_lab[1] & spec_df$model == "no feedback", ]
nofb_30 <- spec_df[spec_df$case == spec_lab[2] & spec_df$model == "no feedback", ]
ratio_spec  <- nofb_30$closed / nofb_un$closed
ratio_low   <- ratio_spec[1]
ratio_high  <- ratio_spec[length(ratio_spec)]
ratio_cross <- nofb_un$freq[which(ratio_spec > 1)[1]]

# local maxima of the closed-form spectrum on a regular frequency grid
freq_pk <- seq(0.0005, 0.5, by = 0.0005)
local_peaks <- function(w_vec, beta) {
  w_f <- transfer(w_vec, freq_pk)
  s_c <- Mod(w_f / (1 - beta * w_f))^2
  i_p <- which(diff(sign(diff(s_c))) == -2) + 1
  data.frame(freq = freq_pk[i_p], rel_low = s_c[i_p] / s_c[1],
             rel_trough = vapply(i_p, function(i) s_c[i] / min(s_c[seq_len(i)]), 0))
}
pk_nofb <- vapply(which(scen$kind == "mature" & !scen$feedback), function(k)
  nrow(local_peaks(lag_weights(base_stock, f_cols[, k], fm_cols[k]), 0)), 0)
pk_fb30 <- local_peaks(lag_weights(base_stock, f_cols[, pick(row_30, "mature", TRUE)], 1),
                       spr_crash / 0.3)
pk_fb15 <- local_peaks(lag_weights(base_stock, f_cols[, pick(row_15, "mature", TRUE)], 1),
                       spr_crash / 0.15)
gt_m15  <- scen$gen_time[pick(row_15, "mature", TRUE)]

# the same check for the maturity-at-8 stock used in the sensitivity runs
stk_8   <- make_stock(8, 0.7)
w_830   <- lag_weights(stk_8, f_for_spr(stk_8, 0.3, stk_8$mature) * stk_8$mature)
gt_830  <- sum(seq_len(lag_max) * w_830) / sum(w_830)
pk_830  <- local_peaks(w_830, spr_crash / 0.3)
pk_830n <- nrow(local_peaks(w_830, 0))

# the bump in the simulated periodogram, SPR 0.15 with feedback
pg_15  <- spec_df[spec_df$case == spec_lab[5], ]
pk_win <- abs(pg_15$freq - pk_fb15$freq[1]) < 0.05
pg_pk  <- which(pk_win)[which.max(pg_15$periodogram[pk_win])]
pg_tr  <- which(pg_15$freq > 0.05 & pg_15$freq < pg_15$freq[pg_pk])
pg_pk_freq  <- pg_15$freq[pg_pk]
pg_pk_ratio <- pg_15$periodogram[pg_pk] / min(pg_15$periodogram[pg_tr])

## ---- fig-spectrum ----
thin_df <- spec_df[seq(1, nrow(spec_df), by = 40), ]
vl_df <- data.frame(model = c("no feedback", "no feedback", "with feedback", "with feedback", "with feedback"),
                    case = spec_lab,
                    x0 = 1 / c(gt_un, gt_m30, gt_un, gt_m30, gt_m15))
spec_cols <- c("unfished" = te_ink, "SPR 0.3, mature ages fished" = te_rust,
               "SPR 0.15, mature ages fished" = te_gold)
spec_df$case <- factor(spec_df$case, levels = names(spec_cols))
thin_df$case <- factor(thin_df$case, levels = names(spec_cols))
vl_df$case   <- factor(vl_df$case, levels = names(spec_cols))
ggplot(spec_df, aes(freq, closed, colour = case)) +
  geom_vline(data = vl_df, aes(xintercept = x0, colour = case),
             linetype = "dotted", linewidth = 0.6, show.legend = FALSE) +
  geom_point(data = thin_df, aes(y = periodogram), size = 1.1, alpha = 0.6) +
  geom_line(linewidth = 0.9) +
  facet_wrap(~ model, ncol = 1) +
  scale_y_log10() +
  scale_colour_manual(values = spec_cols, name = NULL) +
  labs(x = "frequency (cycles per year)", y = "spectrum relative to its mean (log scale)",
       title = "Fishing flattens the spectrum; feedback adds a bump",
       subtitle = "dotted lines: one over the mean age of spawning output") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- windows ----
win_len  <- 50
n_win    <- 2000
win_burn <- 300
obs_grid <- c(0, 0.2)
mc_se_05 <- sqrt(0.05 * 0.95 / n_win)

sim_windows <- function(stk, spr, seed) {
  set.seed(seed)
  eps_w <- matrix(rnorm((win_len + win_burn) * n_win, -sd_rec^2 / 2, sd_rec),
                  nrow = win_len + win_burn)
  f_s   <- f_for_spr(stk, spr, stk$mature)
  f_m   <- matrix(f_s * stk$mature, n_age, n_win)
  run_stock(stk, f_m, rep(1, n_win), rep(TRUE, n_win), eps_w, win_burn)$e_out
}

add_obs <- function(e_mat, obs_sd, seed) {
  set.seed(seed)
  log(e_mat) + matrix(rnorm(length(e_mat), 0, obs_sd), nrow(e_mat))
}

col_sd <- function(y_mat) sqrt(colSums(sweep(y_mat, 2, colMeans(y_mat))^2) / (nrow(y_mat) - 1))

n_eff_est <- function(y_mat, max_lag = 10) {
  y_c <- sweep(y_mat, 2, colMeans(y_mat))
  den <- colSums(y_c^2)
  rho_sq <- vapply(seq_len(max_lag), function(k) {
    (colSums(y_c[1:(win_len - k), ] * y_c[(k + 1):win_len, ]) / den)^2
  }, numeric(ncol(y_mat)))
  win_len / (1 + 2 * rowSums(rho_sq))
}

detect_cell <- function(stk, spr_fish, obs_sd, seeds) {
  e_ref  <- sim_windows(stk, 1, seeds[1])
  e_null <- sim_windows(stk, 1, seeds[2])
  e_fish <- sim_windows(stk, spr_fish, seeds[3])
  y_ref  <- add_obs(e_ref, obs_sd, seeds[4])
  y_null <- add_obs(e_null, obs_sd, seeds[4] + 1)
  y_fish <- add_obs(e_fish, obs_sd, seeds[4] + 2)
  sd_ref <- col_sd(y_ref); sd_null <- col_sd(y_null); sd_fish <- col_sd(y_fish)
  q95    <- quantile(sd_ref, 0.95)
  f_crit <- qf(0.95, win_len - 1, win_len - 1)
  ne_ref <- n_eff_est(y_ref); ne_null <- n_eff_est(y_null); ne_fish <- n_eff_est(y_fish)
  list(sd_ref = sd_ref, sd_fish = sd_fish,
       stats = c(med_ref = median(sd_ref), med_fish = median(sd_fish),
                 exceed = mean(sd_fish > q95), exceed_null = mean(sd_null > q95),
                 naive_size = mean(sd_null^2 / sd_ref^2 > f_crit),
                 naive_power = mean(sd_fish^2 / sd_ref^2 > f_crit),
                 eff_size = mean(sd_null^2 / sd_ref^2 > qf(0.95, ne_null - 1, ne_ref - 1)),
                 eff_power = mean(sd_fish^2 / sd_ref^2 > qf(0.95, ne_fish - 1, ne_ref - 1)),
                 n_eff = median(ne_ref)))
}

det_design <- data.frame(
  label   = c("SPR 0.45, no obs error", "SPR 0.3, no obs error",
              "SPR 0.45, obs sd 0.2", "SPR 0.3, obs sd 0.2"),
  spr     = c(0.45, 0.3, 0.45, 0.3),
  obs     = c(0, 0, 0.2, 0.2))
t_win <- system.time({
  det_out <- lapply(seq_len(nrow(det_design)), function(i) {
    detect_cell(base_stock, det_design$spr[i], det_design$obs[i],
                c(7101, 7202, 7303 + (det_design$spr[i] == 0.3), 7404 + 10 * i))
  })
})[["elapsed"]]
det_tab <- cbind(det_design, t(sapply(det_out, `[[`, "stats")))

sd_long_log <- sd(log(long_run$e_out[, pick(1, "mature", TRUE)]))
var_kept    <- (det_tab$med_ref[2] / sd_long_log)^2
exceed_se   <- sqrt(2) * mc_se_05

## ---- fig-windows ----
win_df <- do.call(rbind, lapply(seq_len(nrow(det_design)), function(i) {
  rbind(if (det_design$spr[i] == 0.3)
          data.frame(sd_log = det_out[[i]]$sd_ref, case = "unfished",
                     obs = paste("observation sd", det_design$obs[i])),
        data.frame(sd_log = det_out[[i]]$sd_fish,
                   case = paste("SPR", det_design$spr[i]),
                   obs = paste("observation sd", det_design$obs[i])))
}))
win_df$case <- factor(win_df$case, levels = c("unfished", "SPR 0.45", "SPR 0.3"))

ggplot(win_df, aes(sd_log, colour = case)) +
  geom_density(linewidth = 0.9, adjust = 1.2) +
  facet_wrap(~ obs, ncol = 1) +
  scale_colour_manual(values = c(te_ink, te_gold, te_rust), name = NULL) +
  labs(x = "standard deviation of the log index within a 50-year window",
       y = "density",
       title = "Observation error blurs the change",
       subtitle = "each curve: 2000 windows with Beverton-Holt feedback") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- sensitivity ----
sens_design <- data.frame(label = c("maturity at age 8", "steepness 0.5"),
                          age_mat = c(8, 5), h_steep = c(0.7, 0.5))
t_sens <- system.time({
  sens_out <- lapply(seq_len(nrow(sens_design)), function(i) {
    stk_i <- make_stock(sens_design$age_mat[i], sens_design$h_steep[i])
    detect_cell(stk_i, 0.3, 0.2, c(8101, 8202, 8303, 8404) + 1000 * i)$stats
  })
})[["elapsed"]]
sens_tab <- cbind(sens_design, t(sapply(sens_out, identity)))
crash_h5 <- (1 - 0.5) / (4 * 0.5)

test_df <- rbind(
  data.frame(scenario = det_tab$label, test = "naive F", what = "size",
             rate = det_tab$naive_size),
  data.frame(scenario = det_tab$label, test = "naive F", what = "power",
             rate = det_tab$naive_power),
  data.frame(scenario = det_tab$label, test = "effective df", what = "size",
             rate = det_tab$eff_size),
  data.frame(scenario = det_tab$label, test = "effective df", what = "power",
             rate = det_tab$eff_power),
  data.frame(scenario = paste("SPR 0.3, obs sd 0.2,", sens_tab$label), test = "naive F",
             what = "size", rate = sens_tab$naive_size),
  data.frame(scenario = paste("SPR 0.3, obs sd 0.2,", sens_tab$label), test = "naive F",
             what = "power", rate = sens_tab$naive_power),
  data.frame(scenario = paste("SPR 0.3, obs sd 0.2,", sens_tab$label), test = "effective df",
             what = "size", rate = sens_tab$eff_size),
  data.frame(scenario = paste("SPR 0.3, obs sd 0.2,", sens_tab$label), test = "effective df",
             what = "power", rate = sens_tab$eff_power))
mc_se_max <- sqrt(0.25 / n_win)
nc_8 <- vapply(c(1, 0.3), function(s) {
  stk8 <- make_stock(8, 0.7)
  w_8 <- lag_weights(stk8, f_for_spr(stk8, s, stk8$mature) * stk8$mature)
  sum(w_8)^2 / sum(w_8^2)
}, 0)
beta_h5 <- crash_h5 / 0.3
pow_ok  <- c(det_tab$eff_power[det_tab$obs == 0.2], sens_tab$eff_power)
pow_ok_max <- max(pow_ok)

# the effective-df correction on pure white noise of the same length
n_wn <- 20000
set.seed(9105)
wn_a <- matrix(rnorm(win_len * n_wn), win_len)
wn_b <- matrix(rnorm(win_len * n_wn), win_len)
ne_a <- n_eff_est(wn_a)
ne_b <- n_eff_est(wn_b)
wn_neff <- median(ne_a)
wn_size <- mean(col_sd(wn_b)^2 / col_sd(wn_a)^2 > qf(0.95, ne_b - 1, ne_a - 1))

## ---- fig-tests ----
test_df$scenario <- factor(test_df$scenario, levels = rev(unique(test_df$scenario)))
test_df$what <- factor(test_df$what, levels = c("size", "power"))

ggplot(test_df, aes(rate, scenario, colour = test, shape = test)) +
  geom_vline(data = data.frame(what = factor("size", levels = c("size", "power")), x0 = 0.05),
             aes(xintercept = x0), linetype = "dashed", colour = te_body, linewidth = 0.6) +
  geom_point(size = 2.8, position = position_dodge(width = 0.5)) +
  facet_wrap(~ what, scales = "free_x") +
  scale_colour_manual(values = c("effective df" = te_forest, "naive F" = te_rust), name = NULL) +
  scale_shape_manual(values = c("effective df" = 16, "naive F" = 17), name = NULL) +
  labs(x = "rejection rate", y = NULL,
       title = "A test that ignores autocorrelation is oversized",
       subtitle = "dashed line: nominal level 0.05") +
  theme_datasheet() +
  theme(legend.position = "bottom", panel.spacing.x = unit(2, "lines"))
