# Summed radiocarbon dates: an honest, nearly blind test
# https://tidyecology.com/posts/summed-radiocarbon-probabilities/
#
# 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-09-16

## ---- 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),
          strip.text       = element_text(colour = te_ink))
}

## ---- curve ----
cal_grid <- seq(1000, 7000, by = 5)
curve_c14 <- cal_grid - 250 + 45 * sin(2 * pi * cal_grid / 1100) +
  18 * sin(2 * pi * cal_grid / 260)
on_plateau_grid <- cal_grid >= 2400 & cal_grid <= 2750
curve_c14[on_plateau_grid] <- curve_c14[cal_grid == 2400] +
  (cal_grid[on_plateau_grid] - 2400) * 0.05
after_plateau <- cal_grid > 2750
curve_c14[after_plateau] <- curve_c14[after_plateau] -
  (curve_c14[after_plateau][1] - (curve_c14[cal_grid == 2750] + 5))

curve_slope <- diff(curve_c14) / 5
slope_q <- quantile(curve_slope, c(0.05, 0.5, 0.95))
share_flat <- mean(curve_slope < 0.2)
share_reversal <- mean(curve_slope < 0)

lab_sd <- 35; curve_sd <- 15
sd_total <- sqrt(lab_sd^2 + curve_sd^2)
c14_ages <- floor(min(curve_c14) - 300):ceiling(max(curve_c14) + 300)
lik_raw  <- outer(c14_ages, curve_c14, function(a, m) dnorm(a, m, sd_total))
lik_norm <- lik_raw / rowSums(lik_raw)

in_window <- cal_grid >= 2000 & cal_grid <= 6000
win_years <- cal_grid[in_window]
in_pop    <- cal_grid >= 1500 & cal_grid <= 6500
plateau_w <- win_years >= 2400 & win_years <= 2750
run_mean  <- function(x, k = 41) as.numeric(stats::filter(x, rep(1 / k, k), sides = 2))

## ---- expected ----
age_dist <- function(pop_idx) {
  pr <- colMeans(t(sapply(pop_idx, function(j) dnorm(c14_ages, curve_c14[j], sd_total))))
  pr / sum(pr)
}
pr_padded <- age_dist(which(in_pop))
pr_trunc  <- age_dist(which(in_window))

exp_norm  <- run_mean(drop(crossprod(lik_norm, pr_padded)))[in_window]
exp_raw   <- run_mean(drop(crossprod(lik_raw, pr_padded)))[in_window]
exp_trunc <- run_mean(drop(crossprod(lik_norm, pr_trunc)))[in_window]

max_min <- function(x) max(x) / min(x)
plat_ratio <- function(x) mean(x[plateau_w]) / mean(x[!plateau_w])
mm_norm  <- max_min(exp_norm);  pr_norm_plat <- plat_ratio(exp_norm)
mm_raw   <- max_min(exp_raw);   pr_raw_plat  <- plat_ratio(exp_raw)
mm_trunc <- max_min(exp_trunc)
edge_left  <- exp_trunc[1] / median(exp_trunc)
edge_right <- exp_trunc[length(exp_trunc)] / median(exp_trunc)

## ---- fig-curve-expected ----
curve_df <- data.frame(cal = cal_grid[in_pop], c14 = curve_c14[in_pop])
p_curve <- ggplot(curve_df, aes(cal, c14)) +
  annotate("rect", xmin = 2400, xmax = 2750, ymin = -Inf, ymax = Inf,
           fill = te_gold, alpha = 0.35) +
  geom_line(colour = te_ink, linewidth = 0.6) +
  scale_x_reverse(limits = c(6500, 1500)) +
  labs(x = "Calendar age (cal BP)", y = "Radiocarbon age (14C BP)",
       title = "Synthetic calibration curve",
       subtitle = "Trend, two wiggles and one plateau (shaded); not IntCal20") +
  theme_datasheet()

exp_df <- data.frame(
  cal = rep(win_years, 3),
  rel = c(exp_norm / median(exp_norm), exp_raw / median(exp_raw),
          exp_trunc / median(exp_trunc)),
  arm = factor(rep(c("normalised, padded", "unnormalised, padded",
                     "normalised, truncated"), each = length(win_years)),
               levels = c("normalised, padded", "unnormalised, padded",
                          "normalised, truncated")))
p_exp <- ggplot(exp_df, aes(cal, rel, colour = arm)) +
  annotate("rect", xmin = 2400, xmax = 2750, ymin = -Inf, ymax = Inf,
           fill = te_gold, alpha = 0.35) +
  geom_hline(yintercept = 1, colour = te_body, linetype = "dashed", linewidth = 0.3) +
  geom_line(linewidth = 0.8) +
  scale_colour_manual(values = c(te_forest, te_rust, te_gold)) +
  scale_x_reverse(limits = c(6500, 1500)) +
  labs(x = "Calendar age (cal BP)", y = "Expected SPD / median", colour = NULL,
       title = "Expected SPD of a constant population") +
  theme_datasheet() +
  theme(legend.position = "bottom")

p_curve / p_exp + plot_annotation(theme = theme_datasheet())

## ---- simulator ----
pop_dates <- function(n, boom = 1) {
  wt <- ifelse(cal_grid >= 4000 & cal_grid < 4300, boom, 1)[in_pop]
  sample(cal_grid[in_pop], n, replace = TRUE, prob = wt) + runif(n, -2.5, 2.5)
}
draw_c14 <- function(cal_dates) {
  round(approx(cal_grid, curve_c14, cal_dates)$y + rnorm(length(cal_dates), 0, sd_total))
}
make_spd <- function(cal_dates, lik_mat) {
  counts <- tabulate(draw_c14(cal_dates) - c14_ages[1] + 1, nbins = length(c14_ages))
  used <- which(counts > 0)
  run_mean(drop(crossprod(lik_mat[used, , drop = FALSE], counts[used])))[in_window]
}
n_set <- c(100, 300, 1000)
span_centuries <- (6500 - 1500) / 100

## ---- single ----
set.seed(3160)
single_df <- do.call(rbind, lapply(n_set, function(n) {
  do.call(rbind, lapply(1:3, function(k) {
    s_k <- make_spd(pop_dates(n), lik_norm)
    data.frame(n = n, set = k, cal = win_years, rel = s_k / mean(s_k))
  }))
}))

## ---- fig-single-spds ----
single_df$n_lab <- factor(paste(single_df$n, "dates"), levels = paste(n_set, "dates"))
ggplot(single_df, aes(cal, rel, colour = factor(set))) +
  annotate("rect", xmin = 2400, xmax = 2750, ymin = -Inf, ymax = Inf,
           fill = te_gold, alpha = 0.3) +
  geom_hline(yintercept = 1, colour = te_body, linetype = "dashed", linewidth = 0.3) +
  geom_line(linewidth = 0.55) +
  facet_wrap(~ n_lab, ncol = 1) +
  scale_colour_manual(values = c(te_forest, te_rust, te_ink), guide = "none") +
  scale_x_reverse() +
  labs(x = "Calendar age (cal BP)", y = "SPD / its own mean",
       title = "A constant population, summed three times") +
  theme_datasheet()

## ---- mc-test ----
global_stat <- function(z, lo, hi) sum(pmax(z - hi, 0) + pmax(lo - z, 0))
in_boom <- win_years >= 4000 & win_years < 4300

build_null <- function(n, n_sim, lik_mat) {
  sims <- replicate(n_sim, make_spd(pop_dates(n), lik_mat))
  m_s <- rowMeans(sims); s_s <- apply(sims, 1, sd)
  z_s <- (sims - m_s) / s_s
  lo <- apply(z_s, 1, quantile, 0.025); hi <- apply(z_s, 1, quantile, 0.975)
  list(mean = m_s, sd = s_s, lo = lo, hi = hi, n_sim = n_sim,
       stat = apply(z_s, 2, global_stat, lo = lo, hi = hi),
       local = colMeans(sims[in_boom, ]))
}
test_spd <- function(x, nul) {
  z <- (x - nul$mean) / nul$sd
  outside <- z > nul$hi | z < nul$lo
  c(p_global = (1 + sum(nul$stat >= global_stat(z, nul$lo, nul$hi))) / (nul$n_sim + 1),
    p_local = (1 + sum(nul$local >= mean(x[in_boom]))) / (nul$n_sim + 1),
    any_out = any(outside), share_out = mean(outside),
    max_min = max(x) / min(x), peak15 = max(x) > 1.5 * mean(x))
}

n_sim <- 999; n_fresh <- 500; alpha_lev <- 0.05
set.seed(3161)
null_pools <- lapply(n_set, build_null, n_sim = n_sim, lik_mat = lik_norm)
names(null_pools) <- n_set
fresh <- lapply(n_set, function(n) {
  sapply(seq_len(n_fresh), function(i) test_spd(make_spd(pop_dates(n), lik_norm),
                                                 null_pools[[as.character(n)]]))
})
names(fresh) <- n_set
size_global <- sapply(fresh, function(f) mean(f["p_global", ] <= alpha_lev))
size_local  <- sapply(fresh, function(f) mean(f["p_local", ] <= alpha_lev))
any_out     <- sapply(fresh, function(f) mean(f["any_out", ]))
share_out   <- sapply(fresh, function(f) median(f["share_out", ]))
spike_mm    <- sapply(fresh, function(f) median(f["max_min", ]))
spike_15    <- sapply(fresh, function(f) mean(f["peak15", ]))
mcse_size   <- sqrt(alpha_lev * (1 - alpha_lev) / n_fresh)
size_dev_se <- max(abs(size_global - alpha_lev)) / mcse_size
size_local_pooled <- mean(size_local)
mcse_local_pooled <- sqrt(alpha_lev * (1 - alpha_lev) / (3 * n_fresh))

pool300 <- null_pools[["300"]]
exp_mc_mm <- max_min(pool300$mean)
rel_sd <- pool300$sd / pool300$mean
slope_win <- run_mean(c(curve_slope, curve_slope[length(curve_slope)]))[in_window]
rel_sd_flat  <- mean(rel_sd[slope_win < 0.5])
rel_sd_other <- mean(rel_sd[slope_win >= 0.5])

## ---- unnormalised ----
set.seed(3162)
null_raw <- build_null(300, n_sim, lik_raw)
fresh_raw <- sapply(seq_len(n_fresh), function(i) test_spd(make_spd(pop_dates(300), lik_raw), null_raw))
size_raw <- mean(fresh_raw["p_global", ] <= alpha_lev)
spike_raw <- median(fresh_raw["max_min", ])

## ---- power ----
boom_set <- c(1.3, 1.6, 2.0); n_power <- 250
set.seed(3163)
power_df <- do.call(rbind, lapply(n_set, function(n) {
  do.call(rbind, lapply(boom_set, function(b) {
    res <- sapply(seq_len(n_power), function(i) {
      test_spd(make_spd(pop_dates(n, boom = b), lik_norm),
               null_pools[[as.character(n)]])[c("p_global", "p_local")]
    })
    data.frame(n = n, boom = b,
               test = c("global statistic", "planned window"),
               power = c(mean(res["p_global", ] <= alpha_lev),
                         mean(res["p_local", ] <= alpha_lev)))
  }))
}))
power_df$mcse <- sqrt(power_df$power * (1 - power_df$power) / n_power)
pw <- function(n, b, tst = "global statistic") {
  power_df$power[power_df$n == n & power_df$boom == b & power_df$test == tst]
}
mcse_max <- max(power_df$mcse)
per_century <- n_set / span_centuries

## ---- fig-power ----
power_df$n_lab <- factor(paste(power_df$n, "dates"), levels = paste(n_set, "dates"))
ggplot(power_df, aes(boom, power, colour = n_lab)) +
  geom_hline(yintercept = alpha_lev, colour = te_body, linetype = "dashed", linewidth = 0.3) +
  geom_errorbar(aes(ymin = pmax(power - 2 * mcse, 0), ymax = pmin(power + 2 * mcse, 1)),
                width = 0.03, linewidth = 0.4) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2) +
  facet_wrap(~ test) +
  scale_colour_manual(values = c(te_gold, te_rust, te_forest)) +
  scale_x_continuous(breaks = boom_set, labels = c("x1.3", "x1.6", "x2.0"),
                     expand = expansion(mult = 0.1)) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "Population multiplier for 300 years", y = "Share of data sets rejected",
       colour = NULL, title = "Power to detect a boom") +
  theme_datasheet() +
  theme(legend.position = "bottom")
