# Class imbalance in species presence models
# https://tidyecology.com/posts/class-imbalance-in-species-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-10-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"))
}

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

## ---- truth ----
set.seed(20260815)
b_int <- -4.6; b_elev <- 1.3; b_wet <- -0.9

sim_sites <- function(nn, b0 = b_int) {
  ev <- rnorm(nn); wv <- rnorm(nn)
  data.frame(elev = ev, wet = wv,
             occ = rbinom(nn, 1, plogis(b0 + b_elev * ev + b_wet * wv)))
}

auc_of <- function(score, yy) {
  rk <- rank(score)
  n1 <- sum(yy == 1); n0 <- sum(yy == 0)
  (sum(rk[yy == 1]) - n1 * (n1 + 1) / 2) / (n1 * n0)
}

check <- sim_sites(200000)
cat(sprintf("true coefficients: intercept %.1f, elevation %.1f, wetness %.1f\n",
            b_int, b_elev, b_wet))
cat(sprintf("marginal prevalence from 200000 sites: %.4f\n", mean(check$occ)))
cat(sprintf("occupancy probability at an average site: %.4f\n", plogis(b_int)))

## ---- popsim ----
set.seed(11235)
n_pop <- 1200000
pop <- sim_sites(n_pop)
pos_all <- which(pop$occ == 1)
neg_all <- which(pop$occ == 0)
cat(sprintf("pool: %d sites, %d occupied, prevalence %.4f\n",
            n_pop, length(pos_all), mean(pop$occ)))

n_warn <- 0
se_slope <- function(rows) {
  fit <- withCallingHandlers(
    glm(occ ~ elev + wet, data = pop[rows, ], family = binomial),
    warning = function(w) { n_warn <<- n_warn + 1; invokeRestart("muffleWarning") })
  summary(fit)$coefficients["elev", "Std. Error"]
}

## ---- sweeps ----
n_fix <- 60
neg_grid <- c(60, 180, 600, 1800, 6000, 20000)
rep_a <- 60
se_a <- vapply(neg_grid, function(nn)
  mean(replicate(rep_a, se_slope(c(sample(pos_all, n_fix), sample(neg_all, nn))))),
  numeric(1))
tab_a <- data.frame(sites = n_fix + neg_grid, positives = n_fix,
                    prevalence = n_fix / (n_fix + neg_grid), se_elev = se_a)

prev_fix <- 0.03
tot_grid <- c(1000, 3000, 10000, 30000, 60000)
rep_b <- 30
se_b <- vapply(tot_grid, function(nn) {
  np <- round(nn * prev_fix)
  mean(replicate(rep_b, se_slope(c(sample(pos_all, np), sample(neg_all, nn - np)))))
}, numeric(1))
tab_b <- data.frame(sites = tot_grid, positives = round(tot_grid * prev_fix),
                    prevalence = prev_fix, se_elev = se_b)

cat(sprintf("design A: %d positives held fixed, %d replicate draws per grid point\n",
            n_fix, rep_a))
print(round(tab_a, 4))
cat(sprintf("design B: prevalence held at %.2f, %d replicate draws per grid point\n",
            prev_fix, rep_b))
print(round(tab_b, 4))
cat(sprintf("glm warnings during both sweeps: %d\n", n_warn))

## ---- exponents ----
cat(sprintf("exponent on positives, fixed prevalence: %.4f\n",
            coef(lm(log(se_b) ~ log(tab_b$positives)))[2]))
cat(sprintf("exponent on negatives, fixed positives:  %.4f\n",
            coef(lm(log(se_a) ~ log(neg_grid)))[2]))
cat(sprintf("fixed positives: se %.4f to %.4f, a %.3f-fold gain for %.0f times the absences\n",
            se_a[1], se_a[6], se_a[1] / se_a[6], neg_grid[6] / neg_grid[1]))
cat(sprintf("last step of design A: %d to %d absences cuts the se by %.1f percent\n",
            neg_grid[5], neg_grid[6], 100 * (1 - se_a[6] / se_a[5])))
cat(sprintf("%d sites with %d positives: se %.4f\n", tab_a$sites[6], n_fix, se_a[6]))
cat(sprintf("%d sites with %d positives: se %.4f (ratio %.2f)\n",
            tab_b$sites[3], tab_b$positives[3], se_b[3], se_a[6] / se_b[3]))

## ---- sefig ----
sweep_dat <- rbind(
  data.frame(tab_a, design = "60 positives, absences added"),
  data.frame(tab_b, design = "prevalence 0.03, survey grows"))

p_se <- ggplot(sweep_dat, aes(sites, se_elev, colour = design)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.4) +
  scale_x_log10() +
  scale_y_log10() +
  scale_colour_manual(values = c(te_pal$clay, te_pal$forest)) +
  labs(title = "Only the positives buy precision",
       x = "sites in the sample (log scale)",
       y = "standard error of the elevation slope (log scale)",
       colour = NULL) +
  theme_te() +
  theme(legend.position = "top")
print(p_se)

## ---- survey ----
set.seed(4142)
survey <- sim_sites(4000)
fit_sv <- glm(occ ~ elev + wet, data = survey, family = binomial)
p_hat <- fitted(fit_sv)
called <- p_hat >= 0.5
cat(sprintf("survey: %d sites, %d occupied, prevalence %.4f\n",
            nrow(survey), sum(survey$occ), mean(survey$occ)))
print(round(summary(fit_sv)$coefficients, 4))
cat(sprintf("largest fitted probability: %.4f\n", max(p_hat)))
cat(sprintf("sites called present at 0.5: %d, of which really occupied: %d\n",
            sum(called), sum(called & survey$occ == 1)))

## ---- zerorule ----
sens <- sum(called & survey$occ == 1) / sum(survey$occ == 1)
spec <- sum(!called & survey$occ == 0) / sum(survey$occ == 0)
cat(sprintf("sensitivity %.4f, specificity %.4f, TSS %.4f\n", sens, spec, sens + spec - 1))
cat(sprintf("accuracy of the 0.5 rule: %.4f\n", mean(called == (survey$occ == 1))))
cat(sprintf("accuracy of calling every site absent: %.4f\n", mean(survey$occ == 0)))
cat(sprintf("AUC of the same fitted values: %.4f\n", auc_of(p_hat, survey$occ)))
cat(sprintf("median fitted probability, occupied %.4f, empty %.4f\n",
            median(p_hat[survey$occ == 1]), median(p_hat[survey$occ == 0])))

## ---- probfig ----
prob_dat <- data.frame(p_hat = p_hat,
                       state = ifelse(survey$occ == 1, "occupied", "empty"))
p_prob <- ggplot(prob_dat, aes(p_hat, fill = state, colour = state)) +
  geom_histogram(bins = 40, position = "identity", alpha = 0.45) +
  geom_vline(xintercept = 0.5, linetype = "dashed", colour = te_pal$ink) +
  scale_x_log10(labels = function(x) vapply(x, format, "", scientific = FALSE,
                                            drop0trailing = TRUE)) +
  scale_y_sqrt() +
  scale_fill_manual(values = c(te_pal$sage, te_pal$clay)) +
  scale_colour_manual(values = c(te_pal$sage, te_pal$clay)) +
  labs(title = "The fitted probabilities almost never reach the default rule",
       x = "fitted probability of presence (log scale)",
       y = "sites (square root scale)", fill = NULL, colour = NULL) +
  theme_te() +
  theme(legend.position = "top", plot.margin = margin(5.5, 14, 5.5, 5.5))
print(p_prob)

## ---- atlas ----
set.seed(2718)
atlas <- sim_sites(40000)
pos_r <- which(atlas$occ == 1)
neg_r <- which(atlas$occ == 0)
n_pos <- length(pos_r); n_neg <- length(neg_r)
cat(sprintf("atlas: %d squares, %d occupied, %d empty, prevalence %.4f\n",
            nrow(atlas), n_pos, n_neg, mean(atlas$occ)))

fit_full <- glm(occ ~ elev + wet, data = atlas, family = binomial)
fit_down <- glm(occ ~ elev + wet, data = atlas[c(pos_r, sample(neg_r, n_pos)), ],
                family = binomial)
frac_1 <- 1
frac_0 <- n_pos / n_neg
off_an <- log(frac_1 / frac_0)
side <- cbind(full = coef(fit_full), downsampled = coef(fit_down),
              difference = coef(fit_down) - coef(fit_full))
print(round(side, 4))
cat(sprintf("sampling fractions: presences %.4f, absences %.4f\n", frac_1, frac_0))
cat(sprintf("analytic intercept offset log(%.4f / %.4f) = %.4f\n", frac_1, frac_0, off_an))
cat(sprintf("measured intercept difference %.4f, gap %.4f\n",
            side["(Intercept)", "difference"], side["(Intercept)", "difference"] - off_an))
cat(sprintf("slope gaps in units of the downsampled standard error: elev %.3f, wet %.3f\n",
            side["elev", "difference"] / summary(fit_down)$coefficients["elev", "Std. Error"],
            side["wet", "difference"] / summary(fit_down)$coefficients["wet", "Std. Error"]))

## ---- downreps ----
n_rep <- 200
draw_down <- function() {
  glm(occ ~ elev + wet, data = atlas[c(pos_r, sample(neg_r, n_pos)), ], family = binomial)
}
rep_coef <- t(replicate(n_rep, coef(draw_down())))
cat(sprintf("downsampling repeated %d times\n", n_rep))
print(round(rbind(mean = colMeans(rep_coef), sd = apply(rep_coef, 2, sd),
                  full_data = coef(fit_full)), 4))
cat(sprintf("mean intercept shift %.4f against analytic %.4f (gap %.4f, full-fit se %.4f)\n",
            mean(rep_coef[, 1]) - coef(fit_full)[1], off_an,
            mean(rep_coef[, 1]) - coef(fit_full)[1] - off_an,
            summary(fit_full)$coefficients[1, "Std. Error"]))

## ---- calib ----
set.seed(3141)
holdout <- sim_sites(40000)
lp_down <- predict(fit_down, holdout)
pr_full <- predict(fit_full, holdout, type = "response")
pr_down <- plogis(lp_down)
pr_corr <- plogis(lp_down - off_an)
brier_of <- function(pv, yy) mean((pv - yy)^2)
cox_of <- function(pv, yy) coef(glm(yy ~ qlogis(pv), family = binomial))
score_tab <- data.frame(
  auc = c(auc_of(pr_full, holdout$occ), auc_of(pr_down, holdout$occ),
          auc_of(pr_corr, holdout$occ)),
  brier = c(brier_of(pr_full, holdout$occ), brier_of(pr_down, holdout$occ),
            brier_of(pr_corr, holdout$occ)),
  mean_pred = c(mean(pr_full), mean(pr_down), mean(pr_corr)),
  cal_int = c(cox_of(pr_full, holdout$occ)[1], cox_of(pr_down, holdout$occ)[1],
              cox_of(pr_corr, holdout$occ)[1]),
  cal_slope = c(cox_of(pr_full, holdout$occ)[2], cox_of(pr_down, holdout$occ)[2],
                cox_of(pr_corr, holdout$occ)[2]),
  row.names = c("full data", "downsampled", "downsampled, offset removed"))
cat(sprintf("held-out squares: %d, observed prevalence %.4f\n",
            nrow(holdout), mean(holdout$occ)))
print(round(score_tab, 5))
cat(sprintf("Brier ratio, downsampled over full: %.2f\n",
            score_tab$brier[2] / score_tab$brier[1]))
cat(sprintf("calibration intercept of the downsampled fit %.4f against offset %.4f\n",
            score_tab$cal_int[2], -off_an))

## ---- calibfig ----
n_bin <- 8
brk <- quantile(pr_full, seq(0, 1, length.out = n_bin + 1))
which_bin <- cut(pr_full, brk, include.lowest = TRUE, labels = FALSE)
obs_rate <- tapply(holdout$occ, which_bin, mean)
bin_dat <- rbind(
  data.frame(model = "full data", pred = tapply(pr_full, which_bin, mean), obs = obs_rate),
  data.frame(model = "downsampled", pred = tapply(pr_down, which_bin, mean), obs = obs_rate),
  data.frame(model = "downsampled, offset removed",
             pred = tapply(pr_corr, which_bin, mean), obs = obs_rate))
cat(sprintf("bins of %d squares; empty bins dropped: %d\n",
            nrow(holdout) / n_bin, sum(obs_rate == 0)))
print(round(data.frame(predicted = tapply(pr_full, which_bin, mean),
                       downsampled = tapply(pr_down, which_bin, mean),
                       observed = obs_rate), 5))
bin_dat <- bin_dat[bin_dat$obs > 0, ]

p_cal <- ggplot(bin_dat, aes(pred, obs, colour = model)) +
  geom_abline(intercept = 0, slope = 1, linetype = "dashed", colour = te_pal$ink) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.4) +
  scale_x_log10() +
  scale_y_log10() +
  scale_colour_manual(values = c(te_pal$clay, te_pal$gold, te_pal$forest)) +
  labs(title = "Downsampling moves the probabilities, not the ranking",
       x = "mean predicted probability in the bin (log scale)",
       y = "observed occupancy in the bin (log scale)", colour = NULL) +
  theme_te() +
  theme(legend.position = "top")
print(p_cal)

## ---- remedies ----
set.seed(1618)
tss_at <- function(pv, yy, thr) {
  sum(pv >= thr & yy == 1) / sum(yy == 1) + sum(pv < thr & yy == 0) / sum(yy == 0) - 1
}
tss_max <- function(pv, yy) {
  o <- order(-pv); ys <- yy[o]
  max(cumsum(ys) / sum(ys) - cumsum(1 - ys) / sum(1 - ys))
}
tune_thr <- function(pv, yy) {
  cand <- sort(unique(round(pv, 4)))
  cand[which.max(vapply(cand, function(tt) tss_at(pv, yy, tt), numeric(1)))]
}

b0_grid <- c(-1.0, -2.2, -3.4, -4.6)
n_train <- 4000
n_test <- 40000

one_prevalence <- function(b0) {
  tr <- sim_sites(n_train, b0)
  te <- sim_sites(n_test, b0)
  ip <- which(tr$occ == 1); iq <- which(tr$occ == 0)
  m_raw <- glm(occ ~ elev + wet, data = tr, family = binomial)
  m_down <- glm(occ ~ elev + wet, data = tr[c(ip, sample(iq, length(ip))), ],
                family = binomial)
  up_rows <- c(iq, sample(ip, length(iq), replace = TRUE))
  m_up <- glm(occ ~ elev + wet, data = tr[up_rows, ], family = binomial)
  wgt <- ifelse(tr$occ == 1, length(iq) / length(ip), 1)
  m_wt <- suppressWarnings(
    glm(occ ~ elev + wet, data = tr, family = binomial, weights = wgt))
  preds <- list(predict(m_raw, te, type = "response"), predict(m_raw, te, type = "response"),
                predict(m_down, te, type = "response"), predict(m_up, te, type = "response"),
                predict(m_wt, te, type = "response"))
  thrs <- c(0.5, tune_thr(fitted(m_raw), tr$occ), 0.5, 0.5, 0.5)
  data.frame(prevalence = mean(tr$occ), positives = sum(tr$occ),
             rule = c("raw, cut at 0.5", "raw, tuned cut", "downsampled, cut at 0.5",
                      "upsampled, cut at 0.5", "class weights, cut at 0.5"),
             cut_at = thrs,
             auc = vapply(preds, function(pv) auc_of(pv, te$occ), numeric(1)),
             brier = vapply(preds, function(pv) brier_of(pv, te$occ), numeric(1)),
             tss_used = mapply(function(pv, tt) tss_at(pv, te$occ, tt), preds, thrs),
             tss_best = vapply(preds, function(pv) tss_max(pv, te$occ), numeric(1)))
}
remedy_tab <- do.call(rbind, lapply(b0_grid, one_prevalence))
cat(sprintf("training sites %d, test sites %d, prevalences tested: %d\n",
            n_train, n_test, length(b0_grid)))
show_tab <- remedy_tab[, c("prevalence", "rule", "cut_at", "auc", "brier",
                           "tss_used", "tss_best")]
show_tab[, c(1, 3:7)] <- round(show_tab[, c(1, 3:7)], 4)
print(show_tab, row.names = FALSE)

## ---- remedysummary ----
rare <- remedy_tab[remedy_tab$prevalence == min(remedy_tab$prevalence), ]
cat(sprintf("at prevalence %.4f (%d positives):\n", rare$prevalence[1], rare$positives[1]))
cat(sprintf("  AUC spread across the five rules: %.5f\n", max(rare$auc) - min(rare$auc)))
cat(sprintf("  Brier, raw %.4f, resampled %.4f to %.4f\n",
            rare$brier[1], min(rare$brier[3:5]), max(rare$brier[3:5])))
cat(sprintf("  TSS at the rule: raw at 0.5 %.4f, raw tuned %.4f, downsampled %.4f\n",
            rare$tss_used[1], rare$tss_used[2], rare$tss_used[3]))
cat(sprintf("  best TSS available: raw %.4f, downsampled %.4f\n",
            rare$tss_best[1], rare$tss_best[3]))
cat(sprintf("  tuned cut on the raw model: %.4f\n", rare$cut_at[2]))

## ---- remedyfig ----
long_dat <- rbind(
  data.frame(remedy_tab[, c("prevalence", "rule")], metric = "AUC",
             value = remedy_tab$auc),
  data.frame(remedy_tab[, c("prevalence", "rule")], metric = "Brier score",
             value = remedy_tab$brier),
  data.frame(remedy_tab[, c("prevalence", "rule")], metric = "TSS at the rule used",
             value = remedy_tab$tss_used))
long_dat$rule <- factor(long_dat$rule, levels = unique(remedy_tab$rule))
p_rem <- ggplot(long_dat, aes(prevalence, value, colour = rule, shape = rule)) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.6) +
  facet_wrap(~ metric, scales = "free_y") +
  scale_x_log10() +
  scale_colour_manual(values = c(te_pal$ink, te_pal$forest, te_pal$clay,
                                 te_pal$gold, te_pal$sage)) +
  labs(title = "Five rules, one difference that matters",
       x = "prevalence (log scale)", y = NULL, colour = NULL, shape = NULL) +
  theme_te() +
  theme(legend.position = "top") +
  guides(colour = guide_legend(nrow = 2), shape = guide_legend(nrow = 2))
print(p_rem)

## ---- upweight ----
set.seed(2236)
tr_one <- sim_sites(n_train)
ip <- which(tr_one$occ == 1); iq <- which(tr_one$occ == 0)
m_raw <- glm(occ ~ elev + wet, data = tr_one, family = binomial)
up_rows <- c(iq, sample(ip, length(iq), replace = TRUE))
m_up <- glm(occ ~ elev + wet, data = tr_one[up_rows, ], family = binomial)
wgt <- ifelse(tr_one$occ == 1, length(iq) / length(ip), 1)
m_wt <- suppressWarnings(
  glm(occ ~ elev + wet, data = tr_one, family = binomial, weights = wgt))
print(round(rbind(raw = coef(m_raw), upsampled = coef(m_up), weighted = coef(m_wt)), 4))
cat(sprintf("weight ratio %.2f, log of it %.4f, intercept shift of the weighted fit %.4f\n",
            length(iq) / length(ip), log(length(iq) / length(ip)),
            coef(m_wt)[1] - coef(m_raw)[1]))

## ---- separation ----
set.seed(2645)
n_seep <- 12
p_seep <- 0.85
sim_seep <- function() {
  d <- sim_sites(n_train)
  d$seep <- 0
  d$seep[sample.int(n_train, n_seep)] <- 1
  d$occ[d$seep == 1] <- rbinom(n_seep, 1, p_seep)
  d
}
n_draw <- 400
sep_out <- as.data.frame(t(replicate(n_draw, {
  d <- sim_seep()
  n_warn <- 0
  fit <- withCallingHandlers(
    glm(occ ~ elev + wet + seep, data = d, family = binomial),
    warning = function(w) { n_warn <<- n_warn + 1; invokeRestart("muffleWarning") })
  sc <- summary(fit)$coefficients
  c(occupied_seeps = sum(d$occ[d$seep == 1]), est = sc["seep", "Estimate"],
    se = sc["seep", "Std. Error"], warned = as.numeric(n_warn > 0))
})))
cat(sprintf("%d datasets, %d seep sites each, true occupancy at a seep %.2f\n",
            n_draw, n_seep, p_seep))
print(table(sep_out$occupied_seeps))
cat(sprintf("all %d seeps occupied in %.4f of datasets\n",
            n_seep, mean(sep_out$occupied_seeps == n_seep)))
for (kk in c(n_seep, n_seep - 1, n_seep - 2)) {
  sub_out <- sep_out[sep_out$occupied_seeps == kk, ]
  cat(sprintf("%d of %d seeps occupied (%d datasets): median estimate %.2f, median se %.2f\n",
              kk, n_seep, nrow(sub_out), median(sub_out$est), median(sub_out$se)))
}
cat(sprintf("true seep contrast at an average site: %.4f\n", qlogis(p_seep) - b_int))
all_occ <- sep_out$occupied_seeps == n_seep
cat(sprintf("glm warned in %d of %d fits, and in %d of the %d fits with every seep occupied\n",
            sum(sep_out$warned), n_draw, sum(sep_out$warned[all_occ]), sum(all_occ)))

## ---- sepone ----
set.seed(9781)
repeat {
  seep_dat <- sim_seep()
  if (sum(seep_dat$occ[seep_dat$seep == 1]) == n_seep) break
}
sep_warn <- character(0)
fit_sep <- withCallingHandlers(
  glm(occ ~ elev + wet + seep, data = seep_dat, family = binomial),
  warning = function(w) { sep_warn <<- c(sep_warn, conditionMessage(w))
                          invokeRestart("muffleWarning") })
print(round(summary(fit_sep)$coefficients, 3))
cat(sprintf("warnings from this fit: %d\n", length(sep_warn)))
gap_to_one <- 1 - max(fitted(fit_sep))
cat(sprintf("largest fitted probability falls short of 1 by %s; glm warns below %s\n",
            formatC(gap_to_one, format = "e", digits = 2),
            formatC(10 * .Machine$double.eps, format = "e", digits = 2)))
glm_src <- deparse(glm.fit)
stopifnot(any(grepl("eps <- 10 * .Machine$double.eps", glm_src, fixed = TRUE)),
          any(grepl("any(mu > 1 - eps) || any(mu < eps)", glm_src, fixed = TRUE)))
lrt_sep <- drop1(fit_sep, test = "Chisq")
print(lrt_sep)
wald_p_sep <- summary(fit_sep)$coefficients["seep", "Pr(>|z|)"]
lrt_p_sep <- lrt_sep["seep", "Pr(>Chi)"]
seep_fix <- seep_dat
seep_fix$occ[which(seep_fix$seep == 1)[1]] <- 0
fit_fix <- suppressWarnings(glm(occ ~ elev + wet + seep, data = seep_fix, family = binomial))
print(round(summary(fit_fix)$coefficients, 3))
cat(sprintf("one absence added: estimate falls from %.2f to %.2f, se from %.1f to %.2f\n",
            coef(fit_sep)["seep"], coef(fit_fix)["seep"],
            summary(fit_sep)$coefficients["seep", "Std. Error"],
            summary(fit_fix)$coefficients["seep", "Std. Error"]))

## ---- background ----
set.seed(1123)
region <- sim_sites(400000)
occupied <- which(region$occ == 1)
use_pts <- sample(occupied, 600)
cat(sprintf("region %d cells, prevalence %.4f, presence records used %d\n",
            nrow(region), mean(region$occ), length(use_pts)))
bg_grid <- c(2000, 5000, 20000)
bg_tab <- do.call(rbind, lapply(bg_grid, function(nb) {
  bg <- sample.int(nrow(region), nb)
  dd <- rbind(data.frame(region[use_pts, c("elev", "wet")], y_pb = 1),
              data.frame(region[bg, c("elev", "wet")], y_pb = 0))
  fit <- glm(y_pb ~ elev + wet, data = dd, family = binomial)
  data.frame(background = nb, occupied_background = sum(region$occ[bg]),
             intercept = unname(coef(fit)[1]), elev = unname(coef(fit)[2]),
             wet = unname(coef(fit)[3]))
}))
print(round(bg_tab, 4), row.names = FALSE)
cat(sprintf("intercept moves %.4f then %.4f; log background ratios %.4f and %.4f\n",
            bg_tab$intercept[2] - bg_tab$intercept[1],
            bg_tab$intercept[3] - bg_tab$intercept[2],
            log(bg_grid[2] / bg_grid[1]), log(bg_grid[3] / bg_grid[2])))
cat(sprintf("elevation slope %.4f to %.4f against a true %.1f\n",
            min(bg_tab$elev), max(bg_tab$elev), b_elev))
