# Niche overlap and the background
# https://tidyecology.com/posts/niche-overlap-and-the-background/
#
# 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)

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "#e7e6da", linewidth = 0.3),
      plot.title = element_text(face = "bold", size = 13),
      axis.title = element_text(colour = "#46604a"),
      strip.text = element_text(face = "bold", colour = "#275139")
    )
}
paper_forest <- c("#f5f4ee", "#c9b458", "#2f8f63", "#1d5b4e")

## ---- prefs ----
gx <- 60; gy <- 60
temp  <- seq(5, 25, length.out = gx)
moist <- seq(0, 1, length.out = gy)
grid  <- expand.grid(temp = temp, moist = moist)
schoener_D <- function(p, q) sum(pmin(p, q))

prefA <- with(grid, dnorm(temp, 13, 2.5) * dnorm(moist, 0.5, 0.14))
prefB <- with(grid, dnorm(temp, 17, 2.5) * dnorm(moist, 0.5, 0.14))
prefA <- prefA / sum(prefA); prefB <- prefB / sum(prefB)
D_fund <- schoener_D(prefA, prefB)

occ       <- function(pref, av) { d <- pref * av; d / sum(d) }
corrected <- function(occd, av) { r <- occd / pmax(av, 1e-12); r / sum(r) }

## ---- fig-occupied ----
av_narrow <- with(grid, dnorm(temp, 15, 1.5) * dnorm(moist, 0.5, 0.30)); av_narrow <- av_narrow / sum(av_narrow)
av_broad  <- with(grid, dnorm(temp, 15, 6.0) * dnorm(moist, 0.5, 0.30)); av_broad  <- av_broad  / sum(av_broad)
df_occ <- rbind(
  data.frame(grid, dens = occ(prefA, av_narrow), species = "Species A", bg = "Narrow background"),
  data.frame(grid, dens = occ(prefB, av_narrow), species = "Species B", bg = "Narrow background"),
  data.frame(grid, dens = occ(prefA, av_broad),  species = "Species A", bg = "Broad background"),
  data.frame(grid, dens = occ(prefB, av_broad),  species = "Species B", bg = "Broad background")
)
df_occ$bg <- factor(df_occ$bg, levels = c("Narrow background", "Broad background"))
ggplot(df_occ, aes(temp, moist, fill = dens)) +
  geom_raster() +
  facet_grid(bg ~ species) +
  scale_fill_gradientn(colours = paper_forest, name = "density") +
  labs(title = "Fixed preferences, two backgrounds",
       x = "temperature", y = "moisture") +
  theme_te()

## ---- sweep ----
sds <- c(1.0, 1.5, 2.5, 4, 6, 10)
D_raw <- D_cor <- numeric(length(sds))
for (i in seq_along(sds)) {
  av <- with(grid, dnorm(temp, 15, sds[i]) * dnorm(moist, 0.5, 0.30)); av <- av / sum(av)
  oA <- occ(prefA, av); oB <- occ(prefB, av)
  D_raw[i] <- schoener_D(oA, oB)
  D_cor[i] <- schoener_D(corrected(oA, av), corrected(oB, av))
}
raw_span <- max(D_raw) - min(D_raw)
cor_span <- max(D_cor) - min(D_cor)

## ---- fig-breadth ----
sw <- rbind(
  data.frame(sd = sds, D = D_raw, kind = "Raw overlap"),
  data.frame(sd = sds, D = D_cor, kind = "Corrected (preference)")
)
ggplot(sw, aes(sd, D, colour = kind)) +
  geom_hline(yintercept = D_fund, linetype = "dashed", colour = "#8a8f83") +
  geom_line(linewidth = 0.9) + geom_point(size = 2.4) +
  scale_x_continuous(transform = "log2", breaks = sds) +
  scale_colour_manual(values = c("Raw overlap" = "#b5534e", "Corrected (preference)" = "#275139"), name = NULL) +
  scale_y_continuous(limits = c(0.4, 0.8)) +
  labs(title = "The background drives the raw overlap",
       x = "background breadth (availability SD, log scale)", y = "Schoener's D") +
  theme_te() + theme(legend.position = "top")

## ---- bias-var ----
av_b <- with(grid, dnorm(temp, 15, 4) * dnorm(moist, 0.5, 0.30)); av_b <- av_b / sum(av_b)
oA <- occ(prefA, av_b); oB <- occ(prefB, av_b)
St <- { d <- outer(temp, temp, "-"); K <- exp(-0.5 * (d / 2)^2); K / rowSums(K) }
Sm <- { d <- outer(moist, moist, "-"); K <- exp(-0.5 * (d / 0.10)^2); K / rowSums(K) }
ndens <- function(pt, pm) {
  it <- findInterval(pt, c(-Inf, (temp[-1] + temp[-gx]) / 2, Inf))
  im <- findInterval(pm, c(-Inf, (moist[-1] + moist[-gy]) / 2, Inf))
  cnt <- matrix(0, gy, gx); for (k in seq_along(it)) cnt[im[k], it[k]] <- cnt[im[k], it[k]] + 1
  # t() puts the cells back in expand.grid order (temperature varying fastest)
  d <- Sm %*% cnt %*% t(St); as.vector(t(pmax(d, 0))) / sum(d)
}
set.seed(606)
reps <- 200; n <- 100; raw <- cor_ <- numeric(reps)
for (i in 1:reps) {
  ia <- sample.int(nrow(grid), n, replace = TRUE, prob = oA)
  ib <- sample.int(nrow(grid), n, replace = TRUE, prob = oB)
  da <- ndens(grid$temp[ia], grid$moist[ia]); db <- ndens(grid$temp[ib], grid$moist[ib])
  raw[i]  <- schoener_D(da, db)
  cor_[i] <- schoener_D(corrected(da, av_b), corrected(db, av_b))
}
raw_m <- mean(raw); raw_s <- sd(raw); cor_m <- mean(cor_); cor_s <- sd(cor_)
var_amp <- cor_s / raw_s
