## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 6.5, fig.height = 4)

## ----setup--------------------------------------------------------------------
library(AMRvalid)

## ----palette, include = FALSE-------------------------------------------------
# Colourblind-safe pair used in all figures:
# orange = naive estimate, blue = population-aware estimate
col_naive <- "#eb6834"
col_aware <- "#2a78d6"
ink_muted <- "#6b6b6b"
grid_col <- "#e6e6e3"

## ----simulate-----------------------------------------------------------------
sim <- amr_simulate(n_lineages = 30, isolates_per_lineage = 15,
                    external_lineages = 30, seed = 2026)
x <- amr_import_predictions(sim$predictions)
x

## ----splits-------------------------------------------------------------------
checks <- amr_validate_splits(x, train_manifest = sim$train_manifest, group = "lineage")
checks$consistent_designs

## ----claim--------------------------------------------------------------------
random_only <- x[x$model_id == "knn/random" & x$dataset_id == "internal", ]
amr_validate_splits(random_only, train_manifest = sim$train_manifest,
                    group = "lineage", claimed_design = "group")

## ----optimism-----------------------------------------------------------------
e <- suppressMessages(amr_evaluate(x, validate = FALSE))
auc <- as.data.frame(e)[e$metric == "roc_auc", c("model_id", "dataset_id", "estimate")]
auc_wide <- reshape(auc, idvar = "model_id", timevar = "dataset_id", direction = "wide")
names(auc_wide) <- c("model", "external", "internal")
auc_wide$optimism <- auc_wide$internal - auc_wide$external
auc_wide[, c("model", "internal", "external", "optimism")]

## ----optimism-plot, echo = FALSE----------------------------------------------
m <- t(as.matrix(auc_wide[, c("internal", "external")]))
colnames(m) <- auc_wide$model
barplot(m, beside = TRUE, ylim = c(0, 1.15), ylab = "ROC-AUC", yaxt = "n",
        legend.text = c("internal test set", "external unseen lineages"),
        args.legend = list(x = "top", bty = "n", cex = 0.8, horiz = TRUE),
        col = c(col_naive, col_aware), border = NA, las = 1, cex.names = 0.8)
axis(2, at = seq(0, 1, 0.2), las = 1, lwd = 0)
abline(h = 0.5, lty = 2, col = ink_muted)

## ----distance-----------------------------------------------------------------
knn_random <- x[x$model_id == "knn/random", ]
knn_random$dataset_id <- "all test isolates"
# Isolates within a lineage are less than about 20 units apart in this simulation
d <- amr_distance_eval(knn_random, distances = sim$distances,
                       train_manifest = sim$train_manifest, bands = c(0, 20, 100, Inf))
table(d$nearest$band)
d$trend[, c("model_id", "model", "effect", "lower", "upper", "n")]

## ----distance-plot, echo = FALSE----------------------------------------------
bb <- d$by_band[d$by_band$metric == "roc_auc", ]
plot(seq_len(nrow(bb)), bb$estimate, ylim = c(0, 1), xlim = c(0.6, nrow(bb) + 0.4), xaxt = "n",
     type = "n", xlab = "Distance to nearest training isolate", ylab = "ROC-AUC", las = 1, bty = "n")
abline(h = seq(0, 1, 0.2), col = grid_col)
lines(seq_len(nrow(bb)), bb$estimate, col = col_aware, lwd = 2)
arrows(seq_len(nrow(bb)), bb$lower, seq_len(nrow(bb)), bb$upper, angle = 90, code = 3, length = 0.05,
       col = col_aware, lwd = 2)
points(seq_len(nrow(bb)), bb$estimate, pch = 21, bg = col_aware, col = "white", cex = 1.8, lwd = 2)
axis(1, at = seq_len(nrow(bb)), cex.axis = 0.8,
     labels = c("same lineage\n(< 20)", "nearby lineage\n(20-100)", "distant\n(> 100)")[seq_len(nrow(bb))],
     padj = 0.5, lwd = 0)
abline(h = 0.5, lty = 2, col = ink_muted)

## ----bootstrap----------------------------------------------------------------
ext <- x[x$model_id == "marker/lineage" & x$dataset_id == "external", ]
by_isolate <- as.data.frame(amr_bootstrap(ext, resample_by = "isolate_id", B = 300, seed = 1))
by_lineage <- as.data.frame(amr_bootstrap(ext, resample_by = "lineage", B = 300, seed = 1))
ci <- rbind(
  isolate = unlist(by_isolate[by_isolate$metric == "roc_auc", c("estimate", "lower", "upper")]),
  lineage = unlist(by_lineage[by_lineage$metric == "roc_auc", c("estimate", "lower", "upper")])
)
cbind(ci, width = ci[, "upper"] - ci[, "lower"])

