# Checking a repeatability analysis
# https://tidyecology.com/posts/checking-a-repeatability-analysis/
#
# 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)

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

fmt <- function(x, digits = 4) formatC(x, format = "f", digits = digits)

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"),
          legend.position = "bottom")
}

## ---- estimator ----
icc_balanced <- function(Y) {
  n <- nrow(Y); k <- ncol(Y)
  row_mean <- rowMeans(Y)
  msb <- k * sum((row_mean - mean(row_mean))^2) / (n - 1)
  msw <- sum((Y - row_mean)^2) / (n * (k - 1))
  (msb - msw) / (msb + (k - 1) * msw)
}

sim_balanced <- function(n, k, R) {
  matrix(rnorm(n * k, 0, sqrt(1 - R)), n, k) + rnorm(n, 0, sqrt(R))
}

set.seed(20260728)
chk_n <- 4000; chk_k <- 5; chk_R <- 0.35
chk_1 <- icc_balanced(sim_balanced(chk_n, chk_k, chk_R))
chk_2 <- icc_balanced(sim_balanced(chk_n, chk_k, chk_R))
print(c(n = chk_n, k = chk_k, observations = chk_n * chk_k))
print(round(c(R_true = chk_R, R_hat_study1 = chk_1, R_hat_study2 = chk_2), 4))

## ---- design-grid ----
set.seed(20260812)
n_total <- 240
k_grid <- c(2, 3, 4, 5, 6, 8, 12)
Rtrue_grid <- c(0.10, 0.30, 0.60)
reps_a <- 800

grid_a <- NULL
for (Rt in Rtrue_grid) {
  for (kk in k_grid) {
    nn <- n_total / kk
    est <- numeric(reps_a)
    for (r in seq_len(reps_a)) est[r] <- max(0, icc_balanced(sim_balanced(nn, kk, Rt)))
    grid_a <- rbind(grid_a,
                    data.frame(R_true = Rt, k = kk, n = nn,
                               se = sd(est), bias = mean(est) - Rt,
                               p_zero = mean(est <= 0)))
  }
}
print(round(c(total_observations = n_total, replicates_per_cell = reps_a), 0))
print(round(grid_a, 4))

## ---- design-summary ----
best_a <- do.call(rbind, lapply(split(grid_a, grid_a$R_true), function(s) {
  data.frame(R_true = s$R_true[1],
             k_best = s$k[which.min(s$se)],
             n_best = s$n[which.min(s$se)],
             se_best = min(s$se),
             cost_of_k3 = s$se[s$k == 3] / min(s$se),
             cost_of_k4 = s$se[s$k == 4] / min(s$se),
             k_algebra = 1 + 1 / s$R_true[1])
}))
row.names(best_a) <- NULL
print(round(best_a, 4))
print(round(c(worst_cost_k3 = max(best_a$cost_of_k3),
              worst_cost_k4 = max(best_a$cost_of_k4)), 4))

## ---- fig-design ----
plot_a <- grid_a
plot_a$series <- factor(plot_a$R_true, levels = Rtrue_grid,
                        labels = paste("true R =", Rtrue_grid))
mins_a <- do.call(rbind, lapply(split(plot_a, plot_a$series), function(s) s[which.min(s$se), ]))

ggplot(plot_a, aes(k, se, colour = series)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2) +
  geom_point(data = mins_a, shape = 21, size = 5.2, stroke = 1.1, fill = te_pal$paper,
             show.legend = FALSE) +
  scale_x_continuous(breaks = k_grid) +
  scale_colour_manual(values = c(te_pal$green, te_pal$gold, te_pal$clay), name = NULL) +
  labs(title = "Where the estimate is most stable",
       subtitle = "the ring on each curve marks its measured minimum",
       x = "repeats per individual k (individuals n = 240 / k)",
       y = "standard error of reported R") +
  theme_te() +
  theme(plot.subtitle = element_text(colour = "#2c3a31"))

## ---- drift-sim ----
set.seed(20260729)
tau_days <- 45
sd_ind <- 1; sd_err <- 1
R_instant <- sd_ind^2 / (sd_ind^2 + sd_err^2)
n_b <- 200; reps_b <- 300

icc_pair <- function(gap, n, reps) {
  rho <- exp(-gap / tau_days)
  out <- numeric(reps)
  for (r in seq_len(reps)) {
    a1 <- rnorm(n, 0, sd_ind)
    a2 <- rho * a1 + rnorm(n, 0, sd_ind * sqrt(1 - rho^2))
    Y <- cbind(a1, a2) + matrix(rnorm(2 * n, 0, sd_err), n, 2)
    out[r] <- icc_balanced(Y)
  }
  mean(out)
}

gaps_head <- c(0.02, 21, 1095)
gap_names <- c("30 minutes", "3 weeks", "3 years")
R_head <- vapply(gaps_head, icc_pair, numeric(1), n = n_b, reps = reps_b)
names(R_head) <- gap_names
print(round(c(tau_true = tau_days, R_instant = R_instant,
              n_individuals = n_b, replicates = reps_b), 4))
print(round(R_head, 4))

## ---- drift-timescale ----
tau_from_gap <- -gaps_head / log(pmax(R_head / R_instant, 1e-8))
names(tau_from_gap) <- gap_names
print(round(tau_from_gap, 2))

## ---- drift-curve ----
set.seed(20260802)
gaps_curve <- c(0.02, 1, 3, 7, 14, 21, 45, 90, 180, 365, 730, 1095)
reps_curve <- 150
R_curve <- vapply(gaps_curve, icc_pair, numeric(1), n = n_b, reps = reps_curve)
curve_b <- data.frame(gap = gaps_curve, R = R_curve,
                      predicted = R_instant * exp(-gaps_curve / tau_days))
print(round(curve_b, 4))
print(round(c(replicates_per_gap = reps_curve,
              max_gap_to_prediction = max(abs(curve_b$R - curve_b$predicted))), 4))

## ---- fig-decay ----
head_b <- data.frame(gap = gaps_head, R = as.numeric(R_head), lab = gap_names)
head_b$lab_x <- c(gaps_head[1], 11, gaps_head[3])
head_b$lab_y <- c(head_b$R[1] + 0.075, 0.225, head_b$R[3] + 0.085)
head_b$hj <- c(0, 1, 1)
long_b <- rbind(data.frame(gap = curve_b$gap, R = curve_b$R, series = "measured"),
                data.frame(gap = curve_b$gap, R = curve_b$predicted,
                           series = "exponential decay, tau = 45 days"))

ggplot(long_b, aes(gap, R, colour = series, linetype = series, linewidth = series)) +
  geom_line() +
  geom_point(data = long_b[long_b$series == "measured", ], size = 2,
             show.legend = FALSE) +
  annotate("segment", x = 12.5, xend = 19.5, y = 0.238, yend = 0.300,
           colour = te_pal$ink, linewidth = 0.35) +
  geom_text(data = head_b, aes(lab_x, lab_y, label = lab), inherit.aes = FALSE,
            hjust = head_b$hj, size = 3.4, colour = te_pal$ink) +
  scale_x_log10(breaks = c(0.02, 1, 7, 30, 180, 1095),
                labels = c("0.02", "1", "7", "30", "180", "1095")) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$green), name = NULL) +
  scale_linetype_manual(values = c(2, 1), name = NULL) +
  scale_linewidth_manual(values = c(1.6, 0.7), name = NULL) +
  coord_cartesian(ylim = c(-0.06, 0.62)) +
  labs(title = "Repeatability decays with the gap between repeats",
       x = "gap between the two repeats (days, log scale)",
       y = "measured R") +
  theme_te()

## ---- observer-setup ----
n_c <- 30; k_c <- 4; m_c <- 6
va_c <- 0.30; vo_c <- 0.25; ve_c <- 0.70
p_primary <- 0.85
R_adjusted <- va_c / (va_c + ve_c)
R_unadjusted <- va_c / (va_c + vo_c + ve_c)
print(round(c(individuals = n_c, repeats = k_c, observers = m_c,
              var_ind = va_c, var_obs = vo_c, var_resid = ve_c,
              share_primary = p_primary,
              R_adjusted = R_adjusted, R_unadjusted = R_unadjusted), 4))

icc_long <- function(y, ind, n, k) {
  ind_mean <- as.vector(rowsum(y, ind)) / k
  msb <- k * sum((ind_mean - mean(ind_mean))^2) / (n - 1)
  msw <- sum((y - ind_mean[ind])^2) / (n * (k - 1))
  (msb - msw) / (msb + (k - 1) * msw)
}

assign_confounded <- function(n, k, m, share = p_primary) {
  primary <- rep(seq_len(m), length.out = n)
  out <- integer(n * k)
  for (i in seq_len(n)) {
    swap <- runif(k) >= share
    alt <- sample(setdiff(seq_len(m), primary[i]), k, replace = TRUE)
    out[((i - 1) * k + 1):(i * k)] <- ifelse(swap, alt, primary[i])
  }
  out
}

assign_rotated <- function(n, k, m) {
  as.integer(sapply(seq_len(n), function(i) sample(m, k)))
}

sim_observer <- function(n, k, m, obs) {
  ind <- rep(seq_len(n), each = k)
  a <- rnorm(n, 0, sqrt(va_c)); o <- rnorm(m, 0, sqrt(vo_c))
  list(y = a[ind] + o[obs] + rnorm(n * k, 0, sqrt(ve_c)), ind = ind, obs = obs)
}

## ---- observer-fit ----
neg_ll <- function(p, K_ind, K_obs, X, N) {
  ra <- exp(p[1]); ro <- exp(p[2])
  V <- ra * K_ind + ro * K_obs
  diag(V) <- diag(V) + 1
  ch <- chol(V)
  S <- backsolve(ch, X, transpose = TRUE)
  mu <- sum(S[, 1] * S[, 2]) / sum(S[, 2]^2)
  q <- sum((S[, 1] - mu * S[, 2])^2)
  0.5 * (2 * sum(log(diag(ch))) + N * log(q / N) + N)
}

fit_crossed <- function(d) {
  N <- length(d$y)
  K_ind <- outer(d$ind, d$ind, "==") * 1
  K_obs <- outer(d$obs, d$obs, "==") * 1
  X <- cbind(d$y, 1)
  opt <- optim(c(log(0.4), log(0.3)), neg_ll, K_ind = K_ind, K_obs = K_obs,
               X = X, N = N, method = "Nelder-Mead",
               control = list(maxit = 200, reltol = 1e-7))
  ra <- exp(opt$par[1]); ro <- exp(opt$par[2])
  V <- ra * K_ind + ro * K_obs
  diag(V) <- diag(V) + 1
  ch <- chol(V)
  S <- backsolve(ch, X, transpose = TRUE)
  mu <- sum(S[, 1] * S[, 2]) / sum(S[, 2]^2)
  s2 <- sum((S[, 1] - mu * S[, 2])^2) / N
  c(var_ind = ra * s2, var_obs = ro * s2, var_resid = s2, R = ra / (ra + 1))
}

## ---- observer-run ----
set.seed(20260730)
reps_c <- 150
conf_icc <- rot_icc <- conf_mod <- rot_mod <- numeric(reps_c)
va_hat <- vo_hat <- ve_hat <- numeric(reps_c)
for (r in seq_len(reps_c)) {
  d_conf <- sim_observer(n_c, k_c, m_c, assign_confounded(n_c, k_c, m_c))
  conf_icc[r] <- icc_long(d_conf$y, d_conf$ind, n_c, k_c)
  f <- fit_crossed(d_conf)
  conf_mod[r] <- f["R"]; va_hat[r] <- f["var_ind"]; vo_hat[r] <- f["var_obs"]
  ve_hat[r] <- f["var_resid"]

  d_rot <- sim_observer(n_c, k_c, m_c, assign_rotated(n_c, k_c, m_c))
  rot_icc[r] <- icc_long(d_rot$y, d_rot$ind, n_c, k_c)
  rot_mod[r] <- fit_crossed(d_rot)["R"]
}

means_c <- c(mean(conf_icc), mean(rot_icc), mean(conf_mod), mean(rot_mod))
res_c <- data.frame(
  design = c("confounded, plain ICC", "rotated, plain ICC",
             "confounded, observer in model", "rotated, observer in model"),
  mean_R = means_c,
  sd_R = c(sd(conf_icc), sd(rot_icc), sd(conf_mod), sd(rot_mod)),
  bias = means_c - R_adjusted,
  abs_bias = abs(means_c - R_adjusted))
print(round(c(replicates = reps_c), 0))
print(data.frame(design = res_c$design, round(res_c[, -1], 4)))
print(round(c(var_ind_true = va_c, var_ind_fitted = mean(va_hat),
              var_obs_true = vo_c, var_obs_fitted = mean(vo_hat),
              var_resid_true = ve_c, var_resid_fitted = mean(ve_hat),
              lower_q = 0.025, upper_q = 0.975), 4))

## ---- fig-observer ----
qs_c <- rbind(quantile(conf_icc, c(0.025, 0.975), names = FALSE),
              quantile(rot_icc, c(0.025, 0.975), names = FALSE),
              quantile(conf_mod, c(0.025, 0.975), names = FALSE),
              quantile(rot_mod, c(0.025, 0.975), names = FALSE))
plot_c <- data.frame(design = factor(res_c$design, levels = rev(res_c$design)),
                     mean_R = res_c$mean_R, lo = qs_c[, 1], hi = qs_c[, 2],
                     fix = c("no fix", "design fix", "modelling fix",
                             "design and modelling fix"))
plot_c$fix <- factor(plot_c$fix, levels = c("no fix", "design fix",
                                            "modelling fix",
                                            "design and modelling fix"))

ggplot(plot_c, aes(mean_R, design, colour = fix, shape = fix)) +
  geom_vline(xintercept = R_adjusted, colour = te_pal$ink, linetype = 2, linewidth = 0.6) +
  geom_vline(xintercept = R_unadjusted, colour = te_pal$ink, linetype = 3, linewidth = 0.6) +
  geom_errorbar(aes(xmin = lo, xmax = hi), orientation = "y", width = 0.22, linewidth = 0.8) +
  geom_point(size = 3) +
  annotate("text", x = R_unadjusted - 0.008, y = 4.8, label = "unadjusted target",
           hjust = 1, size = 3.1, colour = te_pal$ink) +
  annotate("text", x = R_adjusted + 0.008, y = 4.8, label = "adjusted target",
           hjust = 0, size = 3.1, colour = te_pal$ink) +
  scale_y_discrete(expand = expansion(add = c(0.6, 1.25))) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$gold, te_pal$green, te_pal$forest),
                      name = NULL) +
  scale_shape_manual(values = c(16, 17, 15, 18), name = NULL) +
  guides(colour = "none", shape = "none") +
  labs(title = "What the observer does to R",
       x = "repeatability", y = NULL) +
  theme_te() +
  theme(plot.margin = margin(6, 16, 6, 6))

## ---- boundary-tools ----
n_d <- 30; k_d <- 3
df_b <- n_d - 1; df_w <- n_d * (k_d - 1); df_tot <- df_b + df_w
z_norm <- 1.96; nominal <- 0.95

ss_of <- function(Y) {
  row_mean <- rowMeans(Y)
  c(k_d * sum((row_mean - mean(row_mean))^2), sum((Y - row_mean)^2))
}
icc_from_ss <- function(s) {
  msb <- s[1] / df_b; msw <- s[2] / df_w
  (msb - msw) / (msb + (k_d - 1) * msw)
}
deviance_R <- function(R, s) {
  if (R < 0 || R >= 1) return(Inf)
  a <- 1 + (k_d - 1) * R; b <- 1 - R
  v <- (s[1] / a + s[2] / b) / df_tot
  df_tot * log(v) + df_b * log(a) + df_w * log(b)
}
profile_min <- function(s) {
  Rh <- max(0, icc_from_ss(s))
  c(Rh, deviance_R(Rh, s))
}
lr_interval <- function(s, crit = qchisq(nominal, 1)) {
  pm <- profile_min(s); Rh <- pm[1]; d0 <- pm[2]
  f <- function(R) deviance_R(R, s) - d0 - crit
  lo <- if (f(0) <= 0) 0 else uniroot(f, c(0, Rh), tol = 1e-7)$root
  hi <- if (f(0.9999) <= 0) 0.9999 else uniroot(f, c(max(Rh, 1e-9), 0.9999), tol = 1e-7)$root
  c(lo, hi)
}
se_plugin <- function(R) {
  sqrt(2 * (1 - R)^2 * (1 + (k_d - 1) * R)^2 / (k_d * (k_d - 1) * (n_d - 1)))
}
boot_icc <- function(Rh, n, k, B) {
  Y <- matrix(rnorm(n * k * B, 0, sqrt(1 - Rh)), n, k * B)
  ab <- matrix(rnorm(n * B, 0, sqrt(Rh)), n, B)
  Y <- Y + ab[, rep(seq_len(B), each = k)]
  idx <- lapply(seq_len(k), function(j) seq(j, k * B, by = k))
  row_mean <- 0
  for (j in seq_len(k)) row_mean <- row_mean + Y[, idx[[j]], drop = FALSE]
  row_mean <- row_mean / k
  ssb <- k * colSums((row_mean - rep(colMeans(row_mean), each = n))^2)
  ssw <- 0
  for (j in seq_len(k)) ssw <- ssw + colSums((Y[, idx[[j]], drop = FALSE] - row_mean)^2)
  msb <- ssb / (n - 1); msw <- ssw / (n * (k - 1))
  pmax(0, (msb - msw) / (msb + (k - 1) * msw))
}
print(round(c(individuals = n_d, repeats = k_d, nominal = nominal,
              z_norm = z_norm, lower_q = 0.025, upper_q = 0.975,
              chisq_crit = qchisq(nominal, 1), boundary_theory = 0.5), 4))

## ---- boundary-coverage ----
set.seed(20260731)
R_grid_d <- c(0, 0.05, 0.10, 0.20, 0.40, 0.70)
reps_d <- 600; n_boot <- 199
cover_d <- NULL
for (Rt in R_grid_d) {
  miss <- matrix(0, 3, 2); at_zero <- 0; neg_lower <- 0
  for (r in seq_len(reps_d)) {
    s <- ss_of(sim_balanced(n_d, k_d, Rt))
    R_raw <- icc_from_ss(s); Rh <- max(0, R_raw)
    at_zero <- at_zero + (R_raw <= 0)
    half <- z_norm * se_plugin(Rh)
    neg_lower <- neg_lower + (Rh - half < 0)
    miss[1, ] <- miss[1, ] + c(Rh - half > Rt, Rh + half < Rt)
    boot <- boot_icc(Rh, n_d, k_d, n_boot)
    qb <- quantile(boot, c(0.025, 0.975), names = FALSE)
    miss[2, ] <- miss[2, ] + c(qb[1] > Rt, qb[2] < Rt)
    ci <- lr_interval(s)
    miss[3, ] <- miss[3, ] + c(ci[1] > Rt, ci[2] < Rt)
  }
  cover_d <- rbind(cover_d, data.frame(
    R_true = Rt, at_zero = at_zero / reps_d, neg_lower = neg_lower / reps_d,
    naive = 1 - sum(miss[1, ]) / reps_d,
    bootstrap = 1 - sum(miss[2, ]) / reps_d,
    likelihood = 1 - sum(miss[3, ]) / reps_d))
}
print(round(c(replicates = reps_d, bootstrap_draws = n_boot), 0))
print(round(cover_d, 4))
print(round(c(mc_se_of_coverage = sqrt(nominal * (1 - nominal) / reps_d),
              max_bootstrap_minus_naive = max(abs(cover_d$bootstrap - cover_d$naive))), 4))

## ---- fig-coverage ----
long_d <- rbind(
  data.frame(R_true = cover_d$R_true, coverage = cover_d$naive, series = "naive normal"),
  data.frame(R_true = cover_d$R_true, coverage = cover_d$bootstrap,
             series = "parametric bootstrap"),
  data.frame(R_true = cover_d$R_true, coverage = cover_d$likelihood,
             series = "likelihood ratio"))
long_d$series <- factor(long_d$series,
                        levels = c("naive normal", "parametric bootstrap",
                                   "likelihood ratio"))

ggplot(long_d, aes(R_true, coverage, colour = series)) +
  geom_hline(yintercept = nominal, linetype = 2, colour = te_pal$ink, linewidth = 0.6) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.2) +
  scale_colour_manual(values = c(te_pal$green, te_pal$gold, te_pal$clay), name = NULL) +
  scale_x_continuous(breaks = R_grid_d) +
  labs(title = "Coverage of three intervals for R",
       x = "true repeatability", y = "measured coverage") +
  theme_te()

## ---- boundary-test ----
set.seed(20260801)
reps_lrt <- 3000
alpha <- 0.05
stat_lrt <- numeric(reps_lrt)
for (r in seq_len(reps_lrt)) {
  s <- ss_of(sim_balanced(n_d, k_d, 0))
  stat_lrt[r] <- deviance_R(0, s) - profile_min(s)[2]
}
print(c(replicates = reps_lrt))
print(round(c(alpha = alpha), 4))
print(round(c(crit_chisq1 = qchisq(1 - alpha, 1), crit_mixture = qchisq(1 - 2 * alpha, 1),
              error_chisq1 = mean(stat_lrt > qchisq(1 - alpha, 1)),
              error_mixture = mean(stat_lrt > qchisq(1 - 2 * alpha, 1)),
              prop_stat_zero = mean(stat_lrt <= 0)), 4))
