# Correlated random walks and net displacement
# https://tidyecology.com/posts/correlated-random-walk/
#
# 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-14

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

## ---- sim ----
library(ggplot2); library(dplyr); library(tidyr)

sim_walk <- function(n, seed, mode = c("crw", "bounded", "directed"),
                     sigma_turn = 0.6, D = 12, wdir = 0.12) {
  mode <- match.arg(mode)
  set.seed(seed)
  sl <- rgamma(n, shape = 2, scale = 1)
  x <- y <- numeric(n + 1)
  heading <- runif(1, 0, 2 * pi)
  for (t in 1:n) {
    heading <- heading + rnorm(1, 0, sigma_turn)          # persistence
    if (mode == "bounded") {                              # pull home grows with distance
      d <- sqrt(x[t]^2 + y[t]^2); w <- min(1, d / D)
      b <- atan2(-y[t], -x[t])
      heading <- atan2((1 - w) * sin(heading) + w * sin(b),
                       (1 - w) * cos(heading) + w * cos(b))
    } else if (mode == "directed") {                      # constant bias toward +x
      heading <- atan2((1 - wdir) * sin(heading) + wdir * sin(0),
                       (1 - wdir) * cos(heading) + wdir * cos(0))
    }
    x[t + 1] <- x[t] + sl[t] * cos(heading)
    y[t + 1] <- y[t] + sl[t] * sin(heading)
  }
  data.frame(step = 0:n, x = x, y = y)
}

n <- 300
ex_crw <- sim_walk(n, 21, "crw")
ex_bnd <- sim_walk(n, 21, "bounded")
ex_dir <- sim_walk(n, 21, "directed")
round(c(crw = sqrt(tail(ex_crw$x, 1)^2 + tail(ex_crw$y, 1)^2),
        bounded = sqrt(tail(ex_bnd$x, 1)^2 + tail(ex_bnd$y, 1)^2),
        directed = sqrt(tail(ex_dir$x, 1)^2 + tail(ex_dir$y, 1)^2)), 1)

## ---- fig-trajectories ----
traj <- rbind(cbind(ex_crw, regime = "correlated"),
              cbind(ex_bnd, regime = "bounded (home range)"),
              cbind(ex_dir, regime = "directed (migration)"))
traj$regime <- factor(traj$regime,
  levels = c("bounded (home range)", "correlated", "directed (migration)"))
ggplot(traj, aes(x, y, colour = regime)) +
  geom_path(linewidth = 0.5, alpha = 0.9) +
  geom_point(data = subset(traj, step == 0), size = 2.4, colour = te_ink) +
  scale_colour_manual(values = c("bounded (home range)" = te_gold,
                                 "correlated" = te_forest,
                                 "directed (migration)" = te_red), name = NULL) +
  coord_equal() +
  labs(title = "Three movement regimes from a common start", x = "easting", y = "northing") +
  theme_te(13)

## ---- nsd ----
mean_nsd <- function(mode, reps = 1000) {
  M <- matrix(0, reps, n + 1)
  for (r in 1:reps) {
    w <- sim_walk(n, 5000 + r, mode)
    M[r, ] <- w$x^2 + w$y^2
  }
  colMeans(M)
}
nsd_crw <- mean_nsd("crw"); nsd_bnd <- mean_nsd("bounded"); nsd_dir <- mean_nsd("directed")

s1 <- 2; s2 <- 2 * 1 + (2 * 1)^2           # E[l] = 2, E[l^2] = var + mean^2 = 6
cc <- exp(-0.6^2 / 2)                       # mean cosine of the turning angle
ks <- function(k) k * s2 + 2 * s1^2 * (cc / (1 - cc)) * (k - (1 - cc^k) / (1 - cc))
ks_vals <- sapply(0:n, ks)

round(c(mean_cosine = cc, nsd_crw = nsd_crw[n + 1], ks = ks_vals[n + 1],
        crw_ks_ratio = nsd_crw[n + 1] / ks_vals[n + 1],
        nsd_bounded = nsd_bnd[n + 1], nsd_directed = nsd_dir[n + 1]), 3)

## ---- fig-nsd ----
steps <- 0:n
nd <- rbind(
  data.frame(step = steps, nsd = nsd_bnd, regime = "bounded (home range)"),
  data.frame(step = steps, nsd = nsd_crw, regime = "correlated"),
  data.frame(step = steps, nsd = nsd_dir, regime = "directed (migration)"))
nd$regime <- factor(nd$regime,
  levels = c("bounded (home range)", "correlated", "directed (migration)"))
ggplot(nd, aes(step, nsd, colour = regime)) +
  geom_line(linewidth = 0.9) +
  geom_line(data = data.frame(step = steps, nsd = ks_vals), aes(step, nsd),
            colour = te_faint, linetype = "dashed", linewidth = 0.6, inherit.aes = FALSE) +
  scale_colour_manual(values = c("bounded (home range)" = te_gold,
                                 "correlated" = te_forest,
                                 "directed (migration)" = te_red), name = NULL) +
  labs(title = "Net squared displacement separates the regimes", x = "step number",
       y = "mean net squared displacement") +
  theme_te(13)

## ---- exponent ----
half <- (n / 2):n
slope <- function(v) coef(lm(log(v[half + 1]) ~ log(half)))[2]
round(c(bounded = slope(nsd_bnd), correlated = slope(nsd_crw), directed = slope(nsd_dir)), 2)
