# Home ranges in R: MCP versus kernel density
# https://tidyecology.com/posts/home-range-mcp-kde/
#
# 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 ----
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 <- "#cda23f"
te_green <- "#2f8f63"; te_red <- "#b5534e"
theme_te <- function(base_size = 12) {
  ggplot2::theme_minimal(base_size = base_size) +
    ggplot2::theme(
      text = ggplot2::element_text(colour = te_body),
      plot.title = ggplot2::element_text(colour = te_ink, face = "bold"),
      plot.subtitle = ggplot2::element_text(colour = te_faint),
      axis.title = ggplot2::element_text(colour = te_label),
      axis.text = ggplot2::element_text(colour = te_faint),
      panel.grid.major = ggplot2::element_line(colour = te_line, linewidth = 0.3),
      panel.grid.minor = ggplot2::element_blank(),
      plot.background = ggplot2::element_rect(fill = te_paper, colour = NA),
      panel.background = ggplot2::element_rect(fill = te_paper, colour = NA),
      legend.key = ggplot2::element_blank(),
      legend.title = ggplot2::element_text(colour = te_label),
      strip.text = ggplot2::element_text(colour = te_ink, face = "bold"))
}

## ---- data ----
library(MASS); library(ggplot2); library(dplyr)

set.seed(4809)
n_core <- 200
comp <- rbinom(n_core, 1, 0.40)
xA <- rnorm(sum(comp == 0), 0.0, 1.20); yA <- rnorm(sum(comp == 0), 0.0, 1.20)
xB <- rnorm(sum(comp == 1), 4.0, 0.90); yB <- rnorm(sum(comp == 1), 2.5, 0.90)
core <- data.frame(x = c(xA, xB), y = c(yA, yB))

n_exc <- 6
ang <- runif(n_exc, 0, 2 * pi); rad <- runif(n_exc, 7, 10)
exc <- data.frame(x = 2 + rad * cos(ang), y = 1 + rad * sin(ang))

loc <- rbind(core, exc)
loc$kind <- c(rep("relocation", n_core), rep("excursion", n_exc))
nrow(loc)

## ---- mcp ----
mcp_area <- function(x, y) {
  h <- chull(x, y); xh <- x[h]; yh <- y[h]
  0.5 * abs(sum(xh * c(yh[-1], yh[1]) - c(xh[-1], xh[1]) * yh))
}
a100 <- mcp_area(loc$x, loc$y)

# 95% MCP: drop the 5% of points farthest from the centroid
cx <- mean(loc$x); cy <- mean(loc$y)
d2 <- (loc$x - cx)^2 + (loc$y - cy)^2
keep <- d2 <= quantile(d2, 0.95)
a95mcp <- mcp_area(loc$x[keep], loc$y[keep])

round(c(mcp100 = a100, mcp95 = a95mcp, ratio = a100 / a95mcp), 2)

## ---- accumulation ----
iso_threshold <- function(z, cell, p) {
  zv <- sort(as.vector(z), decreasing = TRUE)
  zv[which(cumsum(zv) * cell >= p)[1]]
}
iso_area <- function(z, cell, p) sum(z >= iso_threshold(z, cell, p)) * cell

set.seed(7788)
ns <- seq(20, n_core, by = 20); R <- 60
xlim0 <- range(core$x) + c(-1, 1) * 2; ylim0 <- range(core$y) + c(-1, 1) * 2
acc <- lapply(ns, function(nn) {
  am <- ak <- numeric(R)
  for (r in seq_len(R)) {
    s <- core[sample(nrow(core), nn), ]
    am[r] <- mcp_area(s$x, s$y)
    kk <- kde2d(s$x, s$y, n = 80, lims = c(xlim0, ylim0))
    cc <- diff(kk$x[1:2]) * diff(kk$y[1:2])
    ak[r] <- iso_area(kk$z, cc, 0.95)
  }
  data.frame(n = nn, mcp = mean(am), kde = mean(ak))
})
acc <- do.call(rbind, acc)
round(c(mcp_n20 = acc$mcp[1], mcp_n200 = acc$mcp[10],
        kde_n20 = acc$kde[1], kde_n200 = acc$kde[10]), 1)

# Second arm, on exactly the same subsamples: re-seeding replays the draws
# above, but now the bandwidth is held at the full-sample value instead of
# being recomputed inside each subsample.
h_full <- c(bandwidth.nrd(core$x), bandwidth.nrd(core$y))
set.seed(7788)
fixed_bw <- lapply(ns, function(nn) {
  af <- hx <- numeric(R)
  for (r in seq_len(R)) {
    s <- core[sample(nrow(core), nn), ]
    hx[r] <- bandwidth.nrd(s$x)
    kk <- kde2d(s$x, s$y, n = 80, lims = c(xlim0, ylim0), h = h_full)
    cc <- diff(kk$x[1:2]) * diff(kk$y[1:2])
    af[r] <- iso_area(kk$z, cc, 0.95)
  }
  data.frame(n = nn, kde_fix = mean(af), h_x = mean(hx))
})
fixed_bw <- do.call(rbind, fixed_bw)
acc$kde_fix <- fixed_bw$kde_fix; acc$h_x <- fixed_bw$h_x

data.frame(n = acc$n, kde = round(acc$kde, 1),
           kde_fix = round(acc$kde_fix, 1), h_x = round(acc$h_x, 2))
round(c(h_ratio = acc$h_x[10] / acc$h_x[1], nrd_rule = 10^(-1 / 5)), 3)

## ---- fig-accumulation ----
lev <- c("100% MCP", "95% KDE, bandwidth per subsample", "95% KDE, fixed bandwidth")
acc_long <- rbind(
  data.frame(n = acc$n, area = acc$mcp, estimator = lev[1]),
  data.frame(n = acc$n, area = acc$kde, estimator = lev[2]),
  data.frame(n = acc$n, area = acc$kde_fix, estimator = lev[3]))
acc_long$estimator <- factor(acc_long$estimator, levels = lev)
ggplot(acc_long, aes(n, area, colour = estimator)) +
  geom_line(linewidth = 0.8) + geom_point(size = 1.8) +
  scale_colour_manual(
    values = setNames(c(te_red, te_forest, te_gold), lev), name = NULL) +
  labs(title = "Home-range area against number of relocations",
       x = "number of relocations", y = expression(area ~ (km^2))) +
  theme_te(13)

## ---- kde ----
xr <- range(loc$x) + c(-1, 1) * 2; yr <- range(loc$y) + c(-1, 1) * 2
href <- c(bandwidth.nrd(loc$x), bandwidth.nrd(loc$y))
k <- kde2d(loc$x, loc$y, n = 120, lims = c(xr, yr), h = href)
cell <- diff(k$x[1:2]) * diff(k$y[1:2])
round(c(h_x = href[1], h_y = href[2], integral = sum(k$z) * cell), 3)

## ---- isopleth ----
thr95 <- iso_threshold(k$z, cell, 0.95); thr50 <- iso_threshold(k$z, cell, 0.50)
a95kde <- iso_area(k$z, cell, 0.95); a50kde <- iso_area(k$z, cell, 0.50)
round(c(kde95 = a95kde, kde50 = a50kde), 2)

## ---- fig-overlay ----
hull_idx <- chull(loc$x, loc$y)
hull_df  <- loc[c(hull_idx, hull_idx[1]), c("x", "y")]
grid_df  <- expand.grid(x = k$x, y = k$y); grid_df$z <- as.vector(k$z)

ggplot() +
  geom_point(data = loc, aes(x, y, shape = kind, colour = kind), size = 1.6, alpha = 0.8) +
  geom_path(data = hull_df, aes(x, y), colour = te_red, linewidth = 0.7) +
  geom_contour(data = grid_df, aes(x, y, z = z), breaks = thr95, colour = te_forest, linewidth = 0.8) +
  geom_contour(data = grid_df, aes(x, y, z = z), breaks = thr50, colour = te_gold, linewidth = 0.8) +
  scale_colour_manual(values = c(relocation = te_faint, excursion = te_red), name = NULL) +
  scale_shape_manual(values = c(relocation = 16, excursion = 4), name = NULL) +
  coord_equal() +
  labs(title = "Home range: 100% MCP versus kernel isopleths",
       x = "easting (km)", y = "northing (km)") +
  theme_te(13)

## ---- bandwidth ----
bw_area <- function(mult) {
  kk <- kde2d(loc$x, loc$y, n = 120, lims = c(xr, yr), h = href * mult)
  cc <- diff(kk$x[1:2]) * diff(kk$y[1:2])
  iso_area(kk$z, cc, 0.95)
}
round(sapply(c(0.6, 1.0, 1.5), bw_area), 2)

## ---- ou-model ----
q95 <- qchisq(0.95, 2)
tau_h <- 6          # position autocorrelation time, hours
sigma_km <- 1.2     # stationary standard deviation per axis, km
area_true <- pi * q95 * sigma_km^2
range_diam <- 2 * sqrt(q95) * sigma_km

# exact OU update, run as a recursive filter on the deviations from the centre
ou_dev <- function(n, dt, tau, sigma) {
  aa <- exp(-dt / tau)
  as.numeric(stats::filter(rnorm(n, 0, sigma * sqrt(1 - aa^2)), aa,
                           method = "recursive", init = rnorm(1, 0, sigma)))
}
# the model's own target, estimated its own way: isotropic normal 95% area
area_norm <- function(x, y) {
  vx <- mean((x - mean(x))^2); vy <- mean((y - mean(y))^2)
  pi * q95 * (vx + vy) / 2
}
# expected area over true area for n fixes dt apart, from the discrete
# autocovariance rather than its long-track limit
ratio_exact <- function(n, dt, tau) {
  rho <- exp(-dt / tau); kk <- seq_len(n - 1)
  1 - (n + 2 * sum((n - kk) * rho^kk)) / n^2
}

set.seed(60481)
chk <- ou_dev(2e5, 0.25 * tau_h, tau_h, sigma_km)
chk_sd <- sd(chk); chk_acf <- cor(chk[-1], chk[-length(chk)])
round(c(sd_sim = chk_sd, sd_target = sigma_km, acf1_sim = chk_acf,
        acf1_target = exp(-0.25), area_true = area_true), 4)

## ---- ou-duration ----
boot_cv <- function(v, B = 400) {
  bs <- replicate(B, {u <- sample(v, length(v), TRUE); sd(u) / mean(u)})
  sd(bs)
}

set.seed(31607)
dt_base <- 0.25; R_rep <- 1000
tmult <- c(2, 5, 10, 25, 50, 100, 400)
dur <- lapply(tmult, function(tm) {
  nfix <- tm / dt_base
  a <- replicate(R_rep, area_norm(ou_dev(nfix, dt_base * tau_h, tau_h, sigma_km),
                                  ou_dev(nfix, dt_base * tau_h, tau_h, sigma_km)))
  rr <- a / area_true; cv <- sd(rr) / mean(rr)
  data.frame(t_tau = tm, n_fix = nfix, ratio = mean(rr), se = sd(rr) / sqrt(R_rep),
             asym = 1 - 2 / tm, exact = ratio_exact(nfix, dt_base * tau_h, tau_h),
             cv = cv, cv_se = boot_cv(rr), cv_asym = sqrt(1 / tm))
})
dur <- do.call(rbind, dur)
cv_gain <- dur$cv[6] / dur$cv[5]
cv_gain_se <- cv_gain * sqrt((dur$cv_se[6] / dur$cv[6])^2 + (dur$cv_se[5] / dur$cv[5])^2)
round(dur, 4)

## ---- ou-interval ----
set.seed(90412)
dtm <- c(2.5, 1.25, 0.5, 0.25, 0.125, 0.0625); t_hold <- 25
pace <- lapply(dtm, function(dm) {
  nfix <- t_hold / dm; an <- am <- numeric(R_rep)
  for (r in seq_len(R_rep)) {
    xx <- ou_dev(nfix, dm * tau_h, tau_h, sigma_km)
    yy <- ou_dev(nfix, dm * tau_h, tau_h, sigma_km)
    an[r] <- area_norm(xx, yy); am[r] <- mcp_area(xx, yy)
  }
  rr <- an / area_true; cv <- sd(rr) / mean(rr)
  data.frame(dt_tau = dm, n_fix = nfix, ratio = mean(rr), se = sd(rr) / sqrt(R_rep),
             exact = ratio_exact(nfix, dm * tau_h, tau_h), cv = cv, cv_se = boot_cv(rr),
             mcp = mean(am), mcp_se = sd(am) / sqrt(R_rep))
})
pace <- do.call(rbind, pace)
fix_gain <- pace$cv[6] / pace$cv[5]
fix_gain_se <- fix_gain * sqrt((pace$cv_se[6] / pace$cv[6])^2 + (pace$cv_se[5] / pace$cv[5])^2)
mcp_gain <- pace$mcp[6] / pace$mcp[4]
mcp_gain_se <- mcp_gain * sqrt((pace$mcp_se[6] / pace$mcp[6])^2 + (pace$mcp_se[4] / pace$mcp[4])^2)
n_eff <- 1 + 1 / pace$cv[6]^2   # n independent relocations give a CV of 1 / sqrt(n - 1) here
z_share <- (pace$ratio[4] - dur$ratio[4]) / sqrt(pace$se[4]^2 + dur$se[4]^2)

# what T / tau independent relocations would give, for comparison
set.seed(41137)
iid <- replicate(R_rep, area_norm(rnorm(t_hold, 0, sigma_km), rnorm(t_hold, 0, sigma_km)))
iid_cv <- sd(iid) / mean(iid)
round(pace, 4)

## ---- fig-fix-schedule ----
arm <- c("more fixes from a longer track", "more fixes from a faster fix rate")
qn <- c("area estimate / true area", "coefficient of variation")
d2 <- dur[dur$t_tau >= 5, ]
sched <- rbind(
  data.frame(n_fix = d2$n_fix, value = d2$ratio, arm = arm[1], quantity = qn[1], src = "simulation"),
  data.frame(n_fix = d2$n_fix, value = d2$cv, arm = arm[1], quantity = qn[2], src = "simulation"),
  data.frame(n_fix = pace$n_fix, value = pace$ratio, arm = arm[2], quantity = qn[1], src = "simulation"),
  data.frame(n_fix = pace$n_fix, value = pace$cv, arm = arm[2], quantity = qn[2], src = "simulation"),
  data.frame(n_fix = d2$n_fix, value = d2$asym, arm = arm[1], quantity = qn[1], src = "closed form"),
  data.frame(n_fix = d2$n_fix, value = d2$cv_asym, arm = arm[1], quantity = qn[2], src = "closed form"),
  data.frame(n_fix = pace$n_fix, value = 1 - 2 / t_hold, arm = arm[2], quantity = qn[1], src = "closed form"),
  data.frame(n_fix = pace$n_fix, value = sqrt(1 / t_hold), arm = arm[2], quantity = qn[2], src = "closed form"))
sched$arm <- factor(sched$arm, levels = arm)
sched$quantity <- factor(sched$quantity, levels = qn)

ggplot(sched, aes(n_fix, value, colour = arm, linetype = src)) +
  geom_line(linewidth = 0.8) +
  geom_point(data = subset(sched, src == "simulation"), size = 1.8, show.legend = FALSE) +
  facet_wrap(~ quantity, scales = "free_y") +
  scale_x_log10() +
  scale_colour_manual(values = setNames(c(te_forest, te_gold), arm), name = NULL) +
  scale_linetype_manual(values = c(simulation = "solid", `closed form` = "22"), name = NULL) +
  guides(colour = guide_legend(order = 1), linetype = guide_legend(order = 2)) +
  labs(title = "What extra fixes buy, and what they do not",
       x = "number of fixes (log scale)", y = "dimensionless ratio") +
  theme_te(13) +
  theme(legend.position = "bottom", legend.box = "vertical",
        legend.margin = margin(0, 0, 0, 0))

## ---- ou-season ----
set.seed(55231)
amp_km <- 1.5 * sigma_km; per_h <- 250 * tau_h; R_sea <- 400
tm_sea <- c(5, 25, 100, 500, 2000)
sea <- lapply(tm_sea, function(tm) {
  nfix <- tm / dt_base; dth <- dt_base * tau_h; tt <- seq_len(nfix) * dth
  ef <- es <- numeric(R_sea)
  for (r in seq_len(R_sea)) {
    xx <- ou_dev(nfix, dth, tau_h, sigma_km); yy <- ou_dev(nfix, dth, tau_h, sigma_km)
    ef[r] <- area_norm(xx, yy) / area_true - 1
    es[r] <- area_norm(xx + amp_km * sin(2 * pi * tt / per_h + runif(1, 0, 2 * pi)),
                       yy) / area_true - 1
  }
  data.frame(t_tau = tm, rmse_fix = sqrt(mean(ef^2)),
             se_fix = sd(ef^2) / (2 * sqrt(mean(ef^2)) * sqrt(R_sea)),
             rmse_sea = sqrt(mean(es^2)),
             se_sea = sd(es^2) / (2 * sqrt(mean(es^2)) * sqrt(R_sea)))
})
sea <- do.call(rbind, sea)
infl_pred <- amp_km^2 / (4 * sigma_km^2)
sea_worse <- sea$rmse_sea[5] / sea$rmse_fix[5]
swing_frac <- 2 * amp_km / range_diam
per_days <- per_h / 24
round(sea, 4)

## ---- fig-season-drift ----
lab <- c("fixed range centre", "seasonal shift of the centre")
sea_long <- rbind(
  data.frame(t_tau = sea$t_tau, rmse = sea$rmse_fix, se = sea$se_fix, model = lab[1]),
  data.frame(t_tau = sea$t_tau, rmse = sea$rmse_sea, se = sea$se_sea, model = lab[2]))
sea_long$model <- factor(sea_long$model, levels = lab)

ggplot(sea_long, aes(t_tau, rmse, colour = model)) +
  geom_vline(xintercept = per_h / tau_h, colour = te_faint, linetype = "22", linewidth = 0.4) +
  geom_line(linewidth = 0.8) + geom_point(size = 1.9) +
  geom_errorbar(aes(ymin = rmse - se, ymax = rmse + se), width = 0.06, linewidth = 0.5) +
  scale_x_log10() +
  scale_colour_manual(values = setNames(c(te_forest, te_red), lab), name = NULL) +
  labs(title = "Longer tracks stop paying when the centre moves",
       x = expression("tracking duration in units of" ~ tau ~ "(log scale)"),
       y = "relative RMSE of the area estimate") +
  theme_te(13) +
  theme(legend.position = "bottom")
