# Sampling bias in presence-only models
# https://tidyecology.com/posts/sampling-bias-in-presence-only-models/
#
# 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-14

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

## ---- landscape ----
set.seed(20260816)
nx <- 60
n_cell <- nx * nx
gx <- rep(seq_len(nx), times = nx)
gy <- rep(seq_len(nx), each = nx)
b_env <- 1.2
g_eff <- 1.0
lam0 <- 1.1
n_bg <- 10000
n_cand <- 12

zstd <- function(v) (v - mean(v)) / sd(v)
smooth_field <- function(ux, uy, n_basis, f_max) {
  out <- numeric(length(ux))
  for (k in seq_len(n_basis)) {
    wx <- sample(seq_len(f_max), 1); wy <- sample(seq_len(f_max), 1)
    out <- out + rnorm(1) * cos(2 * pi * (wx * ux + wy * uy) / nx + runif(1, 0, 2 * pi))
  }
  zstd(out)
}
env <- smooth_field(gx, gy, 3, 2)

softplus <- function(z) ifelse(z > 30, z, log1p(exp(z)))
pop_slope <- function(effv, ratio) {
  w1 <- exp(b_env * env + g_eff * effv); w1 <- ratio * w1 / sum(w1)
  w0 <- rep(1 / n_cell, n_cell)
  nll <- function(par) {
    eta <- par[1] + par[2] * env
    -sum(w1 * eta - (w1 + w0) * softplus(eta))
  }
  optim(c(-2, 1), nll, method = "BFGS")$par[2]
}

set.seed(313)
cand_list <- replicate(n_cand, zstd(residuals(lm(smooth_field(gx, gy, 8, 5) ~ env))),
                       simplify = FALSE)
cand_slope <- vapply(cand_list, pop_slope, numeric(1), ratio = 0.15)
acc_perp <- cand_list[[which.min(abs(cand_slope - b_env))]]
acc_bad <- cand_list[[which.max(abs(cand_slope - b_env))]]
cat(sprintf("candidate access surfaces %d; all correlations with environment below %.1e\n",
            n_cand, max(abs(vapply(cand_list, function(v) cor(v, env), numeric(1))))))
cat(sprintf("asymptotic naive slope over the candidates: %.3f to %.3f (truth %.1f)\n",
            min(cand_slope), max(cand_slope), b_env))
cat(sprintf("chosen surface %.4f, worst surface %.4f\n",
            pop_slope(acc_perp, 0.15), pop_slope(acc_bad, 0.15)))

make_effort <- function(rho) zstd(rho * env + sqrt(1 - rho^2) * acc_perp)
draw_records <- function(effv) {
  det_p <- exp(g_eff * (effv - max(effv)))
  rep(seq_len(n_cell), rbinom(n_cell, rpois(n_cell, lam0 * exp(b_env * env)), det_p))
}
uni_bg <- function() sample(seq_len(n_cell), n_bg, replace = TRUE)
fit_pb <- function(rc, bc, form, covs) {
  dd <- cbind(data.frame(pres = c(rep(1, length(rc)), rep(0, length(bc)))),
              covs[c(rc, bc), , drop = FALSE])
  glm(form, data = dd, family = binomial())
}

eff_ref <- make_effort(0.6)
covs_ref <- data.frame(env = env, eff = eff_ref)
det_ref <- exp(g_eff * (eff_ref - max(eff_ref)))
n_ind_ref <- rpois(n_cell, lam0 * exp(b_env * env))
rec_ref <- rbinom(n_cell, n_ind_ref, det_ref)
cat(sprintf("grid %d by %d = %d cells; true slopes environment %.1f effort %.1f\n",
            nx, nx, n_cell, b_env, g_eff))
cat(sprintf("individuals %d, records %d, share recorded %.3f, cells holding a record %d\n",
            sum(n_ind_ref), sum(rec_ref), sum(rec_ref) / sum(n_ind_ref), sum(rec_ref > 0)))
cat(sprintf("detection probability %.4f to %.4f, a ratio of %.0f; correlation %.3f\n",
            min(det_ref), max(det_ref), max(det_ref) / min(det_ref), cor(env, eff_ref)))
cat(sprintf("background points per fit %d; records per occupied cell %.2f; busiest cell %d\n",
            n_bg, sum(rec_ref) / sum(rec_ref > 0), max(rec_ref)))

## ---- fig-landscape ----
rank01 <- function(v) (rank(v) - 0.5) / length(v)
lay_lv <- c("environment", "survey effort", "expected record density")
d_land <- data.frame(x = rep(gx, 3), y = rep(gy, 3),
  layer = factor(rep(lay_lv, each = n_cell), levels = c(lay_lv, "records received")),
  v = c(rank01(env), rank01(eff_ref), rank01(exp(b_env * env) * det_ref)))
d_pts <- data.frame(
  x = gx[rep(seq_len(n_cell), rec_ref)] + runif(sum(rec_ref), -0.4, 0.4),
  y = gy[rep(seq_len(n_cell), rec_ref)] + runif(sum(rec_ref), -0.4, 0.4),
  layer = factor("records received", levels = c(lay_lv, "records received")))
p_land <- ggplot(d_land, aes(x, y)) +
  geom_raster(aes(fill = v)) +
  geom_point(data = d_pts, colour = te_pal$forest, size = 0.45, alpha = 0.55) +
  facet_wrap(~layer, nrow = 2) +
  scale_fill_gradientn(colours = c(te_pal$paper, te_pal$sage, te_pal$green, te_pal$forest),
                       breaks = c(0.1, 0.5, 0.9), labels = c("low", "middle", "high")) +
  coord_equal(expand = FALSE, xlim = c(0.5, nx + 0.5), ylim = c(0.5, nx + 0.5)) +
  labs(title = "Effort decides which part of the species is recorded",
       x = NULL, y = NULL, fill = NULL) +
  theme_te() +
  theme(axis.text = element_blank(), panel.grid.major = element_blank(),
        legend.position = "bottom", legend.key.height = unit(0.3, "cm"),
        legend.key.width = unit(1.1, "cm"))
print(p_land)

## ---- sweep ----
rho_seq <- c(0, 0.2, 0.4, 0.6, 0.8)
n_rep <- 25
set.seed(4242)
sweep_rows <- NULL
for (rh in rho_seq) {
  effv <- make_effort(rh)
  wt <- exp(g_eff * effv)
  covs <- data.frame(env = env, eff = effv)
  acc <- matrix(0, n_rep, 8)
  for (r in seq_len(n_rep)) {
    rc <- draw_records(effv); bc <- uni_bg()
    tg <- sample(seq_len(n_cell), n_bg, replace = TRUE, prob = wt)
    m1 <- fit_pb(rc, bc, pres ~ env, covs)
    m2 <- fit_pb(rc, bc, pres ~ env + eff, covs)
    m3 <- fit_pb(rc, tg, pres ~ env, covs)
    m4 <- fit_pb(unique(rc), bc, pres ~ env, covs)
    acc[r, ] <- c(coef(m1)[2], coef(m2)[2], coef(m3)[2], coef(m4)[2], coef(m2)[3],
                  length(rc), length(unique(rc)), summary(m1)$coefficients[2, 2])
  }
  sweep_rows <- rbind(sweep_rows, data.frame(rho = rh,
    naive = mean(acc[, 1]), effort = mean(acc[, 2]), tgb = mean(acc[, 3]),
    thinned = mean(acc[, 4]), eff_slope = mean(acc[, 5]),
    n_rec = mean(acc[, 6]), n_thin = mean(acc[, 7]),
    sd_naive = sd(acc[, 1]), sd_effort = sd(acc[, 2]), sd_tgb = sd(acc[, 3]),
    sd_thin = sd(acc[, 4])))
}
sweep_rows$asym_naive <- vapply(rho_seq, function(rh) pop_slope(make_effort(rh), 0.15), numeric(1))
print(round(sweep_rows[, c("rho", "n_rec", "naive", "asym_naive", "effort",
                           "eff_slope", "tgb", "thinned")], 3))
cat(sprintf("correlations %d, replicate datasets each %d, background points %d\n",
            length(rho_seq), n_rep, n_bg))
cat(sprintf("naive error at zero correlation %.1f per cent; at 0.8 %.1f per cent\n",
            100 * (sweep_rows$naive[1] / b_env - 1), 100 * (sweep_rows$naive[5] / b_env - 1)))
cat(sprintf("largest gap between simulated and asymptotic naive slope %.3f\n",
            max(abs(sweep_rows$naive - sweep_rows$asym_naive))))

## ---- awkward-surface ----
set.seed(5150)
covs_bad <- data.frame(env = env, eff = acc_bad)
acc <- replicate(15, coef(fit_pb(draw_records(acc_bad), uni_bg(), pres ~ env, covs_bad))[2])
cor_bad <- cor(acc_bad, env)
cat(sprintf("awkward surface: correlation %.1e, simulated naive slope %.3f, asymptotic %.3f\n",
            cor_bad, mean(acc), pop_slope(acc_bad, 0.15)))
cat(sprintf("neutral surface asymptotic %.3f; gap between the two surfaces %.3f\n",
            pop_slope(acc_perp, 0.15), pop_slope(acc_bad, 0.15) - pop_slope(acc_perp, 0.15)))

## ---- prediction ----
set.seed(9091)
n_rep_p <- 10
lo <- which.min(eff_ref); hi <- which.max(eff_ref)
truth <- exp(b_env * env); truth <- truth / mean(truth)
pacc <- matrix(0, n_rep_p, 8)
for (r in seq_len(n_rep_p)) {
  rc <- draw_records(eff_ref); bc <- uni_bg()
  m_eff <- fit_pb(rc, bc, pres ~ env + eff, covs_ref)
  cf <- coef(m_eff)
  map_rec <- exp(cf[2] * env + cf[3] * eff_ref); map_rec <- map_rec / mean(map_rec)
  map_sp <- exp(cf[2] * env); map_sp <- map_sp / mean(map_sp)
  pacc[r, ] <- c(cf[2], cf[3], cor(map_rec, truth), cor(map_sp, truth),
                 map_rec[lo] / truth[lo], map_rec[hi] / truth[hi],
                 map_sp[lo] / truth[lo], map_sp[hi] / truth[hi])
}
pm <- colMeans(pacc)
cat(sprintf("replicate datasets %d, records in the last one %d\n", n_rep_p, length(rc)))
cat(sprintf("fitted slopes: environment %.3f, effort %.3f\n", pm[1], pm[2]))
cat(sprintf("map of records vs truth: correlation %.3f; effort held constant %.4f\n",
            pm[3], pm[4]))
cat(sprintf("least accessible cell: record map %.3f of truth, corrected map %.3f\n",
            pm[5], pm[7]))
cat(sprintf("most accessible cell: record map %.2f times truth, corrected map %.3f\n",
            pm[6], pm[8]))
cat(sprintf("record map error spans a factor of %.0f between those two cells\n", pm[6] / pm[5]))

## ---- fig-prediction ----
pl_lv <- c("true species intensity", "prediction, effort held constant", "prediction as fitted")
clamp <- function(v) pmin(pmax(v, -1.8), 1.8)
d_pred <- data.frame(x = rep(gx, 3), y = rep(gy, 3),
  layer = factor(rep(pl_lv, each = n_cell), levels = pl_lv),
  v = clamp(log10(c(truth, map_sp, map_rec))))
p_pred <- ggplot(d_pred, aes(x, y, fill = v)) +
  geom_raster() + facet_wrap(~layer, nrow = 1) +
  scale_fill_gradientn(colours = c(te_pal$clay, "#e3ded0", te_pal$sage, te_pal$forest),
                       limits = c(-1.8, 1.8), breaks = c(-1.5, 0, 1.5)) +
  coord_equal(expand = FALSE) +
  labs(title = "Predict without holding effort constant and you map the recorders",
       x = NULL, y = NULL, fill = "log10 relative intensity") +
  theme_te() +
  theme(axis.text = element_blank(), panel.grid.major = element_blank(),
        legend.position = "bottom", legend.key.width = unit(1.4, "cm"),
        legend.key.height = unit(0.3, "cm"))
print(p_pred)

## ---- proxy ----
set.seed(6161)
noise_f <- zstd(residuals(lm(smooth_field(gx, gy, 8, 5) ~ env + eff_ref)))
q_seq <- c(0, 0.3, 0.5, 0.7, 0.85, 0.95, 1)
n_rep_q <- 12
prox <- data.frame(quality = q_seq, slope = 0)
for (i in seq_along(q_seq)) {
  px <- zstd(q_seq[i] * eff_ref + sqrt(1 - q_seq[i]^2) * noise_f)
  cv <- data.frame(env = env, eff = px)
  prox$slope[i] <- mean(replicate(n_rep_q,
    coef(fit_pb(draw_records(eff_ref), uni_bg(), pres ~ env + eff, cv))[2]))
}
naive_ref <- sweep_rows$naive[sweep_rows$rho == 0.6]
prox$err_pct <- 100 * (prox$slope / b_env - 1)
prox$removed_pct <- 100 * (1 - (prox$slope - b_env) / (naive_ref - b_env))
print(round(prox, 2))

## ---- tgb-sweep ----
set.seed(7272)
kap_seq <- c(0, 0.25, 0.5, 0.75, 1, 1.25, 1.5)
n_rep_k <- 12
tgs <- data.frame(match = kap_seq, slope = 0)
for (i in seq_along(kap_seq)) {
  wt <- exp(kap_seq[i] * g_eff * eff_ref)
  tgs$slope[i] <- mean(replicate(n_rep_k, {
    tg <- sample(seq_len(n_cell), n_bg, replace = TRUE, prob = wt)
    coef(fit_pb(draw_records(eff_ref), tg, pres ~ env, covs_ref))[2] }))
}
tgs$err_pct <- 100 * (tgs$slope / b_env - 1)
print(round(tgs, 2))

## ---- fig-tgb ----
p_tgb <- ggplot(tgs, aes(match, slope)) +
  geom_ribbon(aes(ymin = 0.9 * b_env, ymax = 1.1 * b_env), fill = te_pal$sage, alpha = 0.28) +
  geom_hline(yintercept = b_env, colour = te_pal$ink, linewidth = 0.7) +
  geom_hline(yintercept = naive_ref, colour = te_pal$clay, linetype = "22", linewidth = 0.7) +
  geom_line(colour = te_pal$green, linewidth = 0.9) +
  geom_point(colour = te_pal$forest, size = 2.6) +
  annotate("text", x = 0.02, y = b_env - 0.07, hjust = 0, size = 3.3,
           colour = te_pal$ink, label = "truth, with a 10 per cent band") +
  annotate("text", x = 1.48, y = naive_ref - 0.07, hjust = 1, size = 3.3,
           colour = te_pal$clay, label = "naive fit") +
  labs(title = "The target group has to share the bias",
       x = "target-group bias as a multiple of the focal species' bias",
       y = "recovered environmental slope") +
  theme_te()
print(p_tgb)

## ---- thinning ----
thin_radius <- function(ii, jj, rad) {
  keep <- integer(0)
  for (k in sample(seq_along(ii))) {
    if (length(keep) == 0L) { keep <- k; next }
    if (min((ii[keep] - ii[k])^2 + (jj[keep] - jj[k])^2) >= rad^2) keep <- c(keep, k)
  }
  keep
}
rad_cells <- 3
n_rep_t <- 15
set.seed(8181)
thin_rows <- NULL
for (rh in c(0, 0.6)) {
  effv <- make_effort(rh); covs <- data.frame(env = env, eff = effv)
  acc <- matrix(0, n_rep_t, 9)
  for (r in seq_len(n_rep_t)) {
    rc <- draw_records(effv); bc <- uni_bg()
    kp <- thin_radius(gx[rc], gy[rc], rad_cells)
    ma <- fit_pb(rc, bc, pres ~ env, covs)
    mb <- fit_pb(unique(rc), bc, pres ~ env, covs)
    mc <- fit_pb(rc[kp], bc, pres ~ env, covs)
    acc[r, ] <- c(coef(ma)[2], coef(mb)[2], coef(mc)[2],
                  summary(ma)$coefficients[2, 2], summary(mb)$coefficients[2, 2],
                  summary(mc)$coefficients[2, 2], length(rc), length(unique(rc)), length(kp))
  }
  thin_rows <- rbind(thin_rows, data.frame(rho = rh,
    scheme = c("all records", "one per cell", "one per radius"),
    kept = round(colMeans(acc)[7:9]), slope = colMeans(acc)[1:3],
    err_pct = 100 * (colMeans(acc)[1:3] / b_env - 1),
    model_se = colMeans(acc)[4:6], spread = apply(acc[, 1:3], 2, sd)))
}
print(round(thin_rows[, -2], 3))
print(as.character(thin_rows$scheme))
cat(sprintf("thinning radius %d cells; replicate datasets %d\n", rad_cells, n_rep_t))
cat(sprintf("at zero correlation, error of one per cell %.1f per cent, one per radius %.1f\n",
            thin_rows$err_pct[2], thin_rows$err_pct[3]))

## ---- thinning-mechanism ----
set.seed(2424)
eff0 <- make_effort(0)
rc <- draw_records(eff0)
kp <- thin_radius(gx[rc], gy[rc], rad_cells)
cat(sprintf("mean environment: background %.3f, all records %.3f, one per cell %.3f, one per radius %.3f\n",
            mean(env), mean(env[rc]), mean(env[unique(rc)]), mean(env[rc[kp]])))
draw_sparse <- function(effv, scale_l) {
  det_p <- exp(g_eff * (effv - max(effv)))
  rep(seq_len(n_cell), rbinom(n_cell, rpois(n_cell, scale_l * lam0 * exp(b_env * env)), det_p))
}
covs0 <- data.frame(env = env, eff = eff0)
sat <- NULL
for (sl in c(1, 0.15)) {
  acc <- matrix(0, 12, 4)
  for (r in 1:12) {
    rr <- draw_sparse(eff0, sl); bc <- uni_bg()
    acc[r, ] <- c(coef(fit_pb(rr, bc, pres ~ env, covs0))[2],
                  coef(fit_pb(unique(rr), bc, pres ~ env, covs0))[2],
                  length(rr), length(unique(rr)))
  }
  sat <- rbind(sat, data.frame(intensity = sl, records = mean(acc[, 3]),
    occupied = mean(acc[, 4]), per_cell = mean(acc[, 3]) / mean(acc[, 4]),
    all_records = mean(acc[, 1]), one_per_cell = mean(acc[, 2])))
}
print(round(sat, 3))

## ---- fig-rank ----
est_lv <- c("naive", "effort covariate", "target-group background", "one record per cell")
d_rank <- data.frame(rho = rep(sweep_rows$rho, 4),
  est = factor(rep(est_lv, each = nrow(sweep_rows)), levels = est_lv),
  slope = c(sweep_rows$naive, sweep_rows$effort, sweep_rows$tgb, sweep_rows$thinned))
p_rank <- ggplot(d_rank, aes(rho, slope, colour = est, shape = est)) +
  geom_hline(yintercept = b_env, colour = te_pal$ink, linewidth = 0.7) +
  geom_line(linewidth = 0.8) + geom_point(size = 2.8) +
  annotate("text", x = 0.8, y = b_env - 0.06, hjust = 1, size = 3.3,
           colour = te_pal$ink, label = "truth") +
  scale_colour_manual(values = c(te_pal$clay, te_pal$forest, te_pal$green, te_pal$gold)) +
  scale_shape_manual(values = c(16, 15, 17, 18)) +
  labs(title = "Only two of the four hold flat as the bias grows",
       x = "correlation between survey effort and environment",
       y = "recovered environmental slope", colour = NULL, shape = NULL) +
  theme_te() +
  theme(legend.position = "top")
print(p_rank)

## ---- ranking ----
rank_tab <- data.frame(
  estimator = est_lv,
  mean_error = c(mean(abs(sweep_rows$naive - b_env)), mean(abs(sweep_rows$effort - b_env)),
                 mean(abs(sweep_rows$tgb - b_env)), mean(abs(sweep_rows$thinned - b_env))),
  worst_error = c(max(abs(sweep_rows$naive - b_env)), max(abs(sweep_rows$effort - b_env)),
                  max(abs(sweep_rows$tgb - b_env)), max(abs(sweep_rows$thinned - b_env))),
  spread = c(mean(sweep_rows$sd_naive), mean(sweep_rows$sd_effort),
             mean(sweep_rows$sd_tgb), mean(sweep_rows$sd_thin)))
rank_tab$needs <- c("nothing", "an effort surface", "a matched target group", "nothing")
rank_tab[, 2:4] <- round(rank_tab[, 2:4], 4)
print(rank_tab[order(rank_tab$mean_error), ], row.names = FALSE)
cat(sprintf("bias ranges over a factor of %.0f; replicate spread over a factor of %.2f\n",
            max(rank_tab$mean_error) / min(rank_tab$mean_error),
            max(rank_tab$spread) / min(rank_tab$spread)))

## ---- identifiability ----
set.seed(1313)
draw_preference <- function(effv) {
  rep(seq_len(n_cell), rpois(n_cell, lam0 * exp(b_env * env + g_eff * (effv - max(effv)))))
}
acc <- matrix(0, 15, 4)
for (r in 1:15) {
  ra <- draw_records(eff_ref); rb <- draw_preference(eff_ref); bc <- uni_bg()
  acc[r, ] <- c(coef(fit_pb(ra, bc, pres ~ env + eff, covs_ref))[2:3],
                coef(fit_pb(rb, bc, pres ~ env + eff, covs_ref))[2:3])
}
im <- colMeans(acc)
cat(sprintf("biased detection: environment %.3f, effort %.3f\n", im[1], im[2]))
cat(sprintf("genuine preference: environment %.3f, effort %.3f\n", im[3], im[4]))
cat(sprintf("difference %.4f and %.4f, against a replicate spread of %.4f\n",
            im[1] - im[3], im[2] - im[4], sd(acc[, 1])))
