# Range size distributions
# https://tidyecology.com/posts/range-size-distributions/
#
# 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-08

## ---- 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 = te_pal$ink),
          legend.position = "bottom")
}

## ---- atlas ----
set.seed(20260725)

nx <- 128
ny <- 128
cell_km <- 2
cell_area <- cell_km^2
gx <- rep(seq_len(nx), ny)
gy <- rep(seq_len(ny), each = nx)
n_cell <- nx * ny
region_area <- n_cell * cell_area
n_sp <- 200

# whole numbers quoted in the prose are written out in full rather than in R's
# scientific shorthand, so that 65536 does not turn up as 6.5536e4
n0 <- function(x) format(round(unname(x)), scientific = FALSE, trim = TRUE)

smooth_field <- function(nk = 5) {
  f <- numeric(n_cell)
  for (k in seq_len(nk)) {
    u <- sample(1:3, 1)
    v <- sample(1:3, 1)
    ph <- runif(2, 0, 2 * pi)
    a <- rnorm(1)
    f <- f + a * cos(2 * pi * u * gx / nx + ph[1]) *
      cos(2 * pi * v * gy / ny + ph[2])
  }
  as.numeric(scale(f))
}
E1 <- smooth_field()
E2 <- smooth_field()

ctr <- sample(n_cell, n_sp, replace = TRUE)
m1 <- E1[ctr] + rnorm(n_sp, 0, 0.2)
m2 <- E2[ctr] + rnorm(n_sp, 0, 0.2)
tol <- exp(rnorm(n_sp, log(0.85), 0.55))
rad <- exp(rnorm(n_sp, log(11), 1.0))
hold <- runif(n_sp, 0.25, 0.95)
n_out <- rbinom(n_sp, 3, 0.16)

occ <- vector("list", n_sp)
for (i in seq_len(n_sp)) {
  dg <- sqrt((gx - gx[ctr[i]])^2 + (gy - gy[ctr[i]])^2)
  de <- sqrt((E1 - m1[i])^2 + (E2 - m2[i])^2)
  p <- hold[i] * exp(-de^2 / (2 * tol[i]^2)) * exp(-dg^2 / (2 * rad[i]^2))
  keep <- which(runif(n_cell) < p)
  if (!length(keep)) keep <- ctr[i]
  if (n_out[i] > 0) {
    ang <- runif(n_out[i], 0, 2 * pi)
    rr <- rad[i] * runif(n_out[i], 2, 4)
    ox <- pmin(nx, pmax(1, round(gx[ctr[i]] + rr * cos(ang))))
    oy <- pmin(ny, pmax(1, round(gy[ctr[i]] + rr * sin(ang))))
    keep <- unique(c(keep, (oy - 1) * nx + ox))
  }
  occ[[i]] <- keep
}
nocc <- lengths(occ)
aoo <- nocc * cell_area

round(c(species = n_sp, grid_cells = n_cell, cell_side_km = cell_km,
        cell_area_km2 = cell_area, region_area_km2 = region_area,
        smallest_aoo_km2 = min(aoo), median_aoo_km2 = median(aoo),
        largest_aoo_km2 = max(aoo),
        species_in_a_single_cell = sum(nocc == 1),
        widest_species_share_of_region = max(aoo) / region_area,
        mean_of_log_aoo = mean(log(aoo)), sd_of_log_aoo = sd(log(aoo))), 4)
print(round(quantile(aoo, c(0.05, 0.25, 0.5, 0.75, 0.95)), 1))

## ---- hull ----
poly_area <- function(x, y) {
  n <- length(x)
  if (n < 3) return(NA_real_)
  j <- c(n, seq_len(n - 1))
  abs(sum(x[j] * y - x * y[j])) / 2
}

hull_area <- function(x, y) {
  if (length(x) < 3) return(NA_real_)
  h <- chull(x, y)
  if (length(h) < 3) return(NA_real_)
  poly_area(x[h], y[h])
}

sq_x <- c(0, 10, 10, 0)
sq_y <- c(0, 0, 10, 10)
tri_x <- c(0, 30, 0)
tri_y <- c(0, 0, 20)

round(c(square_from_the_shoelace = poly_area(sq_x, sq_y),
        square_exact = 10 * 10,
        square_with_the_vertices_reversed = poly_area(rev(sq_x), rev(sq_y)),
        triangle_from_the_shoelace = poly_area(tri_x, tri_y),
        triangle_exact = 30 * 20 / 2,
        square_plus_an_interior_point = hull_area(c(sq_x, 5), c(sq_y, 5)),
        two_points_only = hull_area(c(0, 1), c(0, 1))), 4)

eoo <- vapply(occ, function(k) hull_area(gx[k] * cell_km, gy[k] * cell_km), 1)
packing <- aoo / eoo
n_no_hull <- sum(is.na(eoo))

round(c(species_with_a_defined_eoo = sum(!is.na(eoo)),
        species_with_fewer_than_three_cells = n_no_hull,
        median_eoo_km2 = median(eoo, na.rm = TRUE),
        smallest_eoo_km2 = min(eoo, na.rm = TRUE),
        largest_eoo_km2 = max(eoo, na.rm = TRUE),
        median_eoo_over_aoo = median(eoo / aoo, na.rm = TRUE),
        smallest_eoo_over_aoo = min(eoo / aoo, na.rm = TRUE),
        largest_eoo_over_aoo = max(eoo / aoo, na.rm = TRUE)), 4)

## ---- pair ----
cand <- which(nocc >= 100 & nocc <= 400 & !is.na(eoo))
sp_tight <- cand[which.max(packing[cand])]
sp_loose <- cand[which.min(packing[cand])]
pair_aoo_ratio <- aoo[sp_loose] / aoo[sp_tight]
pair_eoo_ratio <- eoo[sp_loose] / eoo[sp_tight]

round(c(tight_species = sp_tight, tight_cells = nocc[sp_tight],
        tight_aoo_km2 = aoo[sp_tight], tight_eoo_km2 = eoo[sp_tight],
        tight_eoo_over_aoo = eoo[sp_tight] / aoo[sp_tight],
        loose_species = sp_loose, loose_cells = nocc[sp_loose],
        loose_aoo_km2 = aoo[sp_loose], loose_eoo_km2 = eoo[sp_loose],
        loose_eoo_over_aoo = eoo[sp_loose] / aoo[sp_loose],
        ratio_of_the_two_aoo = pair_aoo_ratio,
        ratio_of_the_two_eoo = pair_eoo_ratio), 4)

## ---- fig-map ----
map_one <- function(i, lab) {
  k <- occ[[i]]
  h <- chull(gx[k], gy[k])
  rbind(data.frame(x = gx[k] * cell_km, y = gy[k] * cell_km, part = "cell",
                   panel = lab),
        data.frame(x = gx[k][h] * cell_km, y = gy[k][h] * cell_km,
                   part = "hull", panel = lab))
}
lab_tight <- "Tightly packed species"
lab_loose <- "Loosely packed species"
md <- rbind(map_one(sp_tight, lab_tight), map_one(sp_loose, lab_loose))
md$panel <- factor(md$panel, levels = c(lab_tight, lab_loose))

# the occupied patch is small against a 256 km square, so each panel states its
# own cell count and hull area rather than leaving them to be judged by eye
say <- function(i) sprintf("%s cells, %s km2 occupied\nhull %s km2",
                           n0(nocc[i]), n0(aoo[i]), n0(eoo[i]))
map_lab <- data.frame(x = 248, y = 6, panel = factor(c(lab_tight, lab_loose),
                                                     levels = c(lab_tight, lab_loose)),
                      txt = c(say(sp_tight), say(sp_loose)))

ggplot() +
  geom_tile(data = md[md$part == "cell", ],
            aes(x, y, fill = "Occupied 2 km cell"),
            width = cell_km, height = cell_km, colour = te_pal$forest,
            linewidth = 0.35) +
  geom_polygon(data = md[md$part == "hull", ],
               aes(x, y, colour = "Convex hull (extent of occurrence)"),
               fill = NA, linewidth = 0.7) +
  geom_text(data = map_lab, aes(x, y, label = txt), hjust = 1, vjust = 0,
            size = 2.9, lineheight = 0.95, colour = te_pal$ink) +
  facet_wrap(~panel) +
  coord_fixed(xlim = c(0, nx * cell_km), ylim = c(0, ny * cell_km)) +
  scale_fill_manual(values = te_pal$forest, name = NULL) +
  scale_colour_manual(values = te_pal$clay, name = NULL) +
  scale_x_continuous(breaks = seq(0, 256, 64)) +
  scale_y_continuous(breaks = seq(0, 256, 64)) +
  labs(x = "Easting (km)", y = "Northing (km)",
       title = "Same area of occupancy, very different extent") +
  theme_te() +
  theme(strip.text = element_text(colour = te_pal$ink, face = "bold",
                                  size = 9),
        legend.box = "vertical",
        legend.margin = margin(0, 0, 0, 0),
        plot.margin = margin(6, 12, 6, 6))

## ---- fit ----
set.seed(4404)

y <- log(aoo)
mu <- mean(y)
sigma <- sqrt(mean((y - mu)^2))
ll_lnorm <- sum(dlnorm(aoo, mu, sigma, log = TRUE))

fit_loglogis <- function(a) {
  yy <- log(a)
  optim(c(mean(yy), log(sd(yy) * sqrt(3) / pi)),
        function(p) -sum(dlogis(yy, p[1], exp(p[2]), log = TRUE) - yy),
        method = "Nelder-Mead")
}
f_ll <- fit_loglogis(aoo)
loc <- f_ll$par[1]
scl <- exp(f_ll$par[2])
ll_llogis <- -f_ll$value
d_atlas <- 2 * (ll_lnorm - ll_llogis)

prod6 <- apply(matrix(runif(n_sp * 6, 0.15, 2.2), ncol = 6), 1, prod)
alt <- exp(mu + sigma * (log(prod6) - mean(log(prod6))) / sd(log(prod6)))
ya <- log(alt)
mu_a <- mean(ya)
sig_a <- sqrt(mean((ya - mu_a)^2))
d_alt <- 2 * (sum(dlnorm(alt, mu_a, sig_a, log = TRUE)) +
                fit_loglogis(alt)$value)

nq <- qnorm(ppoints(n_sp))
qq_atlas <- cor(sort(y), nq)
qq_alt <- cor(sort(ya), nq)

round(c(lognormal_mu = mu, lognormal_sigma = sigma,
        lognormal_loglik = ll_lnorm,
        loglogistic_location = loc, loglogistic_scale = scl,
        loglogistic_loglik = ll_llogis,
        parameters_in_each = 2,
        delta_aic_atlas = d_atlas,
        delta_aic_multiplicative_sample = d_alt,
        normal_qq_correlation_atlas = qq_atlas,
        normal_qq_correlation_multiplicative = qq_alt,
        skew_of_log_aoo = mean((y - mu)^3) / sd(y)^3,
        skew_of_the_multiplicative_sample = mean((ya - mu_a)^3) / sd(ya)^3,
        optimiser_converged = f_ll$convergence), 4)

## ---- recover ----
set.seed(1808)

pick <- function(a) {
  yy <- log(a)
  m <- mean(yy)
  s <- sqrt(mean((yy - m)^2))
  c(sum(dlnorm(a, m, s, log = TRUE)), -fit_loglogis(a)$value)
}

n_rep <- 400
right <- matrix(NA, n_rep, 2)
gap <- numeric(n_rep)
for (r in seq_len(n_rep)) {
  v1 <- pick(rlnorm(n_sp, mu, sigma))
  v2 <- pick(exp(rlogis(n_sp, loc, scl)))
  right[r, 1] <- v1[1] > v1[2]
  right[r, 2] <- v2[2] > v2[1]
  gap[r] <- 2 * (v1[1] - v1[2])
}
pc_lnorm <- 100 * mean(right[, 1])
pc_llogis <- 100 * mean(right[, 2])
pc_both <- 100 * mean(right)
med_gap <- median(gap)

round(c(replicates = n_rep, species_per_replicate = n_sp,
        percent_correct_when_lognormal_is_true = pc_lnorm,
        percent_correct_when_loglogistic_is_true = pc_llogis,
        percent_correct_overall = pc_both,
        median_delta_aic_when_lognormal_is_true = med_gap,
        lower_quartile_of_that_delta = quantile(gap, 0.25),
        observed_delta_aic_in_the_atlas = d_atlas), 4)

## ---- fig-dist ----
xs <- seq(min(log10(c(aoo, alt))) - 0.3, max(log10(c(aoo, alt))) + 0.3,
          length.out = 400)
keys <- c("Lognormal fit", "Log-logistic fit", "Multiplicative sample")
curve_df <- data.frame(
  x = rep(xs, 2),
  d = c(log(10) * dnorm(xs * log(10), mu, sigma),
        log(10) * dlogis(xs * log(10), loc, scl)),
  fit = factor(rep(keys[1:2], each = length(xs)), levels = keys))
alt_df <- data.frame(x = log10(alt), fit = factor(keys[3], levels = keys))
key_col <- c(te_pal$forest, te_pal$gold, te_pal$clay)
names(key_col) <- keys
key_lty <- c(1, 2, 1)
names(key_lty) <- keys

ggplot() +
  geom_histogram(data = data.frame(x = log10(aoo)),
                 aes(x, after_stat(density), fill = "Simulated atlas"),
                 binwidth = 0.25, boundary = 0, colour = NA, alpha = 0.9) +
  geom_histogram(data = alt_df,
                 aes(x, after_stat(density), colour = fit, linetype = fit),
                 binwidth = 0.25, boundary = 0, fill = NA, linewidth = 0.6) +
  geom_line(data = curve_df, aes(x, d, colour = fit, linetype = fit),
            linewidth = 0.9) +
  scale_fill_manual(values = te_pal$sage, name = NULL) +
  scale_colour_manual(values = key_col, name = NULL) +
  scale_linetype_manual(values = key_lty, name = NULL) +
  scale_x_continuous(breaks = 0:5,
                     labels = format(10^(0:5), scientific = FALSE,
                                     trim = TRUE, big.mark = "")) +
  labs(x = "Area of occupancy (km2, log scale)", y = "Density per log10 unit",
       title = "Two processes, one histogram") +
  theme_te() +
  theme(legend.box = "vertical",
        legend.margin = margin(0, 0, 0, 0),
        plot.margin = margin(6, 14, 6, 6))

## ---- grain ----
grains <- c(1, 2, 4, 8)
side_km <- grains * cell_km
log_area <- log(side_km^2)

aoo_at <- function(k, b) {
  length(unique(((gx[k] - 1) %/% b) + ((gy[k] - 1) %/% b) * (nx / b))) *
    (b * cell_km)^2
}
A <- sapply(grains, function(b) vapply(occ, aoo_at, 1, b = b))
colnames(A) <- paste0(side_km, "km")

slope_of <- function(v) {
  sum((log_area - mean(log_area)) * (log(v) - mean(log(v)))) /
    sum((log_area - mean(log_area))^2)
}
expo <- apply(A, 1, slope_of)

contig <- vapply(occ, function(k) {
  o <- matrix(FALSE, nx + 2, ny + 2)          # one empty cell of padding on every side
  x <- gx[k] + 1
  y <- gy[k] + 1
  o[cbind(x, y)] <- TRUE
  mean(o[cbind(x + 1, y)] | o[cbind(x - 1, y)] |
         o[cbind(x, y + 1)] | o[cbind(x, y - 1)])
}, 1)

sd_grain <- apply(log(A), 2, sd)
# what the box plot below actually draws, so the caption can name the right part
# of it: the box is the interquartile range, the whiskers the 1.5 IQR reach
iqr_grain <- apply(log10(A), 2, IQR)
whisk_grain <- apply(log10(A), 2, function(v) diff(range(boxplot.stats(v)$stats)))
thr <- apply(A, 2, function(v) c(below_2000 = sum(v < 2000),
                                 below_500 = sum(v < 500)))

print(round(apply(A, 2, median), 1))
print(round(sd_grain, 4))
print(round(rbind(interquartile_range = iqr_grain,
                  whisker_span = whisk_grain), 4))
print(thr)

round(c(exponent_tight_species = expo[sp_tight],
        exponent_loose_species = expo[sp_loose],
        contiguity_tight = contig[sp_tight],
        contiguity_loose = contig[sp_loose],
        aoo_ratio_at_2km = pair_aoo_ratio,
        aoo_ratio_at_16km = A[sp_loose, 4] / A[sp_tight, 4],
        smallest_exponent = min(expo), largest_exponent = max(expo),
        median_exponent = median(expo),
        coarse_grid_cells = n_cell / 64,
        widest_species_share_of_the_coarse_grid =
          max(A[, 4]) / region_area), 4)

## ---- grain-model ----
m_expo <- lm(expo ~ log(aoo) + contig)
cf <- coef(m_expo)
r2_expo <- summary(m_expo)$r.squared
rho_grain <- cor(A[, 1], A[, 4], method = "spearman")

r1 <- rank(-A[, 1], ties.method = "min")
r4 <- rank(-A[, 4], ties.method = "min")
riser <- which.max(r1 - r4)
gained <- r1[riser] - r4[riser]

round(c(intercept = cf[[1]], slope_on_log_aoo = cf[[2]],
        slope_on_contiguity = cf[[3]], r_squared = r2_expo,
        lowest_contiguity = min(contig), highest_contiguity = max(contig),
        spearman_2km_against_16km = rho_grain,
        biggest_riser = riser,
        its_rank_at_2km = r1[riser], its_rank_at_16km = r4[riser],
        places_gained = gained,
        its_contiguity = contig[riser], its_exponent = expo[riser],
        its_aoo_at_2km = A[riser, 1], its_aoo_at_16km = A[riser, 4]), 4)

## ---- fig-grain ----
box_df <- data.frame(
  grain = factor(rep(colnames(A), each = n_sp), levels = colnames(A)),
  laoo = as.numeric(log10(A)))

trace_lab <- c("Tightly packed species", "Loosely packed species",
               "Largest rank gain")
trace_df <- data.frame(
  grain = factor(rep(colnames(A), 3), levels = colnames(A)),
  laoo = log10(c(A[sp_tight, ], A[sp_loose, ], A[riser, ])),
  who = factor(rep(trace_lab, each = length(grains)), levels = trace_lab))

ggplot() +
  geom_boxplot(data = box_df, aes(grain, laoo), fill = te_pal$line,
               colour = te_pal$ink, width = 0.5,
               outlier.size = 0.9, outlier.colour = te_pal$ink) +
  geom_line(data = trace_df, aes(grain, laoo, colour = who, group = who),
            linewidth = 0.9) +
  geom_point(data = trace_df, aes(grain, laoo, colour = who), size = 2.6) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$clay, te_pal$gold),
                      name = NULL) +
  labs(x = "Grid cell side (km)", y = "log10 area of occupancy (km2)",
       title = "Coarsening the grid reorders the species") +
  theme_te() +
  theme(plot.margin = margin(6, 14, 6, 6))

## ---- effort ----
set.seed(9312)

levels_rec <- c(5, 10, 20, 40, 80, 160, 320)
qa <- quantile(aoo, c(0.25, 0.75))

sweep_one <- function(L) {
  ra <- numeric(n_sp)
  re <- rep(NA_real_, n_sp)
  for (i in seq_len(n_sp)) {
    k <- occ[[i]]
    u <- unique(k[sample.int(length(k), L, replace = TRUE)])
    ra[i] <- length(u) * cell_area
    re[i] <- hull_area(gx[u] * cell_km, gy[u] * cell_km)
  }
  small <- aoo <= qa[1]
  big <- aoo >= qa[2]
  c(records = L,
    aoo_all = mean(ra / aoo), eoo_all = mean(re / eoo, na.rm = TRUE),
    aoo_small = mean((ra / aoo)[small]),
    eoo_small = mean((re / eoo)[small], na.rm = TRUE),
    aoo_big = mean((ra / aoo)[big]),
    eoo_big = mean((re / eoo)[big], na.rm = TRUE),
    eoo_undefined = sum(is.na(re) & !is.na(eoo)))
}
sw <- t(vapply(levels_rec, sweep_one, numeric(8)))
rownames(sw) <- paste0(levels_rec, " records")
print(round(sw, 4))

## ---- fig-effort ----
grp <- c("All species", "Narrowest quarter", "Widest quarter")
eff_df <- data.frame(
  records = log2(rep(sw[, "records"], 6)),
  ratio = c(sw[, "aoo_all"], sw[, "aoo_small"], sw[, "aoo_big"],
            sw[, "eoo_all"], sw[, "eoo_small"], sw[, "eoo_big"]),
  measure = factor(rep(c("Area of occupancy", "Extent of occurrence"),
                       each = 3 * nrow(sw)),
                   levels = c("Area of occupancy", "Extent of occurrence")),
  panel = factor(rep(rep(grp, each = nrow(sw)), 2), levels = grp))

truth_lab <- data.frame(records = log2(min(levels_rec)), ratio = 1.045,
                        panel = factor(grp[1], levels = grp))

ggplot(eff_df, aes(records, ratio, colour = measure, shape = measure,
                   linetype = measure)) +
  geom_hline(yintercept = 1, linetype = 2, colour = te_pal$ink,
             linewidth = 0.5) +
  geom_text(data = truth_lab, aes(records, ratio), label = "truth",
            inherit.aes = FALSE, hjust = 0, vjust = 0, size = 3.1,
            colour = te_pal$ink) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.4) +
  facet_wrap(~panel) +
  scale_colour_manual(values = c(te_pal$forest, te_pal$gold), name = NULL) +
  scale_shape_manual(values = c(16, 17), name = NULL) +
  scale_linetype_manual(values = c(1, 2), name = NULL) +
  scale_x_continuous(breaks = log2(levels_rec), labels = levels_rec) +
  scale_y_continuous(limits = c(0, 1.1), breaks = seq(0, 1, 0.25)) +
  labs(x = "Records per species", y = "Estimated over true range size",
       title = "Both measures are biased down, at different rates") +
  theme_te() +
  theme(strip.text = element_text(colour = te_pal$ink, face = "bold",
                                  size = 9),
        plot.margin = margin(6, 14, 6, 6))

## ---- atlas-effort ----
set.seed(2026)

lambda <- 0.20 * nocc^1.25 * exp(rnorm(n_sp, 0, 0.6))
n_rec <- rpois(n_sp, lambda)

est_a <- numeric(n_sp)
est_e <- rep(NA_real_, n_sp)
for (i in seq_len(n_sp)) {
  if (n_rec[i] == 0) next
  k <- occ[[i]]
  u <- unique(k[sample.int(length(k), n_rec[i], replace = TRUE)])
  est_a[i] <- length(u) * cell_area
  est_e[i] <- hull_area(gx[u] * cell_km, gy[u] * cell_km)
}
qtl <- cut(aoo, quantile(aoo, 0:4 / 4), include.lowest = TRUE,
           labels = c("Q1 narrowest", "Q2", "Q3", "Q4 widest"))
by_q <- rbind(
  median_records = tapply(n_rec, qtl, median),
  records_per_occupied_cell = round(tapply(n_rec / nocc, qtl, median), 4),
  mean_aoo_ratio = round(tapply(est_a / aoo, qtl, mean), 4),
  mean_eoo_ratio = round(tapply(est_e / eoo, qtl,
                                function(z) mean(z, na.rm = TRUE)), 4))
print(by_q)

pushed_2000 <- sum(aoo >= 2000 & est_a < 2000)
pushed_500 <- sum(aoo >= 500 & est_a < 500)
lost_hull <- sum(is.na(est_e))

round(c(total_records = sum(n_rec), fewest_records = min(n_rec),
        median_records = median(n_rec), most_records = max(n_rec),
        species_with_no_records = sum(n_rec == 0),
        eoo_undefined_after_thinning = lost_hull,
        true_below_2000 = sum(aoo < 2000),
        estimated_below_2000 = sum(est_a < 2000),
        true_below_500 = sum(aoo < 500),
        estimated_below_500 = sum(est_a < 500),
        pushed_below_2000_by_effort = pushed_2000,
        pushed_above_2000_by_effort = sum(aoo < 2000 & est_a >= 2000),
        pushed_below_500_by_effort = pushed_500,
        pushed_above_500_by_effort = sum(aoo < 500 & est_a >= 500)), 4)

## ---- eoo-aoo ----
ok <- !is.na(eoo)
ratio <- eoo / aoo
dense <- which(ratio == min(ratio, na.rm = TRUE))
sparse <- which(ratio == max(ratio, na.rm = TRUE))
r_log <- cor(log(aoo[ok]), log(eoo[ok]))
rho <- cor(aoo[ok], eoo[ok], method = "spearman")
q_lo <- quantile(ratio, 0.05, na.rm = TRUE)
q_hi <- quantile(ratio, 0.95, na.rm = TRUE)

round(c(species_compared = sum(ok),
        pearson_on_logs = r_log, spearman = rho,
        median_eoo_over_aoo = median(ratio, na.rm = TRUE),
        eoo_over_aoo_5th_percentile = q_lo,
        eoo_over_aoo_95th_percentile = q_hi,
        spread_of_that_ratio = q_hi / q_lo,
        densest_species = dense, densest_cells = nocc[dense],
        densest_aoo_km2 = aoo[dense], densest_eoo_km2 = eoo[dense],
        sparsest_species = sparse, sparsest_cells = nocc[sparse],
        sparsest_aoo_km2 = aoo[sparse], sparsest_eoo_km2 = eoo[sparse],
        sparsest_eoo_over_aoo = ratio[sparse]), 4)

## ---- tail ----
set.seed(5150)

n_boot <- 2000
boot <- t(replicate(n_boot, {
  s <- sample(n_sp, n_sp, replace = TRUE)
  yy <- y[s]
  m <- mean(yy)
  v <- sqrt(mean((yy - m)^2))
  c(v, exp(qnorm(0.05, m, v)), mean(exp(yy) < 2000), mean(exp(yy) < 500))
}))

q05 <- exp(qnorm(0.05, mu, sigma))
ci <- apply(boot, 2, quantile, c(0.025, 0.975))
n_in_tail <- sum(aoo <= q05)

round(c(bootstrap_replicates = n_boot,
        sigma = sigma, sigma_low = ci[1, 1], sigma_high = ci[2, 1],
        fitted_5th_percentile_km2 = q05,
        fitted_5th_percentile_low = ci[1, 2],
        fitted_5th_percentile_high = ci[2, 2],
        width_as_a_ratio = ci[2, 2] / ci[1, 2],
        species_at_or_below_the_fitted_5th_percentile = n_in_tail,
        share_below_2000 = mean(aoo < 2000),
        share_below_2000_low = ci[1, 3],
        share_below_2000_high = ci[2, 3],
        share_below_500 = mean(aoo < 500),
        share_below_500_low = ci[1, 4],
        share_below_500_high = ci[2, 4]), 4)
