# Integrated step selection analysis in R
# https://tidyecology.com/posts/integrated-step-selection-issa/
#
# 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-04

## ---- setup ----
library(ggplot2)
te_canvas <- theme(plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
                   panel.background = element_rect(fill = "#f5f4ee", colour = NA))
library(grid)

res_raw <- function(x, y) {
  1.5 * exp(-((x - 36)^2 + (y - 64)^2) / (2 * 22^2)) +
  1.2 * exp(-((x - 70)^2 + (y - 38)^2) / (2 * 24^2)) +
  (-0.00034) * ((x - 50)^2 + (y - 50)^2)
}
gx <- seq(0, 100, length.out = 120)
grid_df <- expand.grid(x = gx, y = gx)
grid_df$raw <- res_raw(grid_df$x, grid_df$y)
mu_r <- mean(grid_df$raw); sd_r <- sd(grid_df$raw)
resource <- function(x, y) (res_raw(x, y) - mu_r) / sd_r

rvm <- function(n, mu, kappa) {
  out <- numeric(n); a <- 1 + sqrt(1 + 4 * kappa^2)
  b <- (a - sqrt(2 * a)) / (2 * kappa); r <- (1 + b^2) / (2 * b)
  for (i in seq_len(n)) {
    repeat {
      u1 <- runif(1); u2 <- runif(1); u3 <- runif(1)
      z <- cos(pi * u1); f <- (1 + r * z) / (r + z); cc <- kappa * (r - f)
      if (cc * (2 - cc) - u2 > 0 || log(cc / u2) + 1 - cc >= 0) break
    }
    out[i] <- sign(u3 - 0.5) * acos(f) + mu
  }
  ((out + pi) %% (2 * pi)) - pi
}

## ---- simulate ----
k_true <- 2.0; th_true <- 6.0; lam_true <- 1 / th_true; kap_true <- 0.9
beta_true <- 1.0
n <- 1500; M <- 300
set.seed(5150)
pos <- matrix(NA_real_, n + 1, 2); pos[1, ] <- c(45, 52)
heading <- numeric(n + 1); heading[1] <- runif(1, -pi, pi)
for (i in 1:n) {
  L <- rgamma(M, shape = k_true, scale = th_true)
  a <- rvm(M, 0, kap_true)
  ang <- heading[i] + a
  ex <- pos[i, 1] + L * cos(ang); ey <- pos[i, 2] + L * sin(ang)
  w <- exp(beta_true * resource(ex, ey))
  j <- sample.int(M, 1, prob = w)
  pos[i + 1, ] <- c(ex[j], ey[j]); heading[i + 1] <- ang[j]
}
dx <- diff(pos[, 1]); dy <- diff(pos[, 2])
obs_l <- sqrt(dx^2 + dy^2)
bearing <- atan2(dy, dx)
obs_turn <- ((diff(bearing) + pi) %% (2 * pi)) - pi

## ---- tentative ----
m1 <- mean(obs_l); v1 <- var(obs_l)
k0 <- m1^2 / v1; th0 <- v1 / m1; lam0 <- 1 / th0
C <- mean(cos(obs_turn)); S <- mean(sin(obs_turn)); Rbar <- sqrt(C^2 + S^2)
mu0 <- atan2(S, C)
kap0 <- if (Rbar < 0.53) 2 * Rbar + Rbar^3 + 5 * Rbar^5 / 6 else
        if (Rbar < 0.85) -0.4 + 1.39 * Rbar + 0.43 / (1 - Rbar) else
        1 / (Rbar^3 - 4 * Rbar^2 + 3 * Rbar)

## ---- strata ----
K <- 12
set.seed(20260713)
use_idx <- 2:n
n_str <- length(use_idx)
p <- 4
X <- matrix(NA_real_, n_str * (K + 1), p)   # columns: resource, log_l, l, cos_turn
row <- 1
for (s in seq_along(use_idx)) {
  i <- use_idx[s]
  lu <- obs_l[i]; tu <- obs_turn[i - 1]
  zu <- resource(pos[i + 1, 1], pos[i + 1, 2])
  X[row, ] <- c(zu, log(lu), lu, cos(tu)); row <- row + 1
  Ls <- rgamma(K, shape = k0, scale = th0)
  As <- rvm(K, mu0, kap0)
  ang <- heading[i] + As
  ex <- pos[i, 1] + Ls * cos(ang); ey <- pos[i, 2] + Ls * sin(ang)
  X[row:(row + K - 1), ] <- cbind(resource(ex, ey), log(Ls), Ls, cos(As))
  row <- row + K
}

nll <- function(b, cols) {
  eta <- as.vector(X[, cols, drop = FALSE] %*% b)
  em <- matrix(eta, nrow = K + 1)          # column = stratum, row 1 = used step
  -sum(em[1, ] - log(colSums(exp(em))))
}
opt0 <- optim(0, nll, cols = 1, method = "BFGS", hessian = TRUE, control = list(reltol = 1e-10))
b_ssf <- opt0$par; se_ssf <- sqrt(1 / opt0$hessian[1, 1])

## ---- fit-issa ----
opt1 <- optim(rep(0, p), nll, cols = 1:p, method = "BFGS", hessian = TRUE,
              control = list(reltol = 1e-10))
stopifnot(opt1$convergence == 0)   # check before inverting the Hessian
b <- opt1$par
se <- sqrt(diag(solve(opt1$hessian)))
names(b) <- names(se) <- c("resource", "log_l", "l", "cos_turn")

shape_hat <- k0 + b["log_l"]
rate_hat  <- lam0 - b["l"]
scale_hat <- 1 / rate_hat
kappa_hat <- kap0 + b["cos_turn"]

## ---- fig-kernel ----
ll <- seq(0.1, max(obs_l) * 1.02, length.out = 300)
dens_l <- rbind(
  data.frame(kernel = "observed (tentative)", l = ll, d = dgamma(ll, shape = k0, scale = th0)),
  data.frame(kernel = "iSSA corrected", l = ll, d = dgamma(ll, shape = shape_hat, scale = scale_hat)),
  data.frame(kernel = "true", l = ll, d = dgamma(ll, shape = k_true, scale = th_true)))
dens_l$kernel <- factor(dens_l$kernel, levels = c("observed (tentative)", "iSSA corrected", "true"))
cols3 <- c("observed (tentative)" = "#b5534e", "iSSA corrected" = "#275139", "true" = "#16241d")
lty3  <- c("observed (tentative)" = "solid", "iSSA corrected" = "solid", "true" = "22")
pa <- ggplot(dens_l, aes(l, d, colour = kernel, linetype = kernel)) +
  geom_line(linewidth = 0.7) +
  scale_colour_manual(values = cols3) + scale_linetype_manual(values = lty3) +
  labs(x = "step length", y = "density", colour = NULL, linetype = NULL, title = "Step-length kernel") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "inside", legend.position.inside = c(0.66, 0.82),
        legend.background = element_rect(fill = "#ffffff", colour = NA),
        plot.title = element_text(size = 10, colour = "#46604a"))
aa <- seq(-pi, pi, length.out = 300)
vm <- function(a, kappa) exp(kappa * cos(a)) / (2 * pi * besselI(kappa, 0))
dens_a <- rbind(
  data.frame(kernel = "observed (tentative)", a = aa, d = vm(aa, kap0)),
  data.frame(kernel = "iSSA corrected", a = aa, d = vm(aa, kappa_hat)),
  data.frame(kernel = "true", a = aa, d = vm(aa, kap_true)))
dens_a$kernel <- factor(dens_a$kernel, levels = c("observed (tentative)", "iSSA corrected", "true"))
pb <- ggplot(dens_a, aes(a, d, colour = kernel, linetype = kernel)) +
  geom_line(linewidth = 0.7) +
  scale_colour_manual(values = cols3) + scale_linetype_manual(values = lty3) +
  scale_x_continuous(breaks = c(-pi, -pi/2, 0, pi/2, pi), labels = c("-pi", "-pi/2", "0", "pi/2", "pi")) +
  labs(x = "turning angle", y = "density", colour = NULL, linetype = NULL, title = "Turning-angle kernel") +
  theme_minimal(base_size = 11) + te_canvas +
  theme(panel.grid.minor = element_blank(), legend.position = "none",
        plot.title = element_text(size = 10, colour = "#46604a"))
grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
print(pa, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pb, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

## ---- fig-debias ----
coef_df <- data.frame(
  model = factor(c("iSSA (movement + habitat)", "basic SSF (habitat only)"),
                 levels = c("basic SSF (habitat only)", "iSSA (movement + habitat)")),
  est = c(b["resource"], b_ssf), se = c(se["resource"], se_ssf))
ggplot(coef_df, aes(est, model)) +
  geom_vline(xintercept = beta_true, linetype = "dashed", colour = "#b5534e") +
  geom_errorbar(aes(xmin = est - 1.96 * se, xmax = est + 1.96 * se),
                orientation = "y", width = 0.14, colour = "#275139", linewidth = 0.6) +
  geom_point(colour = "#275139", size = 2.8) +
  annotate("text", x = beta_true, y = 2.4, label = "true selection",
           colour = "#b5534e", size = 3, hjust = 1.05) +
  labs(x = "habitat selection coefficient", y = NULL) +
  theme_minimal(base_size = 11) + te_canvas + theme(panel.grid.minor = element_blank())
