# Niche overlap: Schoener’s D and Warren’s I
# https://tidyecology.com/posts/measuring-niche-overlap/
#
# 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-15

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

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)

# availability: how much of each environment exists in the study region
avail <- with(grid, dnorm(temp, 15, 4) * dnorm(moist, 0.5, 0.22))
avail <- avail / sum(avail)

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

## ---- densities ----
occ_density <- function(t0, m0, st = 2.5, sm = 0.14) {
  d <- avail * with(grid, dnorm(grid$temp, t0, st) * dnorm(grid$moist, m0, sm))
  d / sum(d)
}
A <- occ_density(14, 0.42)
B <- occ_density(17, 0.52)
C <- occ_density(22, 0.80)

## ---- fig-surfaces ----
df <- rbind(
  data.frame(grid, dens = A, species = "Species A"),
  data.frame(grid, dens = B, species = "Species B"),
  data.frame(grid, dens = C, species = "Species C")
)
ggplot(df, aes(temp, moist, fill = dens)) +
  geom_raster() +
  facet_wrap(~species) +
  scale_fill_gradientn(colours = paper_forest, name = "density") +
  labs(title = "Three species in environmental space",
       x = "temperature", y = "moisture") +
  theme_te() +
  theme(legend.position = "right")

## ---- metrics ----
schoener_D <- function(p, q) sum(pmin(p, q))               # intersection
warren_I   <- function(p, q) sum(sqrt(p * q))              # Bhattacharyya coefficient
D_formula  <- function(p, q) 1 - 0.5 * sum(abs(p - q))
I_formula  <- function(p, q) 1 - 0.5 * sum((sqrt(p) - sqrt(q))^2)

gap_D <- max(abs(c(schoener_D(A, B) - D_formula(A, B),
                   schoener_D(A, C) - D_formula(A, C))))
gap_I <- max(abs(c(warren_I(A, B) - I_formula(A, B),
                   warren_I(A, C) - I_formula(A, C))))
max_gap <- max(gap_D, gap_I)

## ---- fp-guard-1 ----
stopifnot(max(abs(max_gap)) < 1e-10)

## ---- bounds ----
self_D <- schoener_D(A, A); self_I <- warren_I(A, A)
disj <- rep(0, nrow(grid)); disj2 <- rep(0, nrow(grid))
disj[1] <- 1; disj2[2] <- 1
d0 <- schoener_D(disj, disj2); i0 <- warren_I(disj, disj2)

## ---- overlaps ----
D_AB <- schoener_D(A, B); I_AB <- warren_I(A, B)
D_AC <- schoener_D(A, C); I_AC <- warren_I(A, C)
D_BC <- schoener_D(B, C); I_BC <- warren_I(B, C)

ovl <- data.frame(
  pair   = rep(c("A vs B", "A vs C", "B vs C"), 2),
  metric = rep(c("Schoener's D", "Warren's I"), each = 3),
  value  = c(D_AB, D_AC, D_BC, I_AB, I_AC, I_BC)
)
i_ge_d <- all(c(I_AB >= D_AB, I_AC >= D_AC, I_BC >= D_BC))
termwise_min <- min(sqrt(A * B) - pmin(A, B))

## ---- fig-di ----
ggplot(ovl, aes(pair, value, fill = metric)) +
  geom_col(position = position_dodge(width = 0.7), width = 0.6) +
  geom_text(aes(label = sprintf("%.2f", value)),
            position = position_dodge(width = 0.7), vjust = -0.4, size = 3.4,
            colour = "#2c3a31") +
  scale_fill_manual(values = c("Schoener's D" = "#cda23f", "Warren's I" = "#2f8f63"),
                    name = NULL) +
  scale_y_continuous(limits = c(0, 1), expand = expansion(mult = c(0, 0.08))) +
  labs(title = "Warren's I sits above Schoener's D",
       x = NULL, y = "overlap") +
  theme_te() +
  theme(legend.position = "top")
