# Ripley’s K and the pair correlation function
# https://tidyecology.com/posts/ripleys-k-function/
#
# 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)
library(dplyr)
library(tidyr)

te_ink    <- "#16241d"; te_body   <- "#2c3a31"; te_forest <- "#275139"
te_label  <- "#46604a"; te_sage   <- "#93a87f"; te_paper  <- "#f5f4ee"
te_line   <- "#dad9ca"; te_faint  <- "#5d6b61"; te_gold   <- "#c9b458"
te_rust   <- "#b5534e"

theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
      plot.background  = element_rect(fill = te_paper, colour = NA),
      panel.background = element_rect(fill = te_paper, colour = NA),
      text        = element_text(colour = te_body),
      plot.title  = element_text(colour = te_ink, face = "bold"),
      axis.title  = element_text(colour = te_label),
      axis.text   = element_text(colour = te_faint),
      strip.text  = element_text(colour = te_ink, face = "bold"),
      legend.text = element_text(colour = te_body)
    )
}

n <- 200; A <- 1

make_patterns <- function() {
  set.seed(41); csr <- list(x = runif(n), y = runif(n))
  set.seed(42)
  np <- 15; sdo <- 0.03; px <- runif(np); py <- runif(np)
  cx <- numeric(0); cy <- numeric(0)
  while (length(cx) < n) {
    k <- sample(np, 1); ax <- rnorm(1, px[k], sdo); ay <- rnorm(1, py[k], sdo)
    if (ax >= 0 && ax <= 1 && ay >= 0 && ay <= 1) { cx <- c(cx, ax); cy <- c(cy, ay) }
  }
  clustered <- list(x = cx, y = cy)
  set.seed(43)
  dmin <- 0.038; rx <- numeric(0); ry <- numeric(0)
  while (length(rx) < n) {
    ax <- runif(1); ay <- runif(1)
    if (length(rx) == 0 || min((rx - ax)^2 + (ry - ay)^2) >= dmin^2) { rx <- c(rx, ax); ry <- c(ry, ay) }
  }
  regular <- list(x = rx, y = ry)
  list(CSR = csr, Clustered = clustered, Regular = regular)
}
patterns <- make_patterns()

## ---- kfun ----
pair_dw <- function(x, y) {
  dx <- abs(outer(x, x, "-")); dy <- abs(outer(y, y, "-"))
  D  <- sqrt(dx^2 + dy^2)
  W  <- 1 / ((1 - dx) * (1 - dy))          # translation weight, unit square
  ut <- upper.tri(D)
  o  <- order(D[ut])
  list(d = D[ut][o], w = W[ut][o])
}

K_hat <- function(pw, r_seq) {
  cw  <- cumsum(pw$w)
  idx <- findInterval(r_seq, pw$d)
  csum <- c(0, cw)[idx + 1]                # idx == 0 means no pair within r
  (A / (n * (n - 1))) * 2 * csum
}

## ---- lfun ----
L_minus_r <- function(pw, r_seq) sqrt(K_hat(pw, r_seq) / pi) - r_seq

## ---- envelope-lr ----
r_seq <- seq(0.005, 0.09, by = 0.005)
obs_L <- lapply(patterns, function(p) L_minus_r(pair_dw(p$x, p$y), r_seq))

set.seed(7701)
n_sim <- 199
L_sim <- matrix(NA, n_sim, length(r_seq))
for (s in 1:n_sim) L_sim[s, ] <- L_minus_r(pair_dw(runif(n), runif(n)), r_seq)
L_lo <- apply(L_sim, 2, min); L_hi <- apply(L_sim, 2, max)

at <- function(v, r0) v[which.min(abs(r_seq - r0))]
data.frame(
  pattern  = names(obs_L),
  max_L    = sapply(obs_L, max),
  min_L    = sapply(obs_L, min),
  above_env = sapply(obs_L, function(v) sum(v > L_hi)),
  below_env = sapply(obs_L, function(v) sum(v < L_lo))
)

## ---- fig-lr ----
lr_df <- do.call(rbind, lapply(names(obs_L), function(nm)
  data.frame(pattern = nm, r = r_seq, val = obs_L[[nm]])))
lr_df$pattern <- factor(lr_df$pattern, levels = c("CSR", "Clustered", "Regular"))
env_df <- data.frame(r = r_seq, lo = L_lo, hi = L_hi)

ggplot() +
  geom_ribbon(data = env_df, aes(r, ymin = lo, ymax = hi), fill = te_sage, alpha = 0.30) +
  geom_hline(yintercept = 0, colour = te_faint, linetype = "dashed", linewidth = 0.4) +
  geom_line(data = lr_df, aes(r, val, colour = pattern), linewidth = 0.9) +
  scale_colour_manual(values = c(CSR = te_faint, Clustered = te_rust, Regular = te_forest)) +
  labs(x = "distance r", y = "L(r) - r", colour = NULL) +
  theme_te() + theme(legend.position = "bottom")

## ---- gfun ----
g_fun <- function(pw, r_seq, h) {
  sapply(r_seq, function(r) {
    k <- (3 / (4 * h)) * (1 - ((r - pw$d) / h)^2)
    k[abs(r - pw$d) > h] <- 0
    (A / (n * (n - 1))) * 2 * sum(pw$w * k) / (2 * pi * r)
  })
}

h <- 0.012
obs_g <- lapply(patterns, function(p) g_fun(pair_dw(p$x, p$y), r_seq, h))

set.seed(7701)
g_sim <- matrix(NA, n_sim, length(r_seq))
for (s in 1:n_sim) g_sim[s, ] <- g_fun(pair_dw(runif(n), runif(n)), r_seq, h)
g_lo <- apply(g_sim, 2, min); g_hi <- apply(g_sim, 2, max)

data.frame(
  pattern  = names(obs_g),
  g_at_002 = sapply(obs_g, function(v) at(v, 0.02)),
  g_at_005 = sapply(obs_g, function(v) at(v, 0.05))
)

## ---- fig-g ----
g_df <- do.call(rbind, lapply(names(obs_g), function(nm)
  data.frame(pattern = nm, r = r_seq, val = obs_g[[nm]])))
g_df$pattern <- factor(g_df$pattern, levels = c("CSR", "Clustered", "Regular"))
genv_df <- data.frame(r = r_seq, lo = g_lo, hi = g_hi)

ggplot() +
  geom_ribbon(data = genv_df, aes(r, ymin = lo, ymax = hi), fill = te_sage, alpha = 0.30) +
  geom_hline(yintercept = 1, colour = te_faint, linetype = "dashed", linewidth = 0.4) +
  geom_line(data = g_df, aes(r, val, colour = pattern), linewidth = 0.9) +
  scale_colour_manual(values = c(CSR = te_faint, Clustered = te_rust, Regular = te_forest)) +
  labs(x = "distance r", y = "g(r)", colour = NULL) +
  theme_te() + theme(legend.position = "bottom")
