# Modelling inhomogeneous point patterns in R
# https://tidyecology.com/posts/inhomogeneous-point-processes/
#
# 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-07

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

A <- 1
b0 <- 5.17; b1 <- 1.5                      # true intensity coefficients
covariate <- function(x, y) 2 * (x - 0.5)  # gradient, ranges over -1 to 1
intensity <- function(x, y) exp(b0 + b1 * covariate(x, y))
lam_max   <- exp(b0 + b1 * 1)              # maximum, at the high edge

set.seed(7801)
N_max <- rpois(1, lam_max * A)
ux <- runif(N_max); uy <- runif(N_max)
keep <- runif(N_max) < intensity(ux, uy) / lam_max
X <- data.frame(x = ux[keep], y = uy[keep])
n <- nrow(X)
n

## ---- fig-intensity ----
grid <- expand.grid(x = seq(0.005, 0.995, length.out = 120),
                    y = seq(0.005, 0.995, length.out = 120))
grid$lam <- intensity(grid$x, grid$y)
ggplot() +
  geom_raster(data = grid, aes(x, y, fill = lam)) +
  geom_point(data = X, aes(x, y), colour = te_ink, size = 0.8, alpha = 0.7) +
  scale_fill_gradient(low = te_paper, high = te_forest, name = "intensity") +
  coord_equal(expand = FALSE) +
  labs(x = NULL, y = NULL) +
  theme_te() +
  theme(axis.text = element_blank(), panel.grid = element_blank(),
        legend.position = "right")

## ---- glm-trend ----
G <- 20
edges  <- seq(0, 1, length.out = G + 1)
centre <- (edges[-1] + edges[-(G + 1)]) / 2
cell_area <- (1 / G)^2

bx <- cut(X$x, edges, include.lowest = TRUE)
by <- cut(X$y, edges, include.lowest = TRUE)
cnt <- as.data.frame(table(bx, by))
names(cnt) <- c("bx", "by", "count")
cnt$cx  <- centre[as.integer(cnt$bx)]
cnt$cy  <- centre[as.integer(cnt$by)]
cnt$cov <- covariate(cnt$cx, cnt$cy)

fit <- glm(count ~ cov, family = poisson,
           offset = rep(log(cell_area), nrow(cnt)), data = cnt)
dev_explained <- 1 - fit$deviance / fit$null.deviance
round(c(coef(fit), deviance_explained = dev_explained), 3)
summary(fit)$coefficients

## ---- lam-hat ----
lam_hat <- function(x, y) exp(coef(fit)[1] + coef(fit)[2] * covariate(x, y))

## ---- estimators ----
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))
  ut <- upper.tri(D)
  list(d = D[ut], w = W[ut], i = row(D)[ut], j = col(D)[ut])
}

L_hom <- function(x, y, r_seq) {
  pw <- pair_dw(x, y); o <- order(pw$d)
  cw <- cumsum(pw$w[o])
  idx <- findInterval(r_seq, pw$d[o])
  K <- (A / (n * (n - 1))) * 2 * c(0, cw)[idx + 1]   # idx == 0 means no pair within r
  sqrt(K / pi) - r_seq
}

L_inhom <- function(x, y, r_seq, lam_fun) {
  pw <- pair_dw(x, y); li <- lam_fun(x, y)
  w_l <- pw$w / (li[pw$i] * li[pw$j])
  o <- order(pw$d); cw <- cumsum(w_l[o])
  idx <- findInterval(r_seq, pw$d[o])
  K <- (1 / A) * 2 * c(0, cw)[idx + 1]               # idx == 0 means no pair within r
  sqrt(K / pi) - r_seq
}

r_seq <- seq(0.005, 0.09, by = 0.005)
obs_hom   <- L_hom(X$x, X$y, r_seq)
obs_inhom <- L_inhom(X$x, X$y, r_seq, lam_hat)

## ---- envelopes ----
set.seed(7811); n_sim <- 199
E_hom <- matrix(NA, n_sim, length(r_seq))
for (s in 1:n_sim) E_hom[s, ] <- L_hom(runif(n), runif(n), r_seq)
h_lo <- apply(E_hom, 2, min); h_hi <- apply(E_hom, 2, max)

set.seed(7821)
E_inh <- matrix(NA, n_sim, length(r_seq))
for (s in 1:n_sim) {
  Nm <- rpois(1, lam_max * A); vx <- runif(Nm); vy <- runif(Nm)
  kp <- runif(Nm) < intensity(vx, vy) / lam_max
  E_inh[s, ] <- L_inhom(vx[kp], vy[kp], r_seq, intensity)
}
i_lo <- apply(E_inh, 2, min); i_hi <- apply(E_inh, 2, max)

at <- function(v, r0) v[which.min(abs(r_seq - r0))]
data.frame(
  estimator = c("homogeneous", "inhomogeneous"),
  max_abs   = c(round(max(abs(obs_hom)), 4), round(max(abs(obs_inhom)), 4)),
  outside_env = c(sum(obs_hom > h_hi | obs_hom < h_lo),
                  sum(obs_inhom > i_hi | obs_inhom < i_lo))
)

## ---- fig-kinhom ----
df <- rbind(
  data.frame(r = r_seq, val = obs_hom,   lo = h_lo, hi = h_hi,
             which = "Homogeneous K (ignores trend)"),
  data.frame(r = r_seq, val = obs_inhom, lo = i_lo, hi = i_hi,
             which = "Inhomogeneous K (accounts for trend)"))
df$which <- factor(df$which, levels = c("Homogeneous K (ignores trend)",
                                        "Inhomogeneous K (accounts for trend)"))
ggplot(df, aes(r)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = te_sage, alpha = 0.30) +
  geom_hline(yintercept = 0, colour = te_faint, linetype = "dashed", linewidth = 0.4) +
  geom_line(aes(y = val, colour = which), linewidth = 0.9) +
  facet_wrap(~ which) +
  scale_colour_manual(values = c(te_rust, te_forest), guide = "none") +
  labs(x = "distance r", y = "L(r) - r") +
  theme_te()
