# Checking published summary statistics
# https://tidyecology.com/posts/checking-published-summary-statistics/
#
# 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(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))
}

## ---- grim ----
grim_ok <- function(m_rep, n, d, lenient = FALSE) {
  sc   <- 10^d
  m_int <- round(m_rep * sc)                      # printed mean in units of the last decimal
  s_lo <- -((-(2 * m_int - 1) * n) %/% (2 * sc))  # smallest S with S / n >= m - half a unit
  if (lenient) 2 * s_lo * sc <= (2 * m_int + 1) * n else 2 * s_lo * sc < (2 * m_int + 1) * n
}

# brute force: every sum from 0 to 20 n, rounded half up, compared with the function
grim_brute <- function(m_rep, n, d) {
  s_all <- 0:(20 * n)
  any(floor(s_all * 10^d / n + 0.5) == round(m_rep * 10^d))
}
set.seed(2017)
n_check <- 3000
check_n <- sample(2:150, n_check, replace = TRUE)
check_m <- round(runif(n_check, 0, 15), 2)
agree_all <- all(mapply(grim_brute, check_m, check_n, 2) == grim_ok(check_m, check_n, 2))

clutch_n <- 24; clutch_m <- 3.47
clutch_lo <- floor(clutch_m * clutch_n); clutch_hi <- clutch_lo + 1
clutch_ok <- grim_ok(clutch_m, clutch_n, 2)

## ---- gridmap ----
map_n   <- 1:120
map_dec <- 0:99
grim_map <- expand.grid(n = map_n, dec = map_dec)
grim_map$ok <- grim_ok(3 + grim_map$dec / 100, grim_map$n, 2)
grim_map$status <- ifelse(grim_map$ok, "consistent", "inconsistent")

## ---- fig-grim-map ----
ggplot(grim_map, aes(n, dec / 100, fill = status)) +
  geom_tile() +
  geom_vline(xintercept = 100, colour = te_ink, linewidth = 0.5, linetype = "dashed") +
  scale_fill_manual(values = c(consistent = te_forest, inconsistent = te_paper)) +
  scale_x_continuous(breaks = seq(0, 120, 20), expand = c(0, 0)) +
  scale_y_continuous(breaks = seq(0, 1, 0.2), expand = c(0, 0)) +
  labs(x = "sample size n", y = "decimal part of the printed mean", fill = NULL,
       title = "The grid of reachable means",
       subtitle = "two decimals, round half up; dark cells can come from integer data") +
  theme_datasheet() +
  theme(legend.position = "top",
        legend.key = element_rect(colour = te_ink, linewidth = 0.3))

## ---- power ----
grim_power <- function(n, d) pmax(0, 1 - n / 10^d)

dec_grid <- function(d) 3 + (0:(10^d - 1)) / 10^d
exact_gap <- sapply(1:3, function(d) {
  n_set <- 1:(10^d + 5)
  share <- sapply(n_set, function(n) mean(!grim_ok(dec_grid(d), n, d)))
  max(abs(share - grim_power(n_set, d)))
})

n_sim <- 10000
set.seed(363)
sim24_m   <- round(runif(n_sim, 1, 9), 2)
flag24    <- mean(!grim_ok(sim24_m, clutch_n, 2))
flag24_se <- sqrt(flag24 * (1 - flag24) / n_sim)

pair_n  <- sample(5:150, n_sim, replace = TRUE)
pair_m  <- round(runif(n_sim, 1, 9), 2)
pair_flag <- mean(!grim_ok(pair_m, pair_n, 2))
pair_cf   <- mean(grim_power(pair_n, 2))
pair_z    <- (pair_flag - pair_cf) / sqrt(pair_cf * (1 - pair_cf) / n_sim)
share_big <- mean(pair_n >= 100)

## ---- ties ----
gcd_int <- function(a, b) ifelse(b == 0, a, gcd_int(b, a %% b))
two_adic <- function(n) { v <- 0; while (n %% 2 == 0) { n <- n / 2; v <- v + 1 }; v }

# ties exist exactly when n has more factors of two than 10^d; there are gcd(n, 10^d) of them
tie_count <- function(n, d) if (two_adic(n) > d) gcd_int(n, 10^d) else 0
grim_power_lenient <- function(n, d) pmax(0, 1 - (n + tie_count(n, d)) / 10^d)

n_tie_set <- 1:200
len_count <- sapply(n_tie_set, function(n) mean(!grim_ok(dec_grid(2), n, 2, lenient = TRUE)))
len_form  <- sapply(n_tie_set, grim_power_lenient, d = 2)
tie_gap   <- max(abs(len_count - len_form))
tie_ns    <- n_tie_set[n_tie_set < 100 & sapply(n_tie_set, tie_count, d = 2) > 0]

flag24_len <- mean(!grim_ok(sim24_m, clutch_n, 2, lenient = TRUE))
len_40 <- grim_power_lenient(40, 2); len_80 <- grim_power_lenient(80, 2)

power_tab <- data.frame(n = rep(1:120, 2),
                        power = c(grim_power(1:120, 2), sapply(1:120, grim_power_lenient, d = 2)),
                        rule = rep(c("one fixed rounding rule", "either neighbour of a tie"), each = 120))
power_tab$rule <- factor(power_tab$rule, levels = c("one fixed rounding rule", "either neighbour of a tie"))

## ---- fig-grim-power ----
ggplot(power_tab, aes(n, power, colour = rule)) +
  geom_line(data = subset(power_tab, rule == "one fixed rounding rule"), linewidth = 0.9) +
  geom_point(data = subset(power_tab, rule == "either neighbour of a tie" & n %% 8 == 0 & n < 100),
             size = 2.4) +
  annotate("point", x = clutch_n, y = flag24, shape = 4, size = 3.5, stroke = 1.1, colour = te_ink) +
  annotate("text", x = clutch_n + 4, y = flag24 + 0.07, hjust = 0,
           label = "simulated, n = 24", colour = te_ink, size = 3.6) +
  scale_colour_manual(values = c("one fixed rounding rule" = te_forest,
                                 "either neighbour of a tie" = te_rust)) +
  scale_x_continuous(breaks = seq(0, 120, 20)) +
  coord_cartesian(ylim = c(0, 1)) +
  labs(x = "sample size n", y = "share of printed means GRIM can reject", colour = NULL,
       title = "Blind from one hundred, and earlier at multiples of eight",
       subtitle = "red points: sample sizes with rounding ties, checked leniently") +
  theme_datasheet() +
  theme(legend.position = "top")

## ---- missing ----
honest_flag <- function(n_rep, k_miss, n_rep_sim = 10000) {
  n_use <- n_rep - k_miss
  sums  <- rowSums(matrix(2 + rpois(n_rep_sim * n_use, 1.5), n_rep_sim))
  m_rep <- floor(sums * 100 / n_use + 0.5) / 100
  mean(!grim_ok(m_rep, n_rep, 2, lenient = TRUE))
}
k_set <- 0:3
set.seed(1205)
fa_24 <- sapply(k_set, function(k) honest_flag(24, k))
fa_60 <- sapply(k_set, function(k) honest_flag(60, k))
fa_se_max <- sqrt(0.25 / n_sim)

allow_power <- function(n, j_max, d = 2) {
  reach <- rep(FALSE, 10^d)
  for (j in 0:j_max) reach <- reach | grim_ok(dec_grid(d), n - j, d, lenient = TRUE)
  mean(!reach)
}
n_allow <- c(12, 24, 36, 48, 60)
allow_tab <- expand.grid(n = n_allow, j_max = 0:3)
allow_tab$power <- mapply(allow_power, allow_tab$n, allow_tab$j_max)
pw <- function(n, j) allow_tab$power[allow_tab$n == n & allow_tab$j_max == j]

fa_tab <- data.frame(k = rep(k_set, 2), rate = c(fa_24, fa_60),
                     n_print = factor(rep(c("printed n = 24", "printed n = 60"), each = length(k_set))))

## ---- fig-missing ----
p_fa <- ggplot(fa_tab, aes(k, rate, colour = n_print)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.6) +
  scale_colour_manual(values = c("printed n = 24" = te_rust, "printed n = 60" = te_gold)) +
  scale_x_continuous(breaks = k_set) +
  coord_cartesian(ylim = c(0, 1)) +
  labs(x = "nests missing from the mean", y = "honest means flagged", colour = NULL,
       title = "False alarms") +
  theme_datasheet() +
  theme(legend.position = "top")

p_allow <- ggplot(allow_tab, aes(j_max, power, group = factor(n))) +
  geom_line(colour = te_forest, linewidth = 0.8) +
  geom_point(colour = te_forest, size = 2.2) +
  geom_text(data = subset(allow_tab, j_max == 0), aes(label = paste("n =", n)),
            hjust = 1.2, size = 3.3, colour = te_ink) +
  scale_x_continuous(breaks = 0:3, limits = c(-0.7, 3.1)) +
  coord_cartesian(ylim = c(0, 1)) +
  labs(x = "exclusions allowed for, j", y = "share of endings still rejectable",
       title = "Cost of the allowance") +
  theme_datasheet()

p_fa + p_allow + plot_annotation(theme = theme_datasheet())

## ---- sdbounds ----
sd_bounds <- function(s_sum, n, lo, hi) {
  q <- s_sum %/% n; r <- s_sum - q * n
  ss_min <- (n - r) * q^2 + r * (q + 1)^2
  k_hi <- (s_sum - n * lo) %/% (hi - lo)
  if (k_hi >= n) {
    ss_max <- n * hi^2
  } else {
    mid <- s_sum - k_hi * hi - (n - k_hi - 1) * lo
    ss_max <- k_hi * hi^2 + (n - k_hi - 1) * lo^2 + mid^2
  }
  sqrt(c(min = (ss_min - s_sum^2 / n) / (n - 1), max = (ss_max - s_sum^2 / n) / (n - 1)))
}

# reach[S + 1, SS + 1] is TRUE if some n scores in lo:hi have sum S and sum of squares SS
reach_ss <- function(n, lo, hi) {
  s_top <- n * hi; ss_top <- n * hi^2
  cur <- matrix(FALSE, s_top + 1, ss_top + 1); cur[1, 1] <- TRUE
  for (i in seq_len(n)) {
    nxt <- matrix(FALSE, s_top + 1, ss_top + 1)
    idx <- which(cur, arr.ind = TRUE)
    for (v in lo:hi) {
      moved <- cbind(idx[, 1] + v, idx[, 2] + v^2)
      nxt[moved] <- TRUE
    }
    cur <- nxt
  }
  cur
}

enum_gap <- 0; dp_match <- TRUE
for (n in 2:6) {
  all_samples <- as.matrix(expand.grid(rep(list(0:4), n)))
  s_row <- rowSums(all_samples); sd_row <- apply(all_samples, 1, sd)
  for (s_val in unique(s_row)) {
    obs <- range(sd_row[s_row == s_val])
    enum_gap <- max(enum_gap, abs(sd_bounds(s_val, n, 0, 4) - obs))
  }
  enum_mat <- matrix(FALSE, 4 * n + 1, 16 * n + 1)
  enum_mat[cbind(s_row + 1, rowSums(all_samples^2) + 1)] <- TRUE
  dp_match <- dp_match && identical(enum_mat, reach_ss(n, 0, 4))
}

tree_n <- 20; tree_m <- 3.60
tree_reach <- reach_ss(tree_n, 0, 4)
tree_s <- which(floor((0:(4 * tree_n)) * 100 / tree_n + 0.5) == round(tree_m * 100)) - 1
tree_b <- sd_bounds(tree_s, tree_n, 0, 4)
sd_of <- function(s_val, ss) sqrt((ss - s_val^2 / tree_n) / (tree_n - 1))
tree_sds <- sort(sd_of(tree_s, which(tree_reach[tree_s + 1, ]) - 1), decreasing = TRUE)

sd_printed <- c(1.10, 1.20, 1.30)
sd_ok <- sapply(sd_printed, function(x) any(tree_sds >= x - 0.005 & tree_sds < x + 0.005))
k_top <- (tree_s - 0) %/% 4

# the same top gap at a central mean: step in sum of squares and step in SD
top_two <- function(s_val) {
  ss <- sort(which(tree_reach[s_val + 1, ]) - 1, decreasing = TRUE)[1:2]
  c(ss_step = ss[1] - ss[2], sd_gap = sd_of(s_val, ss[1]) - sd_of(s_val, ss[2]))
}
mid_s   <- 2 * tree_n
gap_mid <- top_two(mid_s)
gap_hi  <- top_two(tree_s)

band_tab <- do.call(rbind, lapply(0:(4 * tree_n), function(s_val) {
  b <- sd_bounds(s_val, tree_n, 0, 4)
  data.frame(mean = s_val / tree_n, sd_min = b[["min"]], sd_max = b[["max"]])
}))
dot_tab <- do.call(rbind, lapply(0:(4 * tree_n), function(s_val) {
  ss <- which(tree_reach[s_val + 1, ]) - 1
  data.frame(mean = s_val / tree_n, sd = sd_of(s_val, ss))
}))
sd_pts <- data.frame(mean = tree_m, sd = sd_printed,
                     status = ifelse(sd_ok, "printed SD possible", "printed SD impossible"))

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

## ---- fig-sd-band ----
ggplot(band_tab, aes(mean)) +
  geom_ribbon(aes(ymin = sd_min, ymax = sd_max), fill = te_forest, alpha = 0.15) +
  geom_line(aes(y = sd_max), colour = te_forest, linewidth = 0.8) +
  geom_line(aes(y = sd_min), colour = te_forest, linewidth = 0.8) +
  geom_point(data = dot_tab, aes(y = sd), colour = te_forest, size = 0.35, alpha = 0.6) +
  geom_point(data = sd_pts, aes(y = sd, colour = status), size = 3.2, shape = 18) +
  scale_colour_manual(values = c("printed SD possible" = te_gold, "printed SD impossible" = te_rust)) +
  labs(x = "mean score of 20 trees", y = "standard deviation", colour = NULL,
       title = "Spread is bounded by the scale, and granular inside it",
       subtitle = "lines: closed form bounds; dots: every reachable standard deviation") +
  theme_datasheet() +
  theme(legend.position = "top")

## ---- pband ----
p_band <- function(t_rep, df, dec) {
  half <- 0.5 * 10^-dec
  t_lo <- max(abs(t_rep) - half, 0); t_hi <- abs(t_rep) + half
  c(lo = 2 * pt(-t_hi, df), hi = 2 * pt(-t_lo, df))
}
df_nest <- 38
band_a <- p_band(2.05, df_nest, 2)
band_b <- p_band(2.02, df_nest, 2)
band_c <- p_band(2.1, df_nest, 1)
band_0 <- p_band(0, df_nest, 2)
t_crit <- qt(0.975, df_nest)
p_rep_a <- 0.047
cons_a <- (p_rep_a + 0.0005 >= band_a[["lo"]]) & (p_rep_a - 0.0005 <= band_a[["hi"]])

curve_tab <- data.frame(t = seq(1.98, 2.10, by = 0.0005))
curve_tab$p <- 2 * pt(-curve_tab$t, df_nest)
rect_tab <- data.frame(xmin = c(2.045, 2.015), xmax = c(2.055, 2.025),
                       ymin = c(band_a[["lo"]], band_b[["lo"]]), ymax = c(band_a[["hi"]], band_b[["hi"]]),
                       lab = c("printed t = 2.05", "printed t = 2.02"))

## ---- fig-p-band ----
ggplot(curve_tab, aes(t, p)) +
  geom_rect(data = rect_tab, inherit.aes = FALSE,
            aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = lab), alpha = 0.55) +
  geom_line(colour = te_ink, linewidth = 0.8) +
  geom_hline(yintercept = 0.05, linetype = "dashed", colour = te_rust, linewidth = 0.6) +
  annotate("text", x = 2.095, y = 0.0503, label = "p = 0.05", hjust = 1, vjust = 0,
           colour = te_rust, size = 3.6) +
  scale_fill_manual(values = c("printed t = 2.05" = te_forest, "printed t = 2.02" = te_gold)) +
  labs(x = "t statistic", y = "two-sided p value", fill = NULL,
       title = "A printed t is an interval, and so is its p",
       subtitle = "38 degrees of freedom") +
  theme_datasheet() +
  theme(legend.position = "top")
