# Plotless density estimation from distances
# https://tidyecology.com/posts/plotless-density-from-distances/
#
# 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-13

## ---- setup ----
library(ggplot2)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

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

# wrap a coordinate difference onto the torus: the shortest signed offset
wrap <- function(d) d - round(d)

## ---- patterns ----
n_trees <- 400
lambda_true <- n_trees          # unit square: count and intensity coincide

gen_csr <- function(n) data.frame(x = runif(n), y = runif(n))

gen_clust <- function(n, n_parent = 20, sd_off = 0.02) {
  px <- runif(n_parent); py <- runif(n_parent)
  k  <- sample(n_parent, n, replace = TRUE)
  data.frame(x = (px[k] + rnorm(n, 0, sd_off)) %% 1,
             y = (py[k] + rnorm(n, 0, sd_off)) %% 1)
}

gen_reg <- function(n, d_min = 0.038) {
  ax <- numeric(n); ay <- numeric(n); got <- 0
  while (got < n) {
    qx <- runif(1); qy <- runif(1)
    if (got == 0) {
      got <- 1; ax[1] <- qx; ay[1] <- qy
    } else if (min(wrap(ax[1:got] - qx)^2 + wrap(ay[1:got] - qy)^2) >= d_min^2) {
      got <- got + 1; ax[got] <- qx; ay[got] <- qy
    }
  }
  data.frame(x = ax, y = ay)
}

# distance from every tree to its nearest neighbouring tree
nn_tree <- function(p) sapply(seq_len(nrow(p)), function(i) {
  d2 <- wrap(p$x - p$x[i])^2 + wrap(p$y - p$y[i])^2
  sqrt(min(d2[-i]))
})

set.seed(20260813)
patterns <- list(random    = gen_csr(n_trees),
                 clustered = gen_clust(n_trees),
                 regular   = gen_reg(n_trees))
nn_all <- lapply(patterns, nn_tree)
sapply(patterns, nrow)

## ---- survey ----
survey <- function(trees, m) {
  ox <- runif(m); oy <- runif(m)
  tx <- trees$x;  ty <- trees$y
  quadrants <- list(c(1, 1), c(1, -1), c(-1, 1), c(-1, -1))
  out <- t(sapply(seq_len(m), function(i) {
    dx <- wrap(tx - ox[i]); dy <- wrap(ty - oy[i])
    d2 <- dx^2 + dy^2
    j  <- which.min(d2)                       # the nearest tree
    # T-square: from that tree, look only into the half plane beyond it
    qx <- wrap(tx - tx[j]); qy <- wrap(ty - ty[j])
    beyond <- (qx * dx[j] + qy * dy[j]) > 0
    quad <- sapply(quadrants, function(s) {
      sel <- sign(dx) == s[1] & sign(dy) == s[2]
      if (any(sel)) sqrt(min(d2[sel])) else NA_real_
    })
    c(sqrt(d2[j]), sqrt(min(qx[beyond]^2 + qy[beyond]^2)), quad, j)
  }))
  data.frame(ox = ox, oy = oy, x = out[, 1], z = out[, 2],
             q1 = out[, 3], q2 = out[, 4], q3 = out[, 5], q4 = out[, 6],
             tree = out[, 7])          # which tree, so shared ones can be counted
}

lam_point <- function(s) (nrow(s) - 1) / (pi * sum(s$x^2))   # Pollard form
lam_ray   <- function(s) 1 / (4 * mean(s$x)^2)               # Rayleigh mean form

## ---- fig-maps ----
set.seed(11)
demo <- lapply(patterns, function(p) survey(p, 15))

circle_path <- function(s) {
  th <- seq(0, 2 * pi, length.out = 80)
  do.call(rbind, lapply(seq_len(nrow(s)), function(i)
    data.frame(id = i, x = s$ox[i] + s$x[i] * cos(th),
               y = s$oy[i] + s$x[i] * sin(th))))
}

tree_df <- do.call(rbind, lapply(names(patterns), function(nm)
  data.frame(pattern = nm, patterns[[nm]])))
disc_df <- do.call(rbind, lapply(names(demo), function(nm)
  data.frame(pattern = nm, circle_path(demo[[nm]]))))
tree_df$pattern <- factor(tree_df$pattern, levels = names(patterns))
disc_df$pattern <- factor(disc_df$pattern, levels = names(patterns))

ggplot(tree_df, aes(x, y)) +
  geom_point(colour = te_ink, size = 0.55, alpha = 0.8) +
  geom_path(data = disc_df, aes(group = id), colour = te_rust, linewidth = 0.5) +
  facet_wrap(~ pattern) +
  coord_fixed(xlim = c(0, 1), ylim = c(0, 1)) +
  labs(x = NULL, y = NULL, title = "Same density, three arrangements") +
  theme_datasheet() +
  theme(axis.text = element_blank())

## ---- crux ----
set.seed(19)
big <- lapply(patterns, function(p) survey(p, 2000))

crux <- data.frame(
  pattern      = names(patterns),
  point_tree   = round(sapply(big, function(s) mean(s$x)), 4),
  tree_tree    = round(sapply(nn_all, mean), 4),
  lam_from_pt  = round(sapply(big, lam_ray)),
  lam_from_nn  = round(sapply(nn_all, function(d) 1 / (4 * mean(d)^2))),
  clark_evans  = round(sapply(nn_all, function(d) mean(d) * 2 * sqrt(lambda_true)), 3))
print(crux, row.names = FALSE)

## ---- reps ----
# a quadrant is a quarter of the plane, so E[q^2] = 4 / (pi * lambda)
lam_quarter <- function(s) {
  q <- as.matrix(s[, c("q1", "q2", "q3", "q4")])
  q <- q[!is.na(q)]
  4 * (length(q) - 1) / (pi * sum(q^2))
}

lam_tsquare <- function(s)
  nrow(s)^2 / (2 * sqrt(2) * sum(s$x) * sum(s$z))

t_index <- function(s) mean(s$x^2 / (s$x^2 + s$z^2 / 2))

gens <- list(random    = function() gen_csr(n_trees),
             clustered = function() gen_clust(n_trees),
             regular   = function() gen_reg(n_trees))

set.seed(2026)
m_pts <- 100
reps <- do.call(rbind, lapply(names(gens), function(nm) {
  out <- t(replicate(200, {
    p <- gens[[nm]](); s <- survey(p, 2 * m_pts); h <- s[1:m_pts, ]
    c(nearest = lam_point(h), quarter = lam_quarter(h), tsquare = lam_tsquare(h),
      double = lam_point(s), t = t_index(h))
  }))
  data.frame(pattern = nm, as.data.frame(out))
}))

stat_row <- function(v) data.frame(mean = round(mean(v)), sd = round(sd(v), 1),
                                  rmse = round(sqrt(mean((v - lambda_true)^2))))
stats <- do.call(rbind, lapply(names(gens), function(nm)
  do.call(rbind, lapply(c("nearest", "quarter", "tsquare", "double"), function(e)
    cbind(data.frame(pattern = nm, estimator = e),
          stat_row(reps[[e]][reps$pattern == nm]))))))
val <- function(pat, est, what)
  stats[[what]][stats$pattern == pat & stats$estimator == est]
print(stats, row.names = FALSE)

## ---- sdboot ----
rand <- reps[reps$pattern == "random", ]
set.seed(88)
paired <- replicate(20000, {
  i <- sample(nrow(rand), replace = TRUE)
  sd(rand$tsquare[i]) - sd(rand$double[i])
})
naive_span <- round(quantile(rand$nearest, c(0.05, 0.95)))
round(c(gap = sd(rand$tsquare) - sd(rand$double), se_paired = sd(paired),
        se_single = sd(rand$tsquare) / sqrt(2 * nrow(rand) - 2)), 2)

## ---- fig-bias ----
long <- do.call(rbind, lapply(c("nearest", "quarter", "tsquare"), function(e)
  data.frame(pattern = reps$pattern, estimator = e,
             ratio = reps[[e]] / lambda_true)))
long$estimator <- factor(long$estimator, levels = c("tsquare", "quarter", "nearest"),
                         labels = c("T-square", "point-centred quarter", "nearest tree"))
long$pattern <- factor(long$pattern, levels = names(gens))

ggplot(long, aes(x = ratio, y = estimator, colour = estimator)) +
  geom_vline(xintercept = 1, linetype = "dashed", colour = te_body) +
  geom_boxplot(outlier.size = 0.6, linewidth = 0.5) +
  scale_x_log10(breaks = c(0.1, 0.25, 0.5, 1, 2)) +
  scale_colour_manual(values = c(te_forest, te_gold, te_rust)) +
  facet_wrap(~ pattern, ncol = 1) +
  labs(x = "estimated density / true density", y = NULL,
       title = "Where each estimator lands when the trees are not random") +
  theme_datasheet() +
  theme(legend.position = "none")

## ---- null-t ----
set.seed(404)
shared <- replicate(200, length(unique(survey(gen_csr(n_trees), m_pts)$tree)))

m_grid <- c(25, 100, 200)
null_t <- lapply(m_grid, function(m)
  replicate(2000, t_index(survey(gen_csr(n_trees), m))))

null_tab <- data.frame(
  m          = m_grid,
  sd_null    = round(sapply(null_t, sd), 4),
  sd_formula = round(1 / sqrt(12 * m_grid), 4),
  size_pct   = round(100 * mapply(function(v, m)
                     mean(abs(v - 0.5) > 1.96 / sqrt(12 * m)), null_t, m_grid), 1))
print(null_tab, row.names = FALSE)

t_lim <- quantile(null_t[[2]], c(0.025, 0.975))   # simulated limits at m = 100

## ---- fig-index ----
idx <- data.frame(pattern = factor(reps$pattern, levels = names(gens)), t = reps$t)

ggplot(idx, aes(x = t, colour = pattern)) +
  geom_vline(xintercept = 0.5, colour = te_body, linewidth = 0.5) +
  geom_vline(xintercept = t_lim, linetype = "dashed",
             colour = te_body, linewidth = 0.4) +
  geom_density(linewidth = 0.9) +
  scale_colour_manual(values = c(te_ink, te_rust, te_gold)) +
  labs(x = "T-square index t", y = "density", colour = NULL,
       title = "The distances test the assumption they depend on") +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- index-tab ----
mean_t  <- tapply(reps$t, reps$pattern, mean)[names(gens)]
idx_tab <- data.frame(pattern = names(gens),
                      mean_t  = round(mean_t, 3),
                      z_score = round((mean_t - 0.5) / sd(null_t[[2]]), 1))
print(idx_tab, row.names = FALSE)

r_t <- reps$t[reps$pattern == "random"]
flagged <- c(simulated = sum(r_t < t_lim[1] | r_t > t_lim[2]),
             textbook  = sum(abs(r_t - 0.5) > 1.96 / sqrt(12 * m_pts)),
             fair_top  = qbinom(0.975, 200, 0.05))   # top of the central 95 per cent range for a true 5 per cent rate
flagged
