# Conservation costs and return on investment
# https://tidyecology.com/posts/conservation-costs-and-return/
#
# 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-06

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

## ---- region-generator ----
smooth_pass <- function(z, passes) {
  n <- nrow(z)
  for (p in seq_len(passes)) {
    pad <- rbind(z[1, ], z, z[n, ])
    pad <- cbind(pad[, 1], pad, pad[, n])
    z <- (pad[1:n, 2:(n + 1)] + pad[3:(n + 2), 2:(n + 1)] +
            pad[2:(n + 1), 1:n] + pad[2:(n + 1), 3:(n + 2)] +
            4 * pad[2:(n + 1), 2:(n + 1)]) / 8
  }
  z
}

smooth_field <- function(n, passes, seed) {
  set.seed(seed)
  z <- smooth_pass(matrix(runif(n * n), n, n), passes)
  (z - min(z)) / (max(z) - min(z))
}

zscore <- function(x) (x - mean(x)) / sd(x)

make_region <- function(n_side = 20, n_species = 80, price_link = 0.92,
                        bias = 0.3, med_size = 6, size_sd = 0.8, span = 100,
                        skew = 2.5, price_smooth = 2, seed = 5117) {
  n_units <- n_side * n_side
  gradient <- as.vector(smooth_field(n_side, 5, seed))
  unrelated <- as.vector(smooth_field(n_side, 5, seed + 1))
  set.seed(seed + 2)
  range_size <- pmax(2, pmin(150, round(rlnorm(n_species, log(med_size),
                                               size_sd))))
  pres <- matrix(FALSE, n_units, n_species)
  for (s in seq_len(n_species)) {
    field <- as.vector(smooth_field(n_side, 3, seed + 100 + s))
    pull <- zscore(field) + bias * zscore(gradient)
    pres[order(pull, decreasing = TRUE)[seq_len(range_size[s])], s] <- TRUE
  }
  rich <- rowSums(pres)
  mix <- price_link * zscore(rich) + sqrt(1 - price_link^2) * zscore(unrelated)
  latent <- as.vector(smooth_pass(matrix(mix, n_side, n_side), price_smooth))
  quant <- (rank(latent) - 0.5) / n_units
  price <- 3 * span^(quant^skew)
  list(n_side = n_side, pres = pres, price = price, rich = rich,
       range_size = range_size)
}

## ---- region-summary ----
reg <- make_region()
pres <- reg$pres
price <- reg$price
total <- sum(price)
dear <- order(price, decreasing = TRUE)

cat("planning units:", nrow(pres), " species:", ncol(pres), "\n")
cat("range size, units occupied: min", min(reg$range_size),
    " median", median(reg$range_size), " max", max(reg$range_size), "\n")
cat("species per unit: min", min(reg$rich), " mean", round(mean(reg$rich), 2),
    " max", max(reg$rich), "\n")
cat("price: min", round(min(price), 2), " max", round(max(price), 2),
    " ratio", round(max(price) / min(price), 1), "\n")
cat("total land value:", round(total), "\n")
cat("per cent of total value in the most expensive 10 per cent of units:",
    round(100 * sum(price[dear[1:40]]) / total, 2), "\n")
cat("units buyable for 15 per cent of the total value, cheapest first:",
    sum(cumsum(sort(price)) <= 0.15 * total), "\n")
cat("Spearman correlation, price against species richness:",
    round(cor(price, reg$rich, method = "spearman"), 4), "\n")
cat("species confined to the most expensive quarter of the region:",
    sum(apply(pres, 2, function(s) all(which(s) %in% dear[1:100]))), "\n")

## ---- greedy-engine ----
greedy_plan <- function(pres, price, budget, rule) {
  covered <- rep(FALSE, ncol(pres))
  taken <- rep(FALSE, nrow(pres))
  spent <- 0
  sel <- integer(0)
  repeat {
    if (all(covered)) break
    afford <- !taken & price <= budget - spent + 1e-9
    if (!any(afford)) break
    gain <- rowSums(pres[, !covered, drop = FALSE])
    score <- if (rule == "benefit") gain else
      if (rule == "cheapest") -price else gain / price
    score[!afford] <- -Inf
    if (rule != "cheapest" && max(score) <= 0) break
    pick <- which.max(score)
    taken[pick] <- TRUE
    spent <- spent + price[pick]
    covered <- covered | pres[pick, ]
    sel <- c(sel, pick)
  }
  list(sel = sel, spent = spent, species = sum(covered))
}

## ---- fixed-budget ----
rule_key <- c("benefit", "cheapest", "ratio")
rule_name <- c("new species per unit", "cheapest first",
               "new species per pound")
budget <- 0.15 * total
plan15 <- lapply(rule_key, function(r) greedy_plan(pres, price, budget, r))

tab15 <- data.frame(
  rule = rule_name,
  units = sapply(plan15, function(p) length(p$sel)),
  spent = round(sapply(plan15, function(p) p$spent)),
  species = sapply(plan15, function(p) p$species),
  mean_price = round(sapply(plan15, function(p) mean(price[p$sel])), 1),
  mean_richness = round(sapply(plan15, function(p) mean(reg$rich[p$sel])), 2))
cat("budget, 15 per cent of the total land value:", round(budget), "\n")
print(tab15, row.names = FALSE)
cat("per cent of the region's area bought:",
    round(100 * tab15$units / nrow(pres), 2), "\n")
cat("species ratio, benefit-cost rule over cost-blind rule:",
    round(plan15[[3]]$species / plan15[[1]]$species, 4),
    " extra species:", plan15[[3]]$species - plan15[[1]]$species, "\n")

## ---- fig-selected-units ----
map_df <- data.frame(x = rep(seq_len(reg$n_side), each = reg$n_side),
                     y = rep(seq_len(reg$n_side), times = reg$n_side),
                     price = price)
panels <- c("cost-blind rule: new species per unit",
            "benefit-cost rule: new species per pound")
sel_df <- rbind(data.frame(map_df[plan15[[1]]$sel, c("x", "y")],
                           plan = panels[1]),
                data.frame(map_df[plan15[[3]]$sel, c("x", "y")],
                           plan = panels[2]))
sel_df$plan <- factor(sel_df$plan, levels = panels)
grid_df <- do.call(rbind, lapply(panels, function(p) data.frame(map_df,
                                                               plan = p)))
grid_df$plan <- factor(grid_df$plan, levels = panels)

ggplot(grid_df, aes(x, y)) +
  geom_raster(aes(fill = log10(price))) +
  geom_point(data = sel_df, shape = 21, size = 2.1, stroke = 0.5,
             colour = "white", fill = te_pal$clay) +
  facet_wrap(~plan) +
  coord_equal() +
  scale_fill_gradient(low = te_pal$paper, high = te_pal$forest, name = "price",
                      breaks = log10(c(5, 20, 80, 250)),
                      labels = c(5, 20, 80, 250)) +
  labs(title = "One budget, two reserve networks",
       subtitle = "circles: units bought with 15 per cent of the total land value",
       x = NULL, y = NULL) +
  theme_te() +
  theme(axis.text = element_blank(), panel.grid = element_blank())

## ---- fixed-target ----
plan_full <- lapply(rule_key, function(r) greedy_plan(pres, price, Inf, r))
tabf <- data.frame(
  rule = rule_name,
  units = sapply(plan_full, function(p) length(p$sel)),
  spent = round(sapply(plan_full, function(p) p$spent)),
  percent_of_value = round(100 * sapply(plan_full,
                                        function(p) p$spent) / total, 2))
print(tabf, row.names = FALSE)
cat("cost of full representation, cost-blind over benefit-cost:",
    round(plan_full[[1]]$spent / plan_full[[3]]$spent, 4),
    " cheapest first over benefit-cost:",
    round(plan_full[[2]]$spent / plan_full[[3]]$spent, 4), "\n")

## ---- efficiency-curve ----
fracs <- seq(0.025, 0.6, by = 0.025)
curve_df <- do.call(rbind, lapply(seq_along(rule_key), function(i) {
  data.frame(percent = round(100 * fracs, 3), rule = rule_name[i],
             species = sapply(fracs, function(f)
               greedy_plan(pres, price, f * total, rule_key[i])$species))
}))
curve_df$rule <- factor(curve_df$rule, levels = rule_name)

cat("budget range covered, per cent of total value:",
    min(curve_df$percent), "to", max(curve_df$percent), "\n")
key_rows <- curve_df[curve_df$percent %in% c(5, 15, 40), ]
print(key_rows[order(key_rows$percent), ], row.names = FALSE)
blind <- curve_df[curve_df$rule == rule_name[1], ]
for (i in seq_along(rule_name)) {
  s <- curve_df$species[curve_df$rule == rule_name[i]]
  cat(rule_name[i], "| increasing throughout:", all(diff(s) >= 0), "\n")
}
cat("cost-blind rule at 7.5 and at 10 per cent of the total value:",
    blind$species[blind$percent == 7.5], blind$species[blind$percent == 10],
    "\n")

## ---- fig-efficiency-curve ----
rule_cols <- c(te_pal$clay, te_pal$gold, te_pal$forest)
names(rule_cols) <- rule_name

ggplot(curve_df, aes(percent, species, colour = rule)) +
  geom_hline(yintercept = 80, linetype = "dashed", colour = te_pal$sage) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 1.6) +
  scale_colour_manual(values = rule_cols, name = NULL) +
  labs(title = "Species represented against the budget",
       subtitle = "dashed line: all 80 species in the region",
       x = "budget, per cent of the total land value",
       y = "species represented") +
  theme_te() +
  theme(legend.position = "bottom")

## ---- correlation-sweep ----
links <- c(-0.92, -0.5, 0, 0.5, 0.92)
sweep_df <- do.call(rbind, lapply(links, function(k) {
  rg <- make_region(price_link = k)
  tt <- sum(rg$price)
  blind_full <- greedy_plan(rg$pres, rg$price, Inf, "benefit")$spent / tt
  do.call(rbind, lapply(c(0.02, 0.15), function(f) {
    a <- greedy_plan(rg$pres, rg$price, f * tt, "benefit")$species
    b <- greedy_plan(rg$pres, rg$price, f * tt, "ratio")$species
    data.frame(correlation = round(cor(rg$price, rg$rich,
                                       method = "spearman"), 3),
               budget_percent = 100 * f, cost_blind = a, benefit_cost = b,
               gain = round(b / a, 3),
               blind_full_percent = round(100 * blind_full, 2))
  }))
}))
print(sweep_df, row.names = FALSE)
cat("total land value, identical at every mixing weight:",
    round(sum(make_region(price_link = -0.92)$price)),
    round(sum(make_region(price_link = 0.92)$price)), "\n")

## ---- fig-cost-correlation-gain ----
sweep_df$panel <- factor(paste("budget", sweep_df$budget_percent,
                               "per cent of land value"),
                         levels = c("budget 2 per cent of land value",
                                    "budget 15 per cent of land value"))
budget_cols <- c(te_pal$forest, te_pal$clay)
names(budget_cols) <- levels(sweep_df$panel)

ggplot(sweep_df, aes(correlation, gain, colour = panel)) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = te_pal$sage) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.4) +
  scale_colour_manual(values = budget_cols, name = NULL) +
  scale_x_continuous(expand = expansion(mult = 0.08)) +
  labs(title = "The gain depends on how price and richness line up",
       subtitle = "dashed line: dividing by price bought no extra species",
       x = "Spearman correlation, unit price against species richness",
       y = "gain in species represented") +
  theme_te() +
  theme(legend.position = "bottom")
