# Checking a niche comparison
# https://tidyecology.com/posts/checking-a-niche-comparison/
#
# 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-01

## ---- 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 <- 50; gy <- 50
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))
avail <- with(grid, dnorm(temp, 15, 4) * dnorm(moist, 0.5, 0.22)); avail <- avail / sum(avail)

## ---- check1-data ----
prefA <- with(grid, dnorm(temp, 14, 2.5) * dnorm(moist, 0.5, 0.14))
prefB <- with(grid, dnorm(temp, 17, 2.5) * dnorm(moist, 0.5, 0.14))
oA <- prefA * avail; oA <- oA / sum(oA)
oB <- prefB * avail; oB <- oB / sum(oB)

mk_smoother <- function(bt, bm) {
  St <- { d <- outer(temp, temp, "-"); K <- exp(-0.5 * (d / bt)^2); K / rowSums(K) }
  Sm <- { d <- outer(moist, moist, "-"); K <- exp(-0.5 * (d / bm)^2); K / rowSums(K) }
  list(St = St, Sm = Sm)
}
ndens <- function(pt, pm, S) {
  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() before as.vector(): expand.grid varies temp fastest, as.vector() is column-major
  d <- S$Sm %*% cnt %*% t(S$St); as.vector(t(pmax(d, 0))) / sum(d)
}

set.seed(909); n <- 120
ia <- sample.int(nrow(grid), n, replace = TRUE, prob = oA)
ib <- sample.int(nrow(grid), n, replace = TRUE, prob = oB)
ta <- grid$temp[ia]; ma <- grid$moist[ia]
tb <- grid$temp[ib]; mb <- grid$moist[ib]

## ---- check1-bandwidth ----
bws <- c(0.8, 1.5, 2.5, 4, 6)
Dbw <- numeric(length(bws))
for (j in seq_along(bws)) {
  S <- mk_smoother(bws[j], bws[j] * 0.05)
  Dbw[j] <- schoener_D(ndens(ta, ma, S), ndens(tb, mb, S))
}
bw_range <- max(Dbw) - min(Dbw)

# bootstrap CI at a single fixed bandwidth: the sampling uncertainty
S0 <- mk_smoother(2.5, 0.12)
Dhat <- schoener_D(ndens(ta, ma, S0), ndens(tb, mb, S0))
B <- 400; Db <- numeric(B)
for (b in 1:B) {
  ra <- sample.int(n, n, replace = TRUE); rb <- sample.int(n, n, replace = TRUE)
  Db[b] <- schoener_D(ndens(ta[ra], ma[ra], S0), ndens(tb[rb], mb[rb], S0))
}
ci <- quantile(Db, c(0.025, 0.975))
ci_width <- unname(ci[2] - ci[1])
dominance <- bw_range / ci_width

## ---- fig-bandwidth ----
dfb <- data.frame(bw = bws, D = Dbw)
ggplot(dfb, aes(bw, D)) +
  geom_line(colour = "#275139", linewidth = 0.9) +
  geom_point(colour = "#275139", size = 2.6) +
  annotate("errorbar", x = 2.5, ymin = ci[1], ymax = ci[2],
           width = 0.25, colour = "#b5534e", linewidth = 0.8) +
  annotate("text", x = 2.75, y = Dhat, hjust = 0, size = 3.2, colour = "#b5534e",
           label = "bootstrap 95% CI\n(sampling)") +
  labs(title = "Bandwidth moves D more than sampling does",
       x = "smoothing bandwidth (temperature)", y = "Schoener's D") +
  theme_te()

## ---- check2 ----
pref <- with(grid, dnorm(temp, 15, 3) * dnorm(moist, 0.5, 0.16)); pref <- pref / sum(pref)
D_fund <- schoener_D(pref, pref)                       # identical preference: overlap is 1
av_cold <- with(grid, ifelse(temp < 15, 1, 0.03)) * avail; av_cold <- av_cold / sum(av_cold)
av_warm <- with(grid, ifelse(temp > 15, 1, 0.03)) * avail; av_warm <- av_warm / sum(av_warm)
occA <- pref * av_cold; occA <- occA / sum(occA)
occB <- pref * av_warm; occB <- occB / sum(occB)
D_real <- schoener_D(occA, occB)
gap <- D_fund - D_real

## ---- fig-truncation ----
dft <- rbind(
  data.frame(grid, dens = occA, species = "Species A (cold access)"),
  data.frame(grid, dens = occB, species = "Species B (warm access)")
)
ggplot(dft, aes(temp, moist, fill = dens)) +
  geom_raster() +
  facet_wrap(~species) +
  scale_fill_gradientn(colours = paper_forest, name = "density") +
  labs(title = "Same preference, non-overlapping realised niches",
       x = "temperature", y = "moisture") +
  theme_te()

## ---- check3 ----
prefX <- with(grid, dnorm(temp, 15,   2.5) * dnorm(moist, 0.5, 0.14))
prefY <- with(grid, dnorm(temp, 16.5, 2.5) * dnorm(moist, 0.5, 0.14))
avBroad  <- with(grid, dnorm(temp, 15, 7.0) * dnorm(moist, 0.5, 0.35)); avBroad  <- avBroad  / sum(avBroad)
avNarrow <- with(grid, dnorm(temp, 16, 2.2) * dnorm(moist, 0.5, 0.16)); avNarrow <- avNarrow / sum(avNarrow)
oX <- prefX * avBroad;  oX <- oX / sum(oX)
oY <- prefY * avNarrow; oY <- oY / sum(oY)

St2 <- { d <- outer(temp, temp, "-"); K <- exp(-0.5 * (d / 2)^2); K / rowSums(K) }
Sm2 <- { d <- outer(moist, moist, "-"); K <- exp(-0.5 * (d / 0.10)^2); K / rowSums(K) }
nd2 <- 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
  d <- Sm2 %*% cnt %*% t(St2); as.vector(t(pmax(d, 0))) / sum(d)   # grid order, as above
}
set.seed(808)
# both niches estimated from 300 occurrences, smoothed like the null samples
idxX <- sample.int(nrow(grid), 300, replace = TRUE, prob = oX)
idxY <- sample.int(nrow(grid), 300, replace = TRUE, prob = oY)
eX <- nd2(grid$temp[idxX], grid$moist[idxX]); eY <- nd2(grid$temp[idxY], grid$moist[idxY])
D_obs <- schoener_D(eX, eY); R <- 499
# A -> B: hold X, draw the null from B's narrow background
dnA <- numeric(R)
for (r in 1:R) { idx <- sample.int(nrow(grid), 300, replace = TRUE, prob = avNarrow); dnA[r] <- schoener_D(eX, nd2(grid$temp[idx], grid$moist[idx])) }
# B -> A: hold Y, draw the null from A's broad background
dnB <- numeric(R)
for (r in 1:R) { idx <- sample.int(nrow(grid), 300, replace = TRUE, prob = avBroad); dnB[r] <- schoener_D(eY, nd2(grid$temp[idx], grid$moist[idx])) }
pA_more <- (sum(dnA >= D_obs) + 1) / (R + 1)
pB_more <- (sum(dnB >= D_obs) + 1) / (R + 1)

## ---- fig-asymmetry ----
asym <- rbind(
  data.frame(D = dnA, dir = "A held, null from B (narrow)", obs = D_obs),
  data.frame(D = dnB, dir = "B held, null from A (broad)", obs = D_obs)
)
asym$dir <- factor(asym$dir, levels = c("A held, null from B (narrow)", "B held, null from A (broad)"))
obs_df <- unique(asym[, c("dir", "obs")])
ggplot(asym, aes(D)) +
  geom_histogram(bins = 30, fill = "#93a87f", colour = "white", linewidth = 0.15) +
  geom_vline(data = obs_df, aes(xintercept = obs), colour = "#b5534e", linewidth = 0.9) +
  facet_wrap(~dir, scales = "free_x") +
  labs(title = "Same pair, opposite similarity verdict",
       x = "Schoener's D", y = "count") +
  theme_te() +
  theme(panel.spacing.x = unit(2, "lines"),
        panel.border = element_rect(colour = "grey70", fill = NA))
