# Detection from a single drone flight
# https://tidyecology.com/posts/detection-from-a-single-flight/
#
# 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-11-16

## ---- 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))
}

## ---- design ----
a_true  <- log(2.5)
b_true  <- 0.6
c_true  <- 0.3
b2_true <- 0.5
d_grid  <- c(-0.4, -1.0, -1.8)
n_grid  <- c(200, 2000)
rep_small <- 400
rep_big   <- 150
rep_two   <- 150
rep_rho   <- 400
rho_grid  <- c(0, 0.5, 0.8, 0.95)
mc_se_small <- sqrt(0.25 / rep_small)
mc_se_big   <- sqrt(0.25 / rep_big)
set.seed(4001)
p_bar <- mean(plogis(c_true + d_grid[2] * rnorm(2e5)))

## ---- marginal ----
set.seed(5501)
n_check <- 2e5
lam_chk <- 2.5
p_chk   <- 0.4
n_lat   <- rpois(n_check, lam_chk)
y_chk   <- rbinom(n_check, n_lat, p_chk)
tab_obs <- tabulate(y_chk + 1L, nbins = 12) / n_check
tab_exp <- dpois(0:11, lam_chk * p_chk)
gap_marg <- max(abs(tab_obs - tab_exp))
se_marg  <- max(sqrt(tab_exp * (1 - tab_exp) / n_check))
gap_in_se <- gap_marg / se_marg

## ---- curvature ----
x_quad <- seq(-6, 6, length.out = 4001)
w_quad <- dnorm(x_quad) / sum(dnorm(x_quad))

decomp <- function(d_det) {
  g_fun <- log(plogis(c_true + d_det * x_quad))
  g0 <- sum(w_quad * g_fun)
  g1 <- sum(w_quad * g_fun * x_quad)
  r_fun <- g_fun - g0 - g1 * x_quad
  list(g = g_fun, g0 = g0, g1 = g1, r = r_fun,
       amp = sqrt(sum(w_quad * r_fun^2)))
}
dec_all  <- lapply(d_grid, decomp)
curv_amp <- vapply(dec_all, function(z) z$amp, 0)
lin_slope <- vapply(dec_all, function(z) z$g1, 0)

mu_bar   <- exp(a_true + b_true^2 / 2) * p_bar
coef_se  <- 1 / sqrt(n_grid * mu_bar)
lever    <- outer(curv_amp, coef_se, "/")
dimnames(lever) <- list(sprintf("%.1f", d_grid), sprintf("%d", n_grid))

## ---- fig-curvature ----
x_show <- seq(-3, 3, length.out = 241)
curve_df <- do.call(rbind, lapply(seq_along(d_grid), function(j) {
  g_fun <- log(plogis(c_true + d_grid[j] * x_show))
  data.frame(x2 = x_show, g = g_fun,
             lin = dec_all[[j]]$g0 + dec_all[[j]]$g1 * x_show,
             slope = factor(sprintf("%.1f", d_grid[j]),
                            levels = sprintf("%.1f", d_grid)))
}))
curve_df$resid <- curve_df$g - curve_df$lin
pal_d <- c(te_gold, te_forest, te_rust)

p_left <- ggplot(curve_df, aes(x2, g, colour = slope)) +
  geom_line(aes(y = lin), linetype = "dashed", linewidth = 0.5,
            show.legend = FALSE) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = pal_d, name = "detection slope",
                      guide = guide_legend(nrow = 1)) +
  labs(x = "canopy cover (standard deviations)",
       y = "log detection term",
       title = "The detection term",
       subtitle = "dashed: its best straight line") +
  theme_datasheet()

p_right <- ggplot(curve_df, aes(x2, resid, colour = slope)) +
  geom_hline(yintercept = 0, colour = te_line, linewidth = 0.4) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = pal_d, name = "detection slope",
                      guide = guide_legend(nrow = 1)) +
  labs(x = "canopy cover (standard deviations)",
       y = "curvature left over",
       title = "What the line misses",
       subtitle = "the whole evidence on detection") +
  theme_datasheet()

(p_left | p_right) + plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet() +
                    theme(legend.position = "bottom",
                          legend.direction = "horizontal"))

## ---- fitters ----
nll_sv <- function(th, y_obs, x1, x2, shared) {
  lin <- th[1] + th[2] * x1
  if (shared) lin <- lin + th[5] * x2
  mu <- exp(lin) * plogis(th[3] + th[4] * x2)
  if (any(!is.finite(mu)) || any(mu <= 0)) return(1e10)
  sum(mu) - sum(y_obs * log(mu))
}

gr_sv <- function(th, y_obs, x1, x2, shared) {
  lin <- th[1] + th[2] * x1
  if (shared) lin <- lin + th[5] * x2
  p_hat <- plogis(th[3] + th[4] * x2)
  mu <- exp(lin) * p_hat
  if (any(!is.finite(mu)) || any(mu <= 0)) return(rep(0, length(th)))
  resid_i <- y_obs - mu
  q_hat <- 1 - p_hat
  -c(sum(resid_i), sum(resid_i * x1), sum(resid_i * q_hat),
     sum(resid_i * q_hat * x2), sum(resid_i * x2))[seq_len(length(th))]
}

sim_tiles <- function(n_tile, shared, d_det, rho = 0) {
  x1 <- rnorm(n_tile)
  x2 <- rnorm(n_tile)
  if (rho != 0) x1 <- rho * x2 + sqrt(1 - rho^2) * x1
  lin <- a_true + b_true * x1
  if (shared) lin <- lin + b2_true * x2
  lam <- exp(lin)
  p_i <- plogis(c_true + d_det * x2)
  n_lat <- rpois(n_tile, lam)
  list(x1 = x1, x2 = x2, n_lat = n_lat,
       y1 = rbinom(n_tile, n_lat, p_i), y2 = rbinom(n_tile, n_lat, p_i))
}

fit_sv <- function(dat, shared) {
  gco <- glm.fit(cbind(1, dat$x1, dat$x2), dat$y1, family = poisson())$coefficients
  naive_cover <- unname(gco[3])
  starts <- list(c(gco[1] + log(2), gco[2], 0, 0, 0),
                 c(gco[1] + log(2), gco[2], 0,  naive_cover, 0),
                 c(gco[1] + log(2), gco[2], 0, -naive_cover, 0))
  best <- NULL
  for (st in starts) {
    fit <- try(optim(st[seq_len(4 + shared)], nll_sv, gr_sv, y_obs = dat$y1,
                     x1 = dat$x1, x2 = dat$x2, shared = shared, method = "BFGS",
                     hessian = TRUE, control = list(maxit = 500)), silent = TRUE)
    if (!inherits(fit, "try-error") && is.finite(fit$value) &&
        (is.null(best) || fit$value < best$value)) best <- fit
  }
  if (is.null(best)) return(c(NA, NA, NA, NA, naive_cover, NA))
  th <- best$par
  lin <- th[1] + th[2] * dat$x1
  if (shared) lin <- lin + th[5] * dat$x2
  se_c <- tryCatch(suppressWarnings(sqrt(diag(solve(best$hessian)))[3]),
                   error = function(e) NA_real_)
  ratio <- sum(exp(lin)) / sum(dat$n_lat)
  ratio_neg <- ratio
  if (shared && th[4] > 0) {
    ratio_neg <- sum(exp(th[1] + th[3] + th[2] * dat$x1 + (th[5] + th[4]) * dat$x2)) /
      sum(dat$n_lat)
  }
  c(ratio, se_c, th[3], th[4], naive_cover, ratio_neg)
}

cell_sv <- function(n_tile, shared, d_det, n_rep, seed, rho = 0) {
  set.seed(seed)
  out <- t(vapply(seq_len(n_rep),
                  function(i) fit_sv(sim_tiles(n_tile, shared, d_det, rho), shared),
                  numeric(6)))
  fin <- is.finite(out[, 1])
  usable <- fin & is.finite(out[, 2])
  data.frame(n_tile = n_tile, shared = shared, d_det = d_det, n_rep = n_rep,
             n_usable = sum(usable), rho = rho,
             med = median(out[fin, 1]),
             q10 = unname(quantile(out[fin, 1], 0.1)),
             q90 = unname(quantile(out[fin, 1], 0.9)),
             blow = mean(!usable | out[, 1] > 50),
             se_c = median(out[usable, 2]),
             wrong_sign = mean(out[usable, 4] > 0),
             naive = median(out[fin, 5]),
             width_neg = unname(quantile(out[fin, 6], 0.9) / quantile(out[fin, 6], 0.1)))
}

## ---- svgrid ----
cells <- expand.grid(d_det = d_grid, shared = c(FALSE, TRUE), n_tile = n_grid)
sv_tab <- do.call(rbind, lapply(seq_len(nrow(cells)), function(i) {
  n_rep <- if (cells$n_tile[i] == n_grid[1]) rep_small else rep_big
  cell_sv(cells$n_tile[i], cells$shared[i], cells$d_det[i], n_rep, 24100 + i)
}))
sv_tab$width <- sv_tab$q90 / sv_tab$q10
pick <- function(n_tile, shared, d_det) {
  sv_tab[sv_tab$n_tile == n_tile & sv_tab$shared == shared &
           sv_tab$d_det == d_det, ]
}
dis_small <- pick(n_grid[1], FALSE, d_grid[2])
n_wrong_dis <- round(pick(n_grid[1], FALSE, d_grid[2])$n_usable *
                       pick(n_grid[1], FALSE, d_grid[2])$wrong_sign)
dis_big   <- pick(n_grid[2], FALSE, d_grid[2])
sha_small <- pick(n_grid[1], TRUE,  d_grid[2])
sha_big   <- pick(n_grid[2], TRUE,  d_grid[2])
flat_dis  <- pick(n_grid[1], FALSE, d_grid[1])
steep_sha <- pick(n_grid[1], TRUE,  d_grid[3])
steep_sha_big <- pick(n_grid[2], TRUE,  d_grid[3])
steep_dis_big <- pick(n_grid[2], FALSE, d_grid[3])

## ---- sharedprose ----
width_ratio_small <- sha_small$width / dis_small$width
width_ratio_big   <- sha_big$width / dis_big$width
se_ratio_small    <- sha_small$se_c / dis_small$se_c

wrong_n    <- c(sha_small$n_usable, sha_big$n_usable)
wrong_hit  <- round(wrong_n * c(sha_small$wrong_sign, sha_big$wrong_sign))
wrong_pool <- sum(wrong_hit) / sum(wrong_n)
wrong_se   <- sqrt(wrong_pool * (1 - wrong_pool) * sum(1 / wrong_n))
wrong_z    <- abs(sha_big$wrong_sign - sha_small$wrong_sign) / wrong_se

cost_big   <- c(sha_big$width / dis_big$width,
                steep_sha_big$width / steep_dis_big$width)

## ---- rhoarm ----
rho_tab <- do.call(rbind, lapply(seq_along(rho_grid), function(j)
  cell_sv(n_grid[1], FALSE, d_grid[2], rep_rho, 31100 + j, rho_grid[j])))
rho_tab$width <- rho_tab$q90 / rho_tab$q10
rho_last  <- nrow(rho_tab)
rho_cost  <- rho_tab$width[rho_last] / rho_tab$width[1]
rho_se_up <- rho_tab$se_c[rho_last] / rho_tab$se_c[1]

## ---- profiles ----
nll_fixd <- function(th, d_fix, y_obs, x1, x2, shared) {
  lin <- th[1] + th[2] * x1
  if (shared) lin <- lin + th[4] * x2
  mu <- exp(lin) * plogis(th[3] + d_fix * x2)
  if (any(!is.finite(mu)) || any(mu <= 0)) return(1e10)
  sum(mu) - sum(y_obs * log(mu))
}

profile_d <- function(dat, shared, d_seq) {
  st0 <- c(log(2 * (mean(dat$y1) + 0.5)), 0, 0, 0)[seq_len(3 + shared)]
  walk <- function(idx, st) {
    out <- matrix(NA_real_, length(idx), 2)
    for (k in seq_along(idx)) {
      fit <- optim(st, nll_fixd, NULL, d_fix = d_seq[idx[k]], y_obs = dat$y1,
                   x1 = dat$x1, x2 = dat$x2, shared = shared,
                   method = "BFGS", control = list(maxit = 800))
      st <- fit$par
      lin <- fit$par[1] + fit$par[2] * dat$x1
      if (shared) lin <- lin + fit$par[4] * dat$x2
      out[k, ] <- c(fit$value, sum(exp(lin)) / sum(dat$n_lat))
    }
    out
  }
  mid <- which.min(abs(d_seq - d_grid[2]))
  up  <- walk(mid:length(d_seq), st0)
  dn  <- walk((mid - 1):1, st0)
  res <- rbind(dn[rev(seq_len(nrow(dn))), , drop = FALSE], up)
  data.frame(d_det = d_seq, nll = res[, 1], ratio = res[, 2])
}

# One fixed-slope fit from several starts; the best value is kept.
fit_fixd <- function(dat, shared, d_fix, starts) {
  best <- Inf
  for (st in starts) {
    fit <- optim(st, nll_fixd, NULL, d_fix = d_fix, y_obs = dat$y1,
                 x1 = dat$x1, x2 = dat$x2, shared = shared, method = "BFGS",
                 control = list(maxit = 5000, reltol = 1e-12))
    best <- min(best, fit$value)
  }
  best
}

# A steep negative slope makes detection a step in cover. Start each fit with
# the step placed between the highest-cover tile that has a count and the next
# tile up, and with the Poisson fit to the tiles below the step.
fit_steep <- function(dat, d_fix) {
  t_last <- max(dat$x2[dat$y1 > 0])
  t_next <- min(c(dat$x2[dat$x2 > t_last], t_last + 0.1))
  below <- dat$x2 <= t_last
  g <- glm.fit(cbind(1, dat$x1, dat$x2)[below, ], dat$y1[below],
               family = poisson())$coefficients
  starts <- lapply(seq(t_last - 0.02, t_next + 0.02, length.out = 9),
                   function(t0) c(g[1], g[2], -d_fix * t0, g[3]))
  fit_fixd(dat, TRUE, d_fix, starts)
}

d_seq <- seq(-3, 3, length.out = 61)
set.seed(51515)
dat_dis <- sim_tiles(n_grid[1], FALSE, d_grid[2])
dat_sha <- sim_tiles(n_grid[1], TRUE,  d_grid[2])
prof_dis <- profile_d(dat_dis, FALSE, d_seq)
prof_sha <- profile_d(dat_sha, TRUE,  d_seq)

# The deviance is measured from the best fit, which the grid can miss. For the
# distinct survey, refine the slope around the best grid point. For the shared
# survey the likelihood keeps improving as the slope steepens past the grid;
# the profile is symmetric in the slope (the mirror image), so the steep side
# is checked with negative slopes only.
k_dis <- which.min(prof_dis$nll)
st_dis <- list(c(log(2 * (mean(dat_dis$y1) + 0.5)), 0, 0))
top_dis <- min(prof_dis$nll,
               optimize(function(d) fit_fixd(dat_dis, FALSE, d, st_dis),
                        d_seq[k_dis] + c(-0.1, 0.1), tol = 1e-6)$objective)
steep_d <- c(-100, -200, -400)
steep_nll <- vapply(steep_d, function(d) fit_steep(dat_sha, d), 0)
top_sha <- min(prof_sha$nll, steep_nll)
steep_spread <- 2 * (max(steep_nll) - min(steep_nll))
prof_dis$devi <- 2 * (prof_dis$nll - top_dis)
prof_sha$devi <- 2 * (prof_sha$nll - top_sha)
sha_devmin <- min(prof_sha$devi)
chi_cut <- qchisq(0.95, 1)
in_dis <- prof_dis[prof_dis$devi <= chi_cut, ]
in_sha <- prof_sha[prof_sha$devi <= chi_cut, ]
dis_nrange <- range(in_dis$ratio)
sha_nrange <- range(in_sha$ratio)
sha_devmax <- max(prof_sha$devi)
dis_devmax <- max(prof_dis$devi)

## ---- fig-profile ----
prof_all <- rbind(cbind(prof_dis, arm = "distinct covariates"),
                  cbind(prof_sha, arm = "cover on both"))
prof_all$arm <- factor(prof_all$arm,
                       levels = c("distinct covariates", "cover on both"))
pal_arm <- c("distinct covariates" = te_forest, "cover on both" = te_rust)

p_d <- ggplot(prof_all, aes(d_det, devi, colour = arm)) +
  geom_hline(yintercept = chi_cut, linetype = "dashed",
             colour = te_body, linewidth = 0.5) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = pal_arm, name = NULL,
                      guide = guide_legend(nrow = 1)) +
  coord_cartesian(ylim = c(0, 20)) +
  labs(x = "detection slope held fixed", y = "profile deviance",
       title = "One survey, profiled",
       subtitle = "dashed: the 95 per cent cut") +
  theme_datasheet()

p_n <- ggplot(prof_all[prof_all$devi <= 8, ], aes(ratio, devi, colour = arm)) +
  geom_hline(yintercept = chi_cut, linetype = "dashed",
             colour = te_body, linewidth = 0.5) +
  geom_line(linewidth = 0.9) +
  scale_colour_manual(values = pal_arm, name = NULL,
                      guide = guide_legend(nrow = 1)) +
  scale_x_log10() +
  labs(x = "estimated total / true total", y = "profile deviance",
       title = "The cost in abundance",
       subtitle = "the shared arm stays flat") +
  theme_datasheet()

(p_d | p_n) + plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet() +
                    theme(legend.position = "bottom",
                          legend.direction = "horizontal"))

## ---- fig-band ----
band_df <- sv_tab
band_df$arm <- factor(ifelse(band_df$shared, "cover on both",
                             "distinct covariates"),
                      levels = c("distinct covariates", "cover on both"))
band_df$steep <- abs(band_df$d_det)
band_df$panel <- factor(sprintf("%d tiles", band_df$n_tile),
                        levels = sprintf("%d tiles", n_grid))

ggplot(band_df, aes(steep, med, colour = arm)) +
  geom_hline(yintercept = 1, linetype = "dashed",
             colour = te_body, linewidth = 0.5) +
  geom_errorbar(aes(ymin = q10, ymax = q90), width = 0.2,
                linewidth = 0.7, position = position_dodge(width = 0.3)) +
  geom_point(size = 2.4, position = position_dodge(width = 0.3)) +
  facet_wrap(~panel) +
  scale_colour_manual(values = pal_arm, name = NULL) +
  scale_y_log10() +
  scale_x_continuous(breaks = abs(d_grid)) +
  labs(x = "steepness of the detection slope",
       y = "estimated total / true total",
       title = "What one flight can promise",
       subtitle = "points: median; bars: middle eight tenths of surveys") +
  theme_datasheet() +
  theme(legend.position = "bottom",
        strip.text = element_text(colour = te_ink, face = "bold"))

## ---- twoflights ----
n_max <- 60L
grid_n <- 0:n_max
sd_log <- sqrt(b_true^2 + b2_true^2)
p_over <- sum(w_quad * ppois(n_max, exp(a_true + sd_log * x_quad),
                             lower.tail = FALSE))

pre_k2 <- function(dat) {
  n_tile <- length(dat$y1)
  n_mat <- matrix(grid_n, n_tile, n_max + 1L, byrow = TRUE)
  list(n_mat = n_mat, ysum = dat$y1 + dat$y2,
       const = lchoose(n_mat, dat$y1) + lchoose(n_mat, dat$y2) -
         lgamma(n_mat + 1))
}

nll_k2 <- function(th, pre, x1, x2, shared) {
  lin <- th[1] + th[2] * x1
  if (shared) lin <- lin + th[5] * x2
  lam <- exp(lin)
  p_hat <- plogis(th[3] + th[4] * x2)
  if (any(!is.finite(lam)) || any(lam <= 0) || any(lam > 1e6)) return(1e10)
  lq <- log1p(-p_hat)
  tot <- pre$const + pre$n_mat * (log(lam) + 2 * lq) +
    (-lam + pre$ysum * (log(p_hat) - lq))
  top <- tot[cbind(seq_along(lam), max.col(tot, "first"))]
  ll <- top + log(rowSums(exp(tot - top)))
  if (any(!is.finite(ll))) return(1e10)
  -sum(ll)
}

fit_k2 <- function(dat, shared) {
  pre <- pre_k2(dat)
  st <- c(log(2 * (mean(dat$y1) + 0.5)), 0, 0, 0, 0)[seq_len(4 + shared)]
  fit <- try(optim(st, nll_k2, NULL, pre = pre, x1 = dat$x1, x2 = dat$x2,
                   shared = shared, method = "BFGS", hessian = TRUE,
                   control = list(maxit = 500)), silent = TRUE)
  if (inherits(fit, "try-error")) return(c(NA, NA, NA, NA))
  th <- fit$par
  lin <- th[1] + th[2] * dat$x1
  if (shared) lin <- lin + th[5] * dat$x2
  se_c <- tryCatch(suppressWarnings(sqrt(diag(solve(fit$hessian)))[3]),
                   error = function(e) NA_real_)
  c(sum(exp(lin)) / sum(dat$n_lat), se_c, th[3], th[4])
}

cell_k2 <- function(shared, seed) {
  set.seed(seed)
  out <- t(vapply(seq_len(rep_two),
                  function(i) fit_k2(sim_tiles(n_grid[1], shared, d_grid[2]),
                                     shared),
                  numeric(4)))
  fin <- is.finite(out[, 1])
  usable <- fin & is.finite(out[, 2])
  data.frame(shared = shared, med = median(out[fin, 1]),
             q10 = unname(quantile(out[fin, 1], 0.1)),
             q90 = unname(quantile(out[fin, 1], 0.9)),
             blow = mean(!usable | out[, 1] > 50),
             se_c = median(out[usable, 2]),
             wrong_sign = mean(out[usable, 4] > 0),
             n_usable = sum(usable))
}
k2_tab <- rbind(cell_k2(FALSE, 26001), cell_k2(TRUE, 26002))
k2_dis <- k2_tab[!k2_tab$shared, ]
k2_sha <- k2_tab[k2_tab$shared, ]
se_gain_sha <- sha_small$se_c / k2_sha$se_c
se_gain_dis <- dis_small$se_c / k2_dis$se_c
n_wrong_k2 <- round(k2_sha$n_usable * k2_sha$wrong_sign)

## ---- fig-flights ----
flight_df <- rbind(
  data.frame(flights = 1, arm = c("distinct covariates", "cover on both"),
             se_c = c(dis_small$se_c, sha_small$se_c),
             med = c(dis_small$med, sha_small$med),
             q10 = c(dis_small$q10, sha_small$q10),
             q90 = c(dis_small$q90, sha_small$q90)),
  data.frame(flights = 2, arm = c("distinct covariates", "cover on both"),
             se_c = c(k2_dis$se_c, k2_sha$se_c),
             med = c(k2_dis$med, k2_sha$med),
             q10 = c(k2_dis$q10, k2_sha$q10),
             q90 = c(k2_dis$q90, k2_sha$q90)))
flight_df$arm <- factor(flight_df$arm,
                        levels = c("distinct covariates", "cover on both"))

p_se <- ggplot(flight_df, aes(flights, se_c, colour = arm)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.6) +
  scale_colour_manual(values = pal_arm, name = NULL,
                      guide = guide_legend(nrow = 1)) +
  scale_x_continuous(breaks = c(1, 2)) +
  scale_y_log10() +
  labs(x = "flights over the block", y = "median SE of detection intercept",
       title = "What the repeat buys",
       subtitle = "two hundred tiles") +
  theme_datasheet()

p_band <- ggplot(flight_df, aes(flights, med, colour = arm)) +
  geom_hline(yintercept = 1, linetype = "dashed",
             colour = te_body, linewidth = 0.5) +
  geom_errorbar(aes(ymin = q10, ymax = q90), width = 0.12, linewidth = 0.7,
                position = position_dodge(width = 0.18)) +
  geom_point(size = 2.4, position = position_dodge(width = 0.18)) +
  scale_colour_manual(values = pal_arm, guide = "none") +
  scale_x_continuous(breaks = c(1, 2)) +
  scale_y_log10() +
  labs(x = "flights over the block", y = "estimated total / true total",
       title = "And to abundance",
       subtitle = "bars: middle eight tenths") +
  theme_datasheet()

(p_se | p_band) + plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet() +
                    theme(legend.position = "bottom",
                          legend.direction = "horizontal"))

## ---- naiveglm ----
naive_dis <- dis_small$naive
naive_sha <- sha_small$naive
naive_shift <- naive_sha - naive_dis
