# Rounded and coarsened measurements
# https://tidyecology.com/posts/rounded-and-coarsened-measurements/
#
# 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-15

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

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

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"),
          axis.text = element_text(colour = "#2c3a31"),
          legend.position = "bottom")
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- lattice ----
round_to <- function(x, h) h * round(x / h)

set.seed(20260731)
mu_true <- 41.5
sd_true <- 12
h_card <- 5
peek <- rnorm(8, mu_true, sd_true)
demo <- data.frame(true_height = round(peek, 2),
                   recorded = round_to(peek, h_card))
demo$residual <- demo$recorded - demo$true_height
print(demo)
max_resid <- max(abs(demo$residual))
print(c(max_abs_residual = max_resid, half_grid = h_card / 2))

## ---- variance-inflation ----
set.seed(20260732)
n_quad <- 720
n_rep <- 2000
sim <- matrix(NA_real_, n_rep, 4)
for (r in seq_len(n_rep)) {
  z <- rnorm(n_quad, mu_true, sd_true)
  y <- round_to(z, h_card)
  sim[r, ] <- c(mean(z), mean(y), var(z), var(y))
}
mean_bias <- mean(sim[, 2]) - mu_true
mean_mcse <- sd(sim[, 2]) / sqrt(n_rep)
infl_obs <- mean(sim[, 4]) - mean(sim[, 3])
infl_ana <- h_card^2 / 12
infl_ratio <- infl_obs / infl_ana
sd_naive <- sqrt(mean(sim[, 4]))
sd_shep <- sqrt(mean(sim[, 4]) - infl_ana)
print(round(c(mean_exact = mean(sim[, 1]), mean_rounded = mean(sim[, 2]),
              bias = mean_bias, mcse = mean_mcse, bias_in_mcse = mean_bias / mean_mcse), 5))
print(round(c(var_exact = mean(sim[, 3]), var_rounded = mean(sim[, 4]),
              inflation = infl_obs, analytic = infl_ana, ratio = infl_ratio), 4))
print(round(c(sd_naive = sd_naive, sd_sheppard = sd_shep, truth = sd_true,
              naive_excess_pct = 100 * (sd_naive / sd_true - 1)), 4))

## ---- sheppard-sweep ----
set.seed(20260733)
k_seq <- c(0.25, 0.5, 0.75, 1, 1.5, 2, 2.5, 3, 4)
n_sw <- 100000
n_sw_rep <- 40
sweep_res <- do.call(rbind, lapply(k_seq, function(k) {
  hh <- k * sd_true
  vr <- numeric(n_sw_rep)
  vx <- numeric(n_sw_rep)
  for (i in seq_len(n_sw_rep)) {
    z <- rnorm(n_sw, mu_true, sd_true)
    vx[i] <- var(z)
    vr[i] <- var(round_to(z, hh))
  }
  data.frame(k = k, infl = mean(vr) - mean(vx), analytic = hh^2 / 12,
             sd_naive = sqrt(mean(vr)),
             sd_shep = sqrt(pmax(mean(vr) - hh^2 / 12, 0)))
}))
sweep_res$ratio <- sweep_res$infl / sweep_res$analytic
print(round(sweep_res, 4))
k_ok <- max(sweep_res$k[abs(sweep_res$ratio - 1) < 0.05])
sd_at3 <- sweep_res$sd_shep[sweep_res$k == 3]
sd_at4 <- sweep_res$sd_shep[sweep_res$k == 4]
ratio_at25 <- sweep_res$ratio[sweep_res$k == 2.5]
print(round(c(valid_to_k = k_ok, ratio_at_2_5 = ratio_at25,
              sd_at_k3 = sd_at3, sd_at_k4 = sd_at4), 4))

## ---- fig-sheppard ----
lab_sw <- c("standard deviation of the recorded values",
            "after Sheppard's correction")
sw_dat <- data.frame(
  k = rep(sweep_res$k, 2),
  value = c(sweep_res$sd_naive, sweep_res$sd_shep),
  series = factor(rep(lab_sw, each = nrow(sweep_res)), levels = lab_sw))

ggplot(sw_dat, aes(k, value, colour = series, shape = series)) +
  geom_hline(yintercept = sd_true, linetype = "22", colour = te_pal$ink,
             linewidth = 0.7) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.2) +
  annotate("text", x = 3.5, y = sd_true + 0.7, label = "true value",
           colour = te_pal$ink, size = 3.3) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$forest), name = NULL) +
  scale_shape_manual(values = c(17, 16), name = NULL) +
  guides(colour = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
  labs(x = "grid width as a multiple of the population standard deviation",
       y = "recovered standard deviation (cm)",
       title = "Where the classical correction stops working") +
  theme_te() +
  theme(plot.margin = margin(8, 16, 4, 8))

## ---- heath-data ----
set.seed(20260738)
z_heath <- rnorm(n_quad, mu_true, sd_true)
ht5 <- round_to(z_heath, h_card)
ht20 <- round_to(z_heath, 20)
print(c(distinct_exact = length(unique(z_heath)),
        distinct_5cm = length(unique(ht5)),
        distinct_20cm = length(unique(ht20))))
print(round(c(mean_exact = mean(z_heath), mean_5cm = mean(ht5),
              sd_exact = sd(z_heath), sd_5cm = sd(ht5),
              sd_sheppard = sqrt(var(ht5) - h_card^2 / 12)), 4))
p_exact <- shapiro.test(z_heath)$p.value
p_5cm <- shapiro.test(ht5)$p.value
p_20cm <- shapiro.test(ht20)$p.value
print(signif(c(shapiro_exact = p_exact, shapiro_5cm = p_5cm,
               shapiro_20cm = p_20cm), 4))

## ---- fig-ecdf ----
lab_ec <- c("exact heights", "5 cm grid", "20 cm grid")
ec_dat <- data.frame(
  height = c(z_heath, ht5, ht20),
  series = factor(rep(lab_ec, each = n_quad), levels = lab_ec))
curve_dat <- data.frame(
  height = seq(min(z_heath) - 12, max(z_heath) + 12, length.out = 400))
curve_dat$cdf <- pnorm(curve_dat$height, mu_true, sd_true)

ggplot(ec_dat, aes(height, colour = series)) +
  geom_line(data = curve_dat, aes(height, cdf), inherit.aes = FALSE,
            colour = te_pal$ink, linewidth = 0.9) +
  stat_ecdf(geom = "step", linewidth = 0.7) +
  scale_colour_manual(values = c(te_pal$sage, te_pal$forest, te_pal$clay),
                      name = NULL) +
  labs(x = "sward height (cm)", y = "cumulative proportion",
       title = "One sample, three rulers, one true distribution") +
  theme_te() +
  theme(plot.margin = margin(8, 16, 4, 8))

## ---- shape-ladder ----
set.seed(20260734)
n_site <- 60
n_shape <- 3000
h_ladder <- c(0, 1, 2, 5, 10, 20)
shape_res <- do.call(rbind, lapply(h_ladder, function(h) {
  rej <- 0
  dis <- numeric(n_shape)
  for (r in seq_len(n_shape)) {
    z <- rnorm(n_site, mu_true, sd_true)
    y <- if (h == 0) z else round_to(z, h)
    dis[r] <- length(unique(y))
    p <- tryCatch(shapiro.test(y)$p.value, error = function(e) 0)
    if (p < 0.05) rej <- rej + 1
  }
  data.frame(h = h, distinct = mean(dis), sw_rej = rej / n_shape)
}))
print(round(shape_res, 4))
rej_of <- function(h) shape_res$sw_rej[shape_res$h == h]
print(round(c(exact = rej_of(0), grid_5 = rej_of(5), grid_10 = rej_of(10),
              grid_20 = rej_of(20)), 4))

## ---- ic-likelihood ----
nll_ic <- function(par, y, h) {
  s <- exp(par[2])
  p <- pnorm(y + h / 2, par[1], s) - pnorm(y - h / 2, par[1], s)
  -sum(log(pmax(p, 1e-300)))
}

fit_ic <- function(y, h) {
  o <- optim(c(mean(y), log(max(sd(y), 1e-3))), nll_ic, y = y, h = h,
             method = "BFGS", hessian = TRUE)
  se <- sqrt(diag(solve(o$hessian)))
  c(mu = unname(o$par[1]), sigma = unname(exp(o$par[2])),
    se_mu = unname(se[1]), se_sigma = unname(exp(o$par[2]) * se[2]))
}

ic_heath <- fit_ic(ht5, h_card)
print(round(ic_heath, 4))
print(round(c(exact_sample_mean = mean(z_heath), exact_sample_sd = sd(z_heath),
              naive_sd = sd(ht5), sheppard_sd = sqrt(var(ht5) - h_card^2 / 12),
              ic_sd = unname(ic_heath["sigma"])), 4))

## ---- ic-recovery ----
set.seed(20260737)
n_rec <- 800
rec_res <- do.call(rbind, lapply(c(5, 10, 20), function(h) {
  M <- matrix(NA_real_, n_rec, 5)
  for (r in seq_len(n_rec)) {
    y <- round_to(rnorm(n_quad, mu_true, sd_true), h)
    f <- fit_ic(y, h)
    M[r, ] <- c(mean(y), sd(y), sqrt(max(var(y) - h^2 / 12, 0)), f["sigma"],
                abs(f["mu"] - mu_true) < 1.96 * f["se_mu"])
  }
  data.frame(h = h, naive_mean = mean(M[, 1]), naive_sd = mean(M[, 2]),
             naive_excess_pct = 100 * (mean(M[, 2]) / sd_true - 1),
             sheppard_sd = mean(M[, 3]), ic_sd = mean(M[, 4]),
             ic_coverage = mean(M[, 5]))
}))
print(round(rec_res, 4))
excess_of <- function(h) rec_res$naive_excess_pct[rec_res$h == h]

## ---- grid-gof ----
gof_grid <- function(y, h, mu, s, min_exp = 5) {
  lv <- seq(min(y), max(y), by = h)
  ob <- as.integer(table(factor(y, levels = lv)))
  edge_lo <- lv - h / 2
  edge_hi <- lv + h / 2
  edge_lo[1] <- -Inf
  edge_hi[length(edge_hi)] <- Inf
  ex <- length(y) * (pnorm(edge_hi, mu, s) - pnorm(edge_lo, mu, s))
  repeat {
    k <- length(ex)
    if (k <= 4) break
    i <- which.min(ex)
    if (ex[i] >= min_exp) break
    j <- if (i == 1) 2 else if (i == k) k - 1 else if (ex[i - 1] < ex[i + 1]) i - 1 else i + 1
    keep <- min(i, j)
    drop_at <- max(i, j)
    ob[keep] <- ob[i] + ob[j]
    ex[keep] <- ex[i] + ex[j]
    ob <- ob[-drop_at]
    ex <- ex[-drop_at]
  }
  dfree <- length(ex) - 3
  if (dfree < 1) return(c(x2 = NA_real_, dfree = NA_real_, p = NA_real_))
  x2 <- sum((ob - ex)^2 / ex)
  c(x2 = x2, dfree = dfree, p = pchisq(x2, dfree, lower.tail = FALSE))
}

gof_heath <- gof_grid(ht5, h_card, ic_heath["mu"], ic_heath["sigma"])
print(round(gof_heath, 4))

set.seed(20260736)
n_gof <- 3000
gof_res <- do.call(rbind, lapply(c(1, 2, 5, 10, 20), function(h) {
  rj <- 0
  nv <- 0
  for (r in seq_len(n_gof)) {
    y <- round_to(rnorm(n_site, mu_true, sd_true), h)
    f <- fit_ic(y, h)
    p <- gof_grid(y, h, f["mu"], f["sigma"])["p"]
    if (!is.na(p)) {
      nv <- nv + 1
      if (p < 0.05) rj <- rj + 1
    }
  }
  data.frame(h = h, gof_rej = rj / nv, testable = nv / n_gof)
}))
print(round(gof_res, 4))
gof_of <- function(h) gof_res$gof_rej[gof_res$h == h]

## ---- fig-rejection ----
lab_rj <- c("Shapiro-Wilk on the recorded values",
            "grid chi-square after the interval-censored fit")
rj_dat <- data.frame(
  h = c(gof_res$h, gof_res$h),
  rate = c(shape_res$sw_rej[match(gof_res$h, shape_res$h)], gof_res$gof_rej),
  series = factor(rep(lab_rj, each = nrow(gof_res)), levels = lab_rj))

ggplot(rj_dat, aes(h, rate, colour = series, shape = series)) +
  geom_hline(yintercept = 0.05, linetype = "22", colour = te_pal$ink,
             linewidth = 0.7) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.3) +
  annotate("text", x = 15.5, y = 0.017, label = "nominal 5 per cent",
           colour = te_pal$ink, size = 3.3) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$forest), name = NULL) +
  scale_shape_manual(values = c(17, 16), name = NULL) +
  scale_y_continuous(limits = c(0, 1)) +
  guides(colour = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
  labs(x = "grid width (cm)", y = "rejection rate at the 5 per cent level",
       title = "The ruler rejects, the right test does not") +
  theme_te() +
  theme(plot.margin = margin(8, 16, 4, 8))

## ---- distance-setup ----
d_true <- 80
len_line <- 30
w_tr <- 0.15
sig_true <- 0.06

g_area <- function(a, b, s) s * sqrt(2 * pi) * (pnorm(b / s) - pnorm(a / s))
esw_hn <- function(s) g_area(0, w_tr, s)
lo_b <- log(0.004)
hi_b <- log(2)

fit_point <- function(x) {
  nll <- function(ls) {
    s <- exp(ls)
    -sum(-x^2 / (2 * s^2) - log(esw_hn(s)))
  }
  exp(optim(lo_b, nll, method = "Brent", lower = lo_b, upper = hi_b)$par)
}

fit_interval <- function(y, h) {
  cell_lo <- pmax(y - h / 2, 0)
  cell_hi <- pmin(y + h / 2, w_tr)
  nll <- function(ls) {
    s <- exp(ls)
    -sum(log(pmax(g_area(cell_lo, cell_hi, s), 1e-300)) - log(esw_hn(s)))
  }
  exp(optim(lo_b, nll, method = "Brent", lower = lo_b, upper = hi_b)$par)
}

draw_survey <- function() {
  n_all <- round(d_true * 2 * w_tr * len_line)
  x_all <- runif(n_all, 0, w_tr)
  x_all[rbinom(n_all, 1, exp(-x_all^2 / (2 * sig_true^2))) == 1]
}

set.seed(20260741)
h_ds <- 0.05
x_ex <- draw_survey()
x_rd <- pmin(round_to(x_ex, h_ds), w_tr)
s_ex <- fit_point(x_ex)
s_rd <- fit_point(x_rd)
s_iv <- fit_interval(x_rd, h_ds)
dens_from <- function(s) length(x_ex) / (2 * len_line * esw_hn(s))
one_survey <- c(n_detected = length(x_ex), sigma_exact = s_ex,
                sigma_rounded = s_rd, sigma_interval = s_iv,
                esw_exact = esw_hn(s_ex), esw_rounded = esw_hn(s_rd),
                esw_interval = esw_hn(s_iv), d_exact = dens_from(s_ex),
                d_rounded = dens_from(s_rd), d_interval = dens_from(s_iv))
print(round(one_survey, 4))

## ---- distance-sweep ----
set.seed(20260742)
n_ds <- 400
ds_res <- do.call(rbind, lapply(c(0.01, 0.025, 0.05, 0.075), function(h) {
  M <- matrix(NA_real_, n_ds, 4)
  for (r in seq_len(n_ds)) {
    xx <- draw_survey()
    yy <- pmin(round_to(xx, h), w_tr)
    M[r, ] <- c(length(xx) / (2 * len_line * esw_hn(fit_point(xx))),
                length(xx) / (2 * len_line * esw_hn(fit_point(yy))),
                length(xx) / (2 * len_line * esw_hn(fit_interval(yy, h))),
                mean(yy^2) - mean(xx^2))
  }
  data.frame(grid_m = h * 1000, d_exact = mean(M[, 1]), d_rounded = mean(M[, 2]),
             d_interval = mean(M[, 3]),
             rounded_pct = 100 * (mean(M[, 2]) / mean(M[, 1]) - 1),  # against the exact fit
             interval_pct = 100 * (mean(M[, 3]) / d_true - 1),
             moment_shift = mean(M[, 4]),
             moment_ratio = mean(M[, 4]) / (h^2 / 12))
}))
print(round(ds_res, 4))
ds_res$grid_over_scale <- ds_res$grid_m / (sig_true * 1000)
pct_at <- function(g) ds_res$rounded_pct[ds_res$grid_m == g]
iv_at <- function(g) ds_res$interval_pct[ds_res$grid_m == g]
ratio_at <- function(g) ds_res$grid_over_scale[ds_res$grid_m == g]
print(round(ds_res[, c("grid_m", "grid_over_scale", "rounded_pct", "interval_pct")], 4))

## ---- fig-distance ----
lab_ds <- c("exact distances", "rounded, treated as exact",
            "rounded, treated as intervals")
ds_dat <- data.frame(
  grid_m = rep(ds_res$grid_m, 3),
  density = c(ds_res$d_exact, ds_res$d_rounded, ds_res$d_interval),
  series = factor(rep(lab_ds, each = nrow(ds_res)), levels = lab_ds))

ggplot(ds_dat, aes(grid_m, density, colour = series, shape = series)) +
  geom_hline(yintercept = d_true, linetype = "22", colour = te_pal$ink,
             linewidth = 0.7) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.3) +
  annotate("text", x = 20, y = d_true + 0.55, label = "true density",
           colour = te_pal$ink, size = 3.3) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay, te_pal$gold),
                      name = NULL) +
  scale_shape_manual(values = c(16, 17, 15), name = NULL) +
  guides(colour = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
  labs(x = "rounding grid for perpendicular distance (m)",
       y = "mean estimated density (animals per square km)",
       title = "What the ruler costs a distance sampling survey") +
  theme_te() +
  theme(plot.margin = margin(8, 16, 4, 8))

## ---- moment-link ----
print(round(ds_res[, c("grid_m", "moment_shift", "moment_ratio")], 6))
mom_lo <- min(ds_res$moment_ratio)
mom_hi <- max(ds_res$moment_ratio)

## ---- mixed-grid ----
nll_mix <- function(par, y, hv) {
  s <- exp(par[2])
  -sum(log(pmax(pnorm(y + hv / 2, par[1], s) - pnorm(y - hv / 2, par[1], s), 1e-300)))
}
fit_mix <- function(y, hv) {
  o <- optim(c(mean(y), log(sd(y))), nll_mix, y = y, hv = hv, method = "BFGS")
  c(mu = unname(o$par[1]), sigma = unname(exp(o$par[2])))
}

set.seed(20260743)
n_mix <- 400
M_mix <- t(replicate(n_mix, {
  z <- rnorm(n_quad, mu_true, sd_true)
  hv <- rep(c(h_card, 20), each = n_quad / 2)
  y <- round_to(z, hv)
  c(sd(y), fit_mix(y, rep(h_card, n_quad))["sigma"],
    fit_mix(y, rep(20, n_quad))["sigma"], fit_mix(y, hv)["sigma"])
}))
mix_res <- c(naive_sd = mean(M_mix[, 1]), assume_fine = mean(M_mix[, 2]),
             assume_coarse = mean(M_mix[, 3]), per_observation = mean(M_mix[, 4]))
print(round(mix_res, 4))
print(round(100 * (mix_res / sd_true - 1), 3))
