# Checking a sequential decision model
# https://tidyecology.com/posts/checking-a-sequential-decision-model/
#
# 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"))
}

## ---- 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)), "}$")
}

## ---- system ----
spread_rate <- 0.7
seed_rain   <- 0.004
log_sd      <- 0.25
damage_full <- 25
dfac        <- 0.95

act_name <- c("No action", "Hand pulling", "Contract control")
act_cap  <- c(0.00, 0.05, 0.12)
act_rate <- c(0, 90, 200)

med_map <- function(x, a, rr = spread_rate, mm = seed_rain) {
  y <- x - pmin(act_cap[a], x)
  y + rr * y * (1 - y) + mm * (1 - y)
}
stage_cost <- function(x, a) damage_full * x + act_rate[a] * pmin(act_cap[a], x)
nodes_of <- function(n) seq(0, 1, length.out = n)

build_P <- function(n, rr = spread_rate, ss = log_sd, mm = seed_rain) {
  xs <- nodes_of(n); hh <- 1 / (n - 1)
  edg <- log(c(xs[-1] - hh / 2, Inf))
  lapply(seq_along(act_name), function(a) {
    lz <- log(med_map(xs, a, rr, mm))
    cp <- pnorm(t(outer(edg, lz, "-")) / ss)
    pm <- cbind(cp[, 1], cp[, -1] - cp[, -ncol(cp)])
    pm[pm < 0] <- 0
    pm / rowSums(pm)
  })
}
cost_of <- function(n) sapply(seq_along(act_name), function(a) stage_cost(nodes_of(n), a))

eval_pol <- function(pl, pol, cc, gg = dfac) {
  n <- nrow(cc); pp <- matrix(0, n, n)
  for (a in seq_along(act_name)) {
    ii <- which(pol == a)
    if (length(ii)) pp[ii, ] <- pl[[a]][ii, , drop = FALSE]
  }
  solve(diag(n) - gg * pp, cc[cbind(seq_len(n), pol)])
}
solve_mdp <- function(pl, cc, gg = dfac) {
  n <- nrow(cc); pol <- rep(1L, n)
  for (it in 1:300) {
    vv <- eval_pol(pl, pol, cc, gg)
    qq <- sapply(seq_along(act_name), function(a) cc[, a] + gg * (pl[[a]] %*% vv))
    np <- max.col(-qq, ties.method = "first")
    if (all(np == pol)) return(list(pol = pol, v = vv, iter = it))
    pol <- np
  }
  list(pol = pol, v = eval_pol(pl, pol, cc, gg), iter = NA_integer_)
}
bounds_of <- function(pol, xs) {
  k <- which(diff(pol) != 0)
  if (!length(k)) return(numeric(0))
  round((xs[k] + xs[k + 1]) / 2, 4)
}
hold_line <- function(u) {
  bb <- -(spread_rate - seed_rain)
  yy <- (-bb - sqrt(bb^2 - 4 * spread_rate * (u - seed_rain))) / (2 * spread_rate)
  yy + u
}

round(c(spread_rate = spread_rate, seed_rain = seed_rain, log_sd = log_sd,
        damage_at_full_cover = damage_full, discount_factor = dfac,
        discount_rate_per_cent = 100 * (1 / dfac - 1)), 4)
print(data.frame(action = act_name, area_cap = act_cap,
                 area_cap_per_cent = 100 * act_cap, cost_per_unit_area = act_rate,
                 cost_at_cap = act_rate * act_cap), row.names = FALSE)
round(c(hand_pulling_holds_below = hold_line(act_cap[2]),
        contract_holds_below = hold_line(act_cap[3])), 4)

## ---- reference ----
n_ref <- 801
p_ref <- build_P(n_ref); c_ref <- cost_of(n_ref); x_ref <- nodes_of(n_ref)
ref <- solve_mdp(p_ref, c_ref)
kk <- which(diff(ref$pol) != 0)
print(data.frame(from = act_name[ref$pol[kk]], to = act_name[ref$pol[kk + 1]],
                 at_cover = bounds_of(ref$pol, x_ref)), row.names = FALSE)
round(c(cost_at_0 = ref$v[1], cost_at_0.10 = approx(x_ref, ref$v, 0.10)$y,
        cost_at_0.30 = approx(x_ref, ref$v, 0.30)$y,
        cost_at_0.50 = approx(x_ref, ref$v, 0.50)$y,
        cost_at_1.00 = ref$v[n_ref]), 3)
lo_ref <- x_ref <= 0.30
round(c(discovery_states = sum(lo_ref), mean_cost_over_discovery = mean(ref$v[lo_ref])), 3)

vv <- rep(0, n_ref)
for (it in 1:4000) {
  qq <- sapply(seq_along(act_name), function(a) c_ref[, a] + dfac * (p_ref[[a]] %*% vv))
  nv <- do.call(pmin, split(qq, col(qq)))
  if (max(abs(nv - vv)) < 1e-12) break
  vv <- nv
}
c(value_iterations = it, policy_iterations = ref$iter)
vi_solve_gap <- signif(c(gap_value_iteration_vs_direct_solve = max(abs(vv - ref$v))), 3)
vi_solve_gap

## ---- discount ----
n_w <- 161
p_w <- build_P(n_w); c_w <- cost_of(n_w); x_w <- nodes_of(n_w)
base <- solve_mdp(p_w, c_w, dfac)
lo_w <- x_w <= 0.30
loss_w <- function(pol, ref_v = base$v, gg = dfac) {
  vu <- eval_pol(p_w, pol, c_w, gg)
  c(extra_cost = mean(vu[lo_w]) - mean(ref_v[lo_w]),
    extra_pct = 100 * (mean(vu[lo_w]) - mean(ref_v[lo_w])) / mean(ref_v[lo_w]))
}
g_seq <- seq(0.80, 0.995, length.out = 40)
pol_g <- lapply(g_seq, function(g) solve_mdp(p_w, c_w, g)$pol)
give_up <- sapply(pol_g, function(p) {
  k <- which(p != 1); if (!length(k)) 0 else (x_w[max(k)] + x_w[max(k) + 1]) / 2 })
enter_hc <- sapply(pol_g, function(p) {
  k <- which(p == 3); if (!length(k)) NA_real_ else (x_w[min(k)] + x_w[min(k) - 1]) / 2 })
sel <- c(1, 21, 40)
print(data.frame(discount_factor = round(g_seq[sel], 3),
                 discount_rate_per_cent = round(100 * (1 / g_seq[sel] - 1), 2),
                 hand_to_contract = round(enter_hc[sel], 4),
                 abandon_above = round(give_up[sel], 4)), row.names = FALSE)
round(c(abandon_lowest = min(give_up), abandon_highest = max(give_up),
        abandon_range = diff(range(give_up)),
        entry_range = diff(range(enter_hc, na.rm = TRUE))), 4)
n_diff_90 <- sum(solve_mdp(p_w, c_w, 0.90)$pol != base$pol)
n_diff_99 <- sum(solve_mdp(p_w, c_w, 0.99)$pol != base$pol)
c(grid_states = n_w, discount_factors_swept = length(g_seq),
  differ_from_0.95_at_0.90 = n_diff_90, differ_from_0.95_at_0.99 = n_diff_99)
round(c(per_cent_of_states_differing_at_0.90 = 100 * n_diff_90 / n_w,
        per_cent_of_states_differing_at_0.99 = 100 * n_diff_99 / n_w), 1)
cross <- function(g_used, g_true) {
  pu <- solve_mdp(p_w, c_w, g_used)$pol
  loss_w(pu, solve_mdp(p_w, c_w, g_true)$v, g_true)
}
print(round(rbind("0.90 policy judged at 0.99" = cross(0.90, 0.99),
                  "0.99 policy judged at 0.90" = cross(0.99, 0.90),
                  "0.90 policy judged at 0.95" = cross(0.90, 0.95),
                  "0.99 policy judged at 0.95" = cross(0.99, 0.95)), 3))

## ---- fig-discount ----
act_col <- c("No action" = te_pal$sage, "Hand pulling" = te_pal$gold,
             "Contract control" = te_pal$forest)
gmap <- data.frame(
  dfactor = rep(g_seq, each = n_w),
  cover = rep(x_w, length(g_seq)),
  action = factor(act_name[unlist(pol_g)], levels = act_name))
ggplot(gmap, aes(dfactor, cover, fill = action)) +
  geom_raster() +
  scale_fill_manual(values = act_col, name = NULL) +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  labs(x = "Discount factor per year", y = "Cover of the invasive shrub",
       title = "The discount rate decides when to give up, not when to start") +
  theme_te() +
  theme(legend.position = "top")

## ---- grid ----
grid_set <- c(11, 41, 161, 801)
to_ref <- function(pol, xs) pol[apply(abs(outer(x_ref, xs, "-")), 1, which.min)]
gres <- lapply(grid_set, function(n) {
  pl <- build_P(n); cc <- cost_of(n); ss <- solve_mdp(pl, cc); xs <- nodes_of(n)
  list(n = n, xs = xs, pol = ss$pol, own = ss$v, stay0 = pl[[1]][1, 1],
       true = eval_pol(p_ref, to_ref(ss$pol, xs), c_ref))
})
print(do.call(rbind, lapply(gres, function(z) data.frame(
  states = z$n,
  bottom_bin_edge = round(1 / (2 * (z$n - 1)), 5),
  prob_stay_at_zero = round(z$stay0, 4),
  claimed_cost_at_0.10 = round(approx(z$xs, z$own, 0.10)$y, 3),
  true_cost_at_0.10 = round(approx(x_ref, z$true, 0.10)$y, 3),
  extra_pct = round(100 * (mean(z$true[lo_ref]) - mean(ref$v[lo_ref])) /
                      mean(ref$v[lo_ref]), 3),
  extra_cost = round(mean(z$true[lo_ref]) - mean(ref$v[lo_ref]), 3)))),
  row.names = FALSE)
for (z in gres) cat("states", z$n, "boundaries at cover:",
                    paste(format(bounds_of(z$pol, z$xs), scientific = FALSE),
                          collapse = " "), "\n")

## ---- fig-grid ----
library(grid)
band <- do.call(rbind, lapply(gres, function(z) {
  hh <- 1 / (2 * (z$n - 1))
  data.frame(states = z$n,
             xmin = pmax(z$xs - hh, 0), xmax = pmin(z$xs + hh, 1),
             action = factor(act_name[z$pol], levels = act_name))
}))
band$row <- match(band$states, grid_set)
lab_grid <- paste(grid_set, "states")

p_left <- ggplot(band) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = row - 0.42, ymax = row + 0.42,
                fill = action)) +
  scale_fill_manual(values = act_col, name = NULL) +
  scale_y_continuous(breaks = seq_along(grid_set), labels = lab_grid,
                     trans = "reverse") +
  scale_x_continuous(expand = c(0, 0)) +
  labs(x = "Cover of the invasive shrub", y = NULL,
       title = "A coarse grid invents a permanent eradication") +
  theme_te() +
  theme(legend.position = "top", panel.grid.major.y = element_blank(),
        plot.margin = margin(4, 14, 6, 6))

curve_df <- do.call(rbind, lapply(gres, function(z)
  data.frame(cover = x_ref[lo_ref], cost = z$true[lo_ref],
             grid = paste(z$n, "states"))))
curve_df$grid <- factor(curve_df$grid, levels = lab_grid)

p_right <- ggplot(curve_df, aes(cover, cost, colour = grid)) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$gold, te_pal$green,
                                 te_pal$forest), name = NULL) +
  guides(colour = guide_legend(nrow = 1)) +
  labs(x = "Cover at which the shrub is found",
       y = "True cost, thousand pounds",
       title = "The cost of a coarse grid lands at low cover") +
  theme_te() +
  theme(legend.position = "top", plot.margin = margin(4, 14, 6, 6))

grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 1)))
print(p_left, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p_right, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))

## ---- estimation ----
hist_act <- function(x, u1, u2) {
  a <- if (x > 0.2) 3L else if (x > 0.05) 2L else 1L
  if (u1 < 0.25) a <- 1L + as.integer(u2 * 3)
  a
}
sim_series <- function(n_yr, x0 = 0.12) {
  x <- numeric(n_yr + 1); a <- integer(n_yr); x[1] <- x0
  for (k in 1:n_yr) {
    a[k] <- hist_act(x[k], runif(1), runif(1))
    x[k + 1] <- min(med_map(x[k], a[k]) * exp(log_sd * rnorm(1)), 1)
  }
  list(x = x, a = a)
}
neg_ll <- function(rr, sg, mm, yy, lxn, cen) {
  lz <- log(yy + rr * yy * (1 - yy) + mm * (1 - yy))
  ll <- numeric(length(lz))
  ll[!cen] <- dnorm(lxn[!cen], lz[!cen], sg, log = TRUE)
  ll[cen] <- pnorm(lz[cen] / sg, log.p = TRUE)
  -sum(ll)
}
prep <- function(sr) {
  x <- head(sr$x, -1); xn <- sr$x[-1]
  list(y = x - pmin(act_cap[sr$a], x), lxn = log(pmax(xn, 1e-12)),
       cen = xn >= 1 - 1e-12)
}
fit_two <- function(sr) {
  dd <- prep(sr)
  o <- optim(c(log(0.7), log(0.25)), function(p)
    neg_ll(exp(p[1]), exp(p[2]), seed_rain, dd$y, dd$lxn, dd$cen))
  c(r = exp(o$par[1]), s = exp(o$par[2]), m = seed_rain)
}
fit_three <- function(sr) {
  dd <- prep(sr)
  o <- optim(c(log(0.7), log(0.25), log(0.004)), function(p)
    neg_ll(exp(p[1]), exp(p[2]), exp(p[3]), dd$y, dd$lxn, dd$cen))
  c(r = exp(o$par[1]), s = exp(o$par[2]), m = exp(o$par[3]))
}
bin_of <- function(v, n) {
  xs <- nodes_of(n)
  as.integer(cut(v, c(-Inf, xs[-1] - 1 / (2 * (n - 1)), Inf), labels = FALSE))
}
emp_P <- function(sr, n) {
  ii <- bin_of(head(sr$x, -1), n); jj <- bin_of(sr$x[-1], n)
  lapply(seq_along(act_name), function(a) {
    mm <- matrix(1 / n, n, n)
    for (k in which(sr$a == a)) mm[ii[k], jj[k]] <- mm[ii[k], jj[k]] + 1
    mm / rowSums(mm)
  })
}
set.seed(20260724)
n_rep <- 120; len_set <- c(20, 50, 200); rows <- list()
for (n_yr in len_set) for (rp in 1:n_rep) {
  sr <- sim_series(n_yr)
  f2 <- fit_two(sr); f3 <- fit_three(sr)
  l2 <- loss_w(solve_mdp(build_P(n_w, f2["r"], f2["s"], f2["m"]), c_w)$pol)
  l3 <- loss_w(solve_mdp(build_P(n_w, f3["r"], f3["s"], f3["m"]), c_w)$pol)
  lc <- loss_w(solve_mdp(emp_P(sr, n_w), c_w)$pol)
  rows[[length(rows) + 1]] <- data.frame(years = n_yr,
    r2 = f2["r"], r3 = f3["r"], m3 = f3["m"],
    two = l2["extra_pct"], three = l3["extra_pct"], counts = lc["extra_pct"],
    counts_cost = lc["extra_cost"],
    cells = length(unique(paste(bin_of(head(sr$x, -1), n_w), sr$a))))
}
est <- do.call(rbind, rows)
c(replicates = n_rep, rows_in_the_matrix = n_w * length(act_name))
print(round(aggregate(cbind(r2, r3, m3, cells) ~ years, est, median), 4), row.names = FALSE)
print(round(aggregate(cbind(two, three, counts) ~ years, est, median), 3), row.names = FALSE)
print(round(aggregate(cbind(two, three, counts) ~ years, est,
                      function(z) quantile(z, 0.9)), 3), row.names = FALSE)
print(round(aggregate(counts_cost ~ years, est, median), 3), row.names = FALSE)
e20 <- est[est$years == 20, ]
round(c(share_three_above_5pct_at_20y = mean(e20$three > 5),
        share_two_above_5pct_at_20y = mean(e20$two > 5),
        spearman_seed_rain_vs_loss = cor(e20$m3, e20$three, method = "spearman"),
        seed_rain_q90_at_20y = unname(quantile(e20$m3, 0.9))), 4)
round(loss_w(solve_mdp(build_P(n_w, mm = 0.07), c_w)$pol), 3)

## ---- fig-estimator ----
est_lab <- c("Two parameters", "Three parameters", "Transition counts")
long <- rbind(
  data.frame(years = est$years, loss = est$two, estimator = est_lab[1]),
  data.frame(years = est$years, loss = est$three, estimator = est_lab[2]),
  data.frame(years = est$years, loss = est$counts, estimator = est_lab[3]))
long$estimator <- factor(long$estimator, levels = est_lab)
long$years <- factor(long$years, levels = len_set, labels = paste(len_set, "years"))
long$loss <- pmax(long$loss, 0.01)

ggplot(long, aes(years, loss, fill = estimator)) +
  geom_boxplot(colour = te_pal$ink, linewidth = 0.35, outlier.size = 0.7,
               alpha = 0.75) +
  scale_fill_manual(values = c(te_pal$forest, te_pal$gold, te_pal$clay), name = NULL) +
  scale_y_log10(breaks = c(0.01, 0.1, 1, 10, 100, 1000),
                labels = c("0.01", "0.1", "1", "10", "100", "1000")) +
  labs(x = "Length of the management record", y = "Extra cost, per cent",
       title = "One extra parameter is what makes short records dangerous") +
  theme_te() +
  theme(legend.position = "top")

## ---- horizon ----
n_hz <- 40
v_t <- rep(0, n_w); pol_t <- matrix(0L, n_w, n_hz); v_hz <- matrix(0, n_w, n_hz)
for (k in 1:n_hz) {
  qq <- sapply(seq_along(act_name), function(a) c_w[, a] + dfac * (p_w[[a]] %*% v_t))
  pol_t[, k] <- max.col(-qq, ties.method = "first")
  v_t <- qq[cbind(seq_len(n_w), pol_t[, k])]
  v_hz[, k] <- v_t
}
diff_k <- apply(pol_t, 2, function(p) sum(p != base$pol))
gu_t <- apply(pol_t, 2, function(p) {
  k <- which(p != 1); if (!length(k)) 0 else (x_w[max(k)] + x_w[max(k) + 1]) / 2 })
kshow <- c(1, 2, 5, 10, 20, 30, 40)
print(data.frame(years_left = kshow, states_differing = diff_k[kshow],
                 abandon_above = round(gu_t[kshow], 4)), row.names = FALSE)
round(c(stationary_abandon_above = (x_w[max(which(base$pol != 1))] +
          x_w[max(which(base$pol != 1)) + 1]) / 2,
        horizon_40_cost = mean(v_hz[lo_w, n_hz]),
        infinite_cost = mean(base$v[lo_w]),
        understated_pct = 100 * (mean(base$v[lo_w]) - mean(v_hz[lo_w, n_hz])) /
          mean(base$v[lo_w])), 3)
fin_val <- function(pol_fixed, tp) {
  vv <- rep(0, n_w)
  for (k in 1:tp) {
    pp <- matrix(0, n_w, n_w)
    for (a in seq_along(act_name)) {
      ii <- which(pol_fixed == a)
      if (length(ii)) pp[ii, ] <- p_w[[a]][ii, , drop = FALSE]
    }
    vv <- c_w[cbind(seq_len(n_w), pol_fixed)] + dfac * (pp %*% vv)
  }
  as.vector(vv)
}
print(do.call(rbind, lapply(c(5, 10, 20, 40), function(tp) {
  vs <- fin_val(base$pol, tp)
  data.frame(plan_years = tp,
             plan_used_for_ever_pct = round(loss_w(pol_t[, tp])["extra_pct"], 3),
             stationary_used_for_plan_pct = round(100 * (mean(vs[lo_w]) -
               mean(v_hz[lo_w, tp])) / mean(v_hz[lo_w, tp]), 3))
})), row.names = FALSE)
v_t2 <- base$v; n_diff2 <- 0L
for (k in 1:n_hz) {
  qq <- sapply(seq_along(act_name), function(a) c_w[, a] + dfac * (p_w[[a]] %*% v_t2))
  pk <- max.col(-qq, ties.method = "first")
  n_diff2 <- n_diff2 + sum(pk != base$pol)
  v_t2 <- qq[cbind(seq_len(n_w), pk)]
}
c(states_differing_with_stationary_terminal_value = n_diff2,
  state_steps_checked = n_w * n_hz)

## ---- fig-horizon ----
hz_map <- data.frame(
  years_left = rep(seq_len(n_hz), each = n_w),
  cover = rep(x_w, n_hz),
  action = factor(act_name[as.vector(pol_t)], levels = act_name))
st_bounds <- bounds_of(base$pol, x_w)
ggplot(hz_map, aes(years_left, cover, fill = action)) +
  geom_raster() +
  geom_hline(yintercept = st_bounds[2:4], colour = te_pal$ink,
             linetype = "22", linewidth = 0.5) +
  scale_fill_manual(values = act_col, name = NULL) +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  labs(x = "Years remaining in the plan", y = "Cover of the invasive shrub",
       title = "A finite horizon changes the rule decades before the end",
       subtitle = paste("Dashed lines: the upper three action boundaries of the same rule",
                        "solved with no end to the horizon")) +
  theme_te() +
  theme(legend.position = "top",
        plot.subtitle = element_text(size = 9.5, colour = "#2c3a31"))

## ---- observation ----
set.seed(20260724)
n_sim <- 4000; n_yr_sim <- 120
start_pool <- x_ref[lo_ref]
pol_fun <- function(xo) ref$pol[pmax(1L, pmin(n_ref, round(xo * (n_ref - 1)) + 1L))]
run_sim <- function(obs_sd, miss_p, x0) {
  x <- x0; tot <- rep(0, n_sim)
  for (k in 1:n_yr_sim) {
    xo <- if (obs_sd > 0) pmin(x * exp(obs_sd * z_obs[, k]), 1) else x
    if (miss_p > 0) xo[x < 0.05 & u_miss[, k] < miss_p] <- 0
    a <- pol_fun(xo)
    tot <- tot + dfac^(k - 1) * stage_cost(x, a)
    x <- pmin(med_map(x, a) * exp(log_sd * z_proc[, k]), 1)
  }
  mean(tot)
}
x0_pool <- sample(start_pool, n_sim, replace = TRUE)
set.seed(20260724)
z_proc <- matrix(rnorm(n_sim * n_yr_sim), n_sim)
z_obs  <- matrix(rnorm(n_sim * n_yr_sim), n_sim)
u_miss <- matrix(runif(n_sim * n_yr_sim), n_sim)
s_perfect <- run_sim(0, 0, x0_pool)
s_noisy   <- run_sim(0.30, 0, x0_pool)
s_missed  <- run_sim(0.30, 0.30, x0_pool)
c(replicates = n_sim, years_simulated = n_yr_sim)
round(c(observation_log_sd = 0.30, non_detection_below_0.05 = 0.30,
        analytic_cost = mean(ref$v[lo_ref]), simulated_cost = s_perfect,
        calibration_gap_pct = 100 * (s_perfect - mean(ref$v[lo_ref])) /
          mean(ref$v[lo_ref])), 3)
round(c(perfect = s_perfect, noisy = s_noisy, noisy_and_missed = s_missed,
        noisy_pct = 100 * (s_noisy - s_perfect) / s_perfect,
        missed_pct = 100 * (s_missed - s_perfect) / s_perfect), 3)
