# Step lengths and turning angles in R
# https://tidyecology.com/posts/step-lengths-turning-angles/
#
# 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-15

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

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

set.seed(5122)
n <- 500
sl <- rgamma(n, shape = 2, scale = 15)   # step lengths (m)
turn <- rnorm(n, 0, 0.8)                  # turning angles, wrapped normal
head <- cumsum(turn)                      # absolute heading
pos <- data.frame(x = c(0, cumsum(sl * cos(head))),
                  y = c(0, cumsum(sl * sin(head))))
round(c(steps = n, extent_x = diff(range(pos$x)), extent_y = diff(range(pos$y))))

## ---- extract ----
step <- sqrt(diff(pos$x)^2 + diff(pos$y)^2)              # step lengths
bear <- atan2(diff(pos$y), diff(pos$x))                 # bearing of each step
tn <- diff(bear); tn <- (tn + pi) %% (2 * pi) - pi      # turning angle, wrapped to [-pi, pi)
round(c(mean_step = mean(step), median_step = median(step), max_step = max(step)), 1)

## ---- fit ----
aic <- function(fit, k) -2 * fit$loglik + 2 * k
fe <- fitdistr(step, "exponential")
fg <- fitdistr(step, "gamma")
fw <- fitdistr(step, "weibull")
tab <- data.frame(dist = c("exponential", "gamma", "weibull"),
                  AIC = round(c(aic(fe, 1), aic(fg, 2), aic(fw, 2)), 1))
tab$dAIC <- tab$AIC - min(tab$AIC)
tab
round(c(gamma_shape = fg$estimate[["shape"]],
        gamma_mean = fg$estimate[["shape"]] / fg$estimate[["rate"]]), 2)

## ---- fig-steplength ----
xs <- seq(0, max(step), length.out = 200)
dens <- rbind(
  data.frame(x = xs, d = dexp(xs, rate = fe$estimate["rate"]), fit = "exponential"),
  data.frame(x = xs, d = dgamma(xs, shape = fg$estimate["shape"], rate = fg$estimate["rate"]), fit = "gamma"))
ggplot() +
  geom_histogram(data = data.frame(step = step), aes(step, after_stat(density)),
                 bins = 30, fill = te_sage, colour = te_paper, alpha = 0.8) +
  geom_line(data = dens, aes(x, d, colour = fit), linewidth = 0.9) +
  scale_colour_manual(values = c(exponential = te_red, gamma = te_forest), name = NULL) +
  labs(title = "Step-length distribution with fitted models",
       x = "step length (m)", y = "density") +
  theme_te(13)

## ---- turning ----
Rbar <- sqrt(mean(cos(tn))^2 + mean(sin(tn))^2)
mang <- atan2(mean(sin(tn)), mean(cos(tn)))
nt <- length(tn); Z <- nt * Rbar^2
p_ray <- exp(-Z) * (1 + (2 * Z - Z^2) / (4 * nt) -
         (24 * Z - 132 * Z^2 + 76 * Z^3 - 9 * Z^4) / (288 * nt^2))
a_inv <- function(R) {
  if (R < 0.53) 2 * R + R^3 + 5 * R^5 / 6
  else if (R < 0.85) -0.4 + 1.39 * R + 0.43 / (1 - R)
  else 1 / (R^3 - 4 * R^2 + 3 * R)
}
round(c(Rbar = Rbar, mean_angle = mang, rayleigh_p = p_ray, kappa = a_inv(Rbar)), 3)

## ---- scaling ----
thin_metrics <- function(pos, m) {
  p <- pos[seq(1, nrow(pos), by = m), ]
  s <- sqrt(diff(p$x)^2 + diff(p$y)^2)
  b <- atan2(diff(p$y), diff(p$x)); t <- diff(b); t <- (t + pi) %% (2 * pi) - pi
  data.frame(m = m, path = sum(s), mean_step = mean(s),
             Rbar = sqrt(mean(cos(t))^2 + mean(sin(t))^2))
}
sc <- do.call(rbind, lapply(c(1, 2, 3, 4, 6, 8), thin_metrics, pos = pos))
sc$path_rel <- sc$path / sc$path[1]; sc$Rbar_rel <- sc$Rbar / sc$Rbar[1]
round(sc, 3)

## ---- fig-scaling ----
scl <- rbind(
  data.frame(m = sc$m, value = sc$path_rel, metric = "total path length"),
  data.frame(m = sc$m, value = sc$Rbar_rel, metric = "turning concentration (Rbar)"))
ggplot(scl, aes(m, value, colour = metric)) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = te_faint, linewidth = 0.3) +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  scale_colour_manual(values = c("total path length" = te_forest,
                                 "turning concentration (Rbar)" = te_gold), name = NULL) +
  labs(title = "Movement metrics shrink as the fix interval coarsens",
       x = "thinning interval m (keep every m-th fix)", y = "fraction of native value") +
  theme_te(13)
