# Model discrepancy in simulator calibration
# https://tidyecology.com/posts/model-discrepancy-in-simulator-calibration/
#
# 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)
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))
}

## ---- design ----
theta_true <- 1.2
sat_k      <- 10
sd_obs     <- 0.05
x_lo       <- 0.1
x_hi       <- 4
n_set      <- c(10, 30, 90, 270)
amp_fix    <- 1
len_fix    <- 1.5
z_95       <- qnorm(0.975)

bound_log       <- 6
x_in            <- 2.05
x_out           <- 6
n_rep_ml        <- c(`10` = 200, `30` = 200, `90` = 200, `270` = 60)
n_rep_bayes     <- 100
amp_prior_sd    <- 1
len_prior_med   <- 1.5
len_prior_sdlog <- 0.75

eta_fun <- function(x, a0 = 0) a0 + theta_true * x / (1 + x / sat_k)
x_design <- function(n) seq(x_lo, x_hi, length.out = n)

k_se <- function(a, b, amp, len) {
  amp^2 * exp(-outer(a, b, "-")^2 / (2 * len^2))
}
k_con <- function(a, b, amp, len) {
  ga <- exp(-a^2 / (2 * len^2))
  gb <- exp(-b^2 / (2 * len^2))
  k_se(a, b, amp, len) - amp^2 * (outer(ga, gb) + outer(ga * a, gb * b) / len^2)
}
k_none <- function(a, b, amp, len) matrix(0, length(a), length(b))
k_pick <- function(kind) switch(kind, none = k_none, gp = k_se, con = k_con)

cov_obs <- function(kind, x, amp, len) {
  k_pick(kind)(x, x, amp, len) + diag(sd_obs^2, length(x))
}

## ---- one-dataset ----
set.seed(4102)
n_demo  <- 30
x_demo  <- x_design(n_demo)
y_demo  <- eta_fun(x_demo) + rnorm(n_demo, 0, sd_obs)
ls_demo <- sum(x_demo * y_demo) / sum(x_demo^2)
gap_4   <- theta_true * x_hi - eta_fun(x_hi)
gap_pct <- 100 * gap_4 / eta_fun(x_hi)
proj_theta <- integrate(function(x) x * eta_fun(x), x_lo, x_hi)$value /
  integrate(function(x) x^2, x_lo, x_hi)$value

## ---- fig-setting ----
x_line <- seq(0, 6, length.out = 200)
curve_df <- rbind(
  data.frame(x = x_line, y = eta_fun(x_line), what = "truth, saturating"),
  data.frame(x = x_line, y = ls_demo * x_line, what = "simulator, least squares"),
  data.frame(x = x_line, y = theta_true * x_line, what = "simulator, true attack rate"))
ggplot(curve_df, aes(x, y, colour = what, linetype = what)) +
  annotate("rect", xmin = x_hi, xmax = 6, ymin = -Inf, ymax = Inf,
           fill = te_line, alpha = 0.45) +
  geom_line(linewidth = 0.9) +
  geom_point(data = data.frame(x = x_demo, y = y_demo), aes(x, y),
             inherit.aes = FALSE, colour = te_ink, size = 1.6) +
  scale_colour_manual(values = c(te_gold, te_rust, te_forest), name = NULL) +
  scale_linetype_manual(values = c("solid", "dashed", "solid"), name = NULL) +
  labs(x = "prey density", y = "intake rate",
       title = "A straight line against a gentle bend",
       subtitle = "shaded: beyond the trial densities, where the simulator will be used") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- closed-form ----
linear_arm <- function(kind, n, amp = amp_fix, len = len_fix, a0 = 0,
                       target = theta_true) {
  x  <- x_design(n)
  kx <- solve(cov_obs(kind, x, amp, len), x)
  v  <- 1 / sum(x * kx)
  w  <- v * kx
  m  <- sum(w * eta_fun(x, a0))
  sd_w <- sd_obs * sqrt(sum(w^2))
  se <- sqrt(v)
  data.frame(n = n, arm = kind, mean = m, se = se, sd_true = sd_w,
             cover = pnorm((target - m + z_95 * se) / sd_w) -
                     pnorm((target - m - z_95 * se) / sd_w),
             sum_w = sum(w))
}
cf_tab <- do.call(rbind, lapply(n_set, function(n)
  do.call(rbind, lapply(c("none", "gp", "con"), linear_arm, n = n))))
cf_get <- function(arm, n, col) cf_tab[cf_tab$arm == arm & cf_tab$n == n, col]

n_check <- 400
set.seed(733)
x_chk  <- x_design(30)
ch_chk <- lapply(c(gp = "gp", con = "con"),
                 function(kind) chol(cov_obs(kind, x_chk, amp_fix, len_fix)))
gls_chol <- function(ch, x, y) {
  xs <- backsolve(ch, x, transpose = TRUE)
  ys <- backsolve(ch, y, transpose = TRUE)
  v  <- 1 / sum(xs^2)
  c(est = v * sum(xs * ys), se = sqrt(v))
}
chk <- replicate(n_check, {
  y <- eta_fun(x_chk) + rnorm(30, 0, sd_obs)
  sapply(ch_chk, function(ch) {
    g <- gls_chol(ch, x_chk, y)
    c(g, hit = abs(g[["est"]] - theta_true) < z_95 * g[["se"]])
  })
})
chk_cover <- apply(chk["hit", , ], 1, mean)
chk_mean  <- apply(chk["est", , ], 1, mean)
chk_mcse  <- sqrt(chk_cover * (1 - chk_cover) / n_check)
knitr::kable(cf_tab[, c("n", "arm", "mean", "se", "cover")], digits = 3,
             row.names = FALSE)

## ---- fig-closed ----
arm_lab <- c(none = "no discrepancy", gp = "GP discrepancy",
             con = "GP, zero value and slope at zero density")
cf_plot <- cf_tab
cf_plot$arm_name <- factor(arm_lab[cf_plot$arm], levels = arm_lab)
ggplot(cf_plot, aes(factor(n), mean, colour = arm_name)) +
  geom_hline(yintercept = theta_true, linetype = "dashed", colour = te_ink) +
  geom_errorbar(aes(ymin = mean - z_95 * se, ymax = mean + z_95 * se),
                width = 0.25, linewidth = 0.8,
                position = position_dodge(width = 0.6)) +
  geom_point(size = 2.4, position = position_dodge(width = 0.6)) +
  scale_colour_manual(values = c(te_rust, te_gold, te_forest), name = NULL) +
  labs(x = "feeding trials (n)", y = "attack rate",
       title = "Fixed hyperparameters: honest, but only one arm learns",
       subtitle = "dashed: the true attack rate") +
  guides(colour = guide_legend(nrow = 2)) +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- estimated ----
starts_log <- list(c(log(0.5), log(1)), c(log(5), log(5)),
                   c(log(0.05), log(0.3)), c(log(2), log(10)))

fit_hyper <- function(kind, x, y) {
  sq_dist <- outer(x, x, "-")^2
  x_prod  <- outer(x, x)
  nll <- function(p) {
    if (any(abs(p) > bound_log)) return(1e10)
    amp <- exp(p[1])
    len <- exp(p[2])
    kmat <- exp(-sq_dist / (2 * len^2))
    if (kind == "con") {
      g <- exp(-x^2 / (2 * len^2))
      kmat <- kmat - outer(g, g) * (1 + x_prod / len^2)
    }
    ch <- tryCatch(chol(amp^2 * kmat + diag(sd_obs^2, length(x))),
                   error = function(e) NULL)
    if (is.null(ch)) return(1e10)
    xs <- backsolve(ch, x, transpose = TRUE)
    ys <- backsolve(ch, y, transpose = TRUE)
    r  <- ys - xs * sum(xs * ys) / sum(xs^2)
    0.5 * sum(r^2) + sum(log(diag(ch)))
  }
  fits <- lapply(starts_log, function(s)
    optim(s, nll, control = list(maxit = 200, reltol = 1e-6)))
  vals <- vapply(fits, function(o) o$value, numeric(1))
  opt  <- fits[[which.min(vals)]]
  c(amp = exp(opt$par[1]), len = exp(opt$par[2]),
    at_bound = any(abs(opt$par) > bound_log - 0.05),
    first_worse = vals[1] - min(vals) > 0.01)
}

predict_arm <- function(kind, x, y, amp, len, a0 = 0) {
  kfun <- k_pick(kind)
  ch <- chol(cov_obs(kind, x, amp, len))
  solve_k <- function(b) backsolve(ch, backsolve(ch, b, transpose = TRUE))
  kx  <- solve_k(x)
  v   <- 1 / sum(x * kx)
  est <- v * sum(kx * y)
  x_new <- c(x_in, x_out)
  ks  <- kfun(x_new, x, amp, len)
  p_mean <- drop(x_new * est + ks %*% solve_k(y - x * est))
  p_var  <- diag(kfun(x_new, x_new, amp, len)) -
    rowSums(ks * t(solve_k(t(ks)))) + drop(x_new - ks %*% kx)^2 * v
  p_sd <- sqrt(pmax(p_var, 0))
  hit  <- abs(p_mean - eta_fun(x_new, a0)) < z_95 * p_sd
  c(est = est, se = sqrt(v), hit_in = hit[1], hit_out = hit[2],
    psd_in = p_sd[1], psd_out = p_sd[2])
}

set.seed(9150)
ml_rows <- list()
for (n in n_set) {
  x  <- x_design(n)
  mu <- eta_fun(x)
  for (i in seq_len(n_rep_ml[[as.character(n)]])) {
    y <- mu + rnorm(n, 0, sd_obs)
    for (kind in c("gp", "con")) {
      hp <- fit_hyper(kind, x, y)
      ml_rows[[length(ml_rows) + 1]] <- data.frame(
        n = n, arm = kind, fit = "estimated", t(hp),
        t(predict_arm(kind, x, y, hp[["amp"]], hp[["len"]])))
      ml_rows[[length(ml_rows) + 1]] <- data.frame(
        n = n, arm = kind, fit = "fixed", amp = amp_fix, len = len_fix,
        at_bound = 0, first_worse = 0,
        t(predict_arm(kind, x, y, amp_fix, len_fix)))
    }
  }
}
ml_all <- do.call(rbind, ml_rows)
ml_all$hit <- abs(ml_all$est - theta_true) < z_95 * ml_all$se

ml_sum <- do.call(rbind, lapply(split(ml_all, list(ml_all$n, ml_all$arm, ml_all$fit)),
  function(d) data.frame(n = d$n[1], arm = d$arm[1], fit = d$fit[1],
                         reps = nrow(d), mean = mean(d$est), se = mean(d$se),
                         cover = mean(d$hit),
                         mcse = sqrt(mean(d$hit) * (1 - mean(d$hit)) / nrow(d)),
                         amp = median(d$amp), len = median(d$len),
                         at_bound = mean(d$at_bound),
                         first_worse = mean(d$first_worse),
                         cover_in = mean(d$hit_in), cover_out = mean(d$hit_out),
                         psd_in = mean(d$psd_in), psd_out = mean(d$psd_out))))
ml_sum <- ml_sum[order(ml_sum$fit, ml_sum$arm, ml_sum$n), ]
ml_get <- function(arm, fit, n, col) {
  ml_sum[ml_sum$arm == arm & ml_sum$fit == fit & ml_sum$n == n, col]
}
knitr::kable(ml_sum[ml_sum$fit == "estimated",
                    c("n", "arm", "reps", "mean", "se", "cover", "amp", "len", "at_bound",
                      "first_worse")],
             digits = 3, row.names = FALSE)

## ---- fig-estimated ----
est_long <- rbind(
  data.frame(ml_sum[, c("n", "arm", "fit")], metric = "coverage of the true rate",
             value = ml_sum$cover, lo = pmax(ml_sum$cover - 2 * ml_sum$mcse, 0),
             hi = pmin(ml_sum$cover + 2 * ml_sum$mcse, 1)),
  data.frame(ml_sum[, c("n", "arm", "fit")], metric = "mean standard error",
             value = ml_sum$se, lo = NA, hi = NA))
est_long$arm_name <- factor(ifelse(est_long$arm == "gp", "GP discrepancy",
                                   "GP, zero value and slope at zero"),
                            levels = c("GP discrepancy", "GP, zero value and slope at zero"))
est_long$fit <- factor(est_long$fit, levels = c("fixed", "estimated"),
                       labels = c("amplitude 1, length 1.5 fixed", "estimated by maximum likelihood"))
ref_df <- data.frame(metric = "coverage of the true rate", value = 0.95)
ggplot(est_long, aes(n, value, colour = fit)) +
  geom_hline(data = ref_df, aes(yintercept = value), linetype = "dashed",
             colour = te_ink) +
  geom_line(linewidth = 0.8) +
  geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.08, linewidth = 0.5,
                na.rm = TRUE) +
  geom_point(size = 2.3) +
  facet_grid(metric ~ arm_name, scales = "free_y", switch = "y") +
  scale_x_log10(breaks = n_set) +
  expand_limits(y = 0) +
  scale_colour_manual(values = c(te_forest, te_rust), name = NULL) +
  labs(x = "feeding trials (n)", y = NULL,
       title = "Learning the discrepancy from the same data",
       subtitle = "bars: two Monte Carlo standard errors; dashed: 0.95") +
  theme_datasheet() +
  theme(legend.position = "bottom", strip.placement = "outside")

## ---- bayes-grid ----
la_grid <- seq(log(0.02), log(5), length.out = 18)
ll_grid <- seq(log(0.2), log(12), length.out = 18)
hyper_grid <- expand.grid(la = la_grid, ll = ll_grid)
log_prior <- -exp(2 * hyper_grid$la) / (2 * amp_prior_sd^2) + hyper_grid$la +
  dnorm(hyper_grid$ll, log(len_prior_med), len_prior_sdlog, log = TRUE)

bayes_rows <- list()
set.seed(6628)
for (n in c(30, 90)) {
  x  <- x_design(n)
  mu <- eta_fun(x)
  chols <- lapply(c(gp = "gp", con = "con"), function(kind)
    lapply(seq_len(nrow(hyper_grid)), function(j)
      chol(cov_obs(kind, x, exp(hyper_grid$la[j]), exp(hyper_grid$ll[j])))))
  for (i in seq_len(n_rep_bayes)) {
    y <- mu + rnorm(n, 0, sd_obs)
    for (kind in c("gp", "con")) {
      grid_fit <- t(vapply(chols[[kind]], function(ch) {
        xs <- backsolve(ch, x, transpose = TRUE)
        ys <- backsolve(ch, y, transpose = TRUE)
        v  <- 1 / sum(xs^2)
        est <- v * sum(xs * ys)
        r  <- ys - xs * est
        c(ll = -0.5 * sum(r^2) - sum(log(diag(ch))) + 0.5 * log(v),
          est = est, se = sqrt(v))
      }, numeric(3)))
      lw <- grid_fit[, "ll"] + log_prior
      wt <- exp(lw - max(lw))
      wt <- wt / sum(wt)
      post_cdf <- function(th) sum(wt * pnorm(th, grid_fit[, "est"], grid_fit[, "se"]))
      lo <- uniroot(function(th) post_cdf(th) - 0.025, c(-5, 5))$root
      hi <- uniroot(function(th) post_cdf(th) - 0.975, c(-5, 5))$root
      bayes_rows[[length(bayes_rows) + 1]] <- data.frame(
        n = n, arm = kind, mean = sum(wt * grid_fit[, "est"]), lo = lo, hi = hi,
        amp_post = sum(wt * exp(hyper_grid$la)))
    }
  }
}
bayes_all <- do.call(rbind, bayes_rows)
bayes_all$hit <- bayes_all$lo < theta_true & bayes_all$hi > theta_true
bayes_sum <- do.call(rbind, lapply(split(bayes_all, list(bayes_all$n, bayes_all$arm)),
  function(d) data.frame(n = d$n[1], arm = d$arm[1], mean = mean(d$mean),
                         width = mean(d$hi - d$lo), cover = mean(d$hit),
                         mcse = sqrt(mean(d$hit) * (1 - mean(d$hit)) / nrow(d)),
                         amp_post = mean(d$amp_post))))
by_get <- function(arm, n, col) bayes_sum[bayes_sum$arm == arm & bayes_sum$n == n, col]
knitr::kable(bayes_sum, digits = 3, row.names = FALSE)

## ---- near-true ----
a0_small <- 0.05
q_n  <- 400
q_x  <- x_lo + (seq_len(q_n) - 0.5) * (x_hi - x_lo) / q_n
q_wx <- rep((x_hi - x_lo) / q_n, q_n) * q_x
k_orth <- function(a, b, amp, len) {
  ka <- k_se(a, q_x, amp, len) %*% q_wx
  kb <- k_se(b, q_x, amp, len) %*% q_wx
  k_se(a, b, amp, len) - ka %*% t(kb) / drop(t(q_wx) %*% k_se(q_x, q_x, amp, len) %*% q_wx)
}
k_pick <- function(kind) switch(kind, none = k_none, gp = k_se, con = k_con,
                                orth = k_orth)
near_tab <- do.call(rbind, lapply(n_set, function(n) rbind(
  cbind(linear_arm("con", n, a0 = a0_small), case = "constrained, small intercept"),
  cbind(linear_arm("gp", n, a0 = a0_small), case = "unconstrained, small intercept"),
  cbind(linear_arm("orth", n), case = "orthogonal, true rate"),
  cbind(linear_arm("orth", n, target = proj_theta), case = "orthogonal, projection"))))
nr_get <- function(case, n, col) near_tab[near_tab$case == case & near_tab$n == n, col]
knitr::kable(near_tab[, c("n", "case", "mean", "se", "cover", "sum_w")], digits = 3,
             row.names = FALSE)

## ---- fig-near ----
near_plot <- rbind(
  cbind(cf_tab[cf_tab$arm == "con", c("n", "mean", "se")],
        case = "constraint exactly true"),
  near_tab[near_tab$case == "constrained, small intercept", c("n", "mean", "se", "case")],
  near_tab[near_tab$case == "orthogonal, projection", c("n", "mean", "se", "case")])
near_plot$case <- factor(near_plot$case,
  levels = c("constraint exactly true", "constrained, small intercept", "orthogonal, projection"),
  labels = c("constrained, truth passes through zero", "constrained, truth has intercept 0.05",
             "orthogonal discrepancy"))
ggplot(near_plot, aes(factor(n), mean, colour = case)) +
  geom_hline(yintercept = theta_true, linetype = "dashed", colour = te_ink) +
  geom_hline(yintercept = proj_theta, linetype = "dotted", colour = te_ink) +
  geom_errorbar(aes(ymin = mean - z_95 * se, ymax = mean + z_95 * se),
                width = 0.25, linewidth = 0.8,
                position = position_dodge(width = 0.6)) +
  geom_point(size = 2.4, position = position_dodge(width = 0.6)) +
  scale_colour_manual(values = c(te_forest, te_rust, te_gold), name = NULL) +
  labs(x = "feeding trials (n)", y = "attack rate",
       title = "The constraint is information, and it can be wrong",
       subtitle = "dashed: true rate; dotted: least-squares projection of the truth") +
  guides(colour = guide_legend(nrow = 2)) +
  theme_datasheet() +
  theme(legend.position = "bottom")
