# Slope and aspect: what a DEM does not measure
# https://tidyecology.com/posts/slope-and-aspect-from-a-dem/
#
# 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 ----
library(terra)
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))
}

make_dem <- function(noise) {
  r <- rast(xmin = 400000, xmax = 410000, ymin = 5050000, ymax = 5060000,
            resolution = 25, crs = "EPSG:32634")
  xy <- xyFromCell(r, 1:ncell(r))
  xs <- (xy[, 1] - 400000) / 1000
  ys <- (xy[, 2] - 5050000) / 1000
  values(r) <- 500 + 60 * sin(xs * 2.2) + 75 * cos(ys * 1.7) +
    45 * sin((xs + ys) * 1.3) +
    120 * exp(-(((xs - 3.2)^2 + (ys - 6.4)^2) / 3)) +
    rnorm(ncell(r), 0, noise)
  names(r) <- "elevation"
  r
}

set.seed(20260812)
dem <- make_dem(noise = 1.5)
dem

## ---- neighbours ----
slope8 <- terrain(dem, v = "slope", unit = "degrees", neighbors = 8)
slope4 <- terrain(dem, v = "slope", unit = "degrees", neighbors = 4)

global(c(slope8, slope4), c("mean", "max"), na.rm = TRUE)

## ---- gap ----
gap <- values(slope4)[, 1] - values(slope8)[, 1]
round(c(mean_of_map      = mean(gap, na.rm = TRUE),
        median_abs_cell  = median(abs(gap), na.rm = TRUE),
        p90_abs_cell     = quantile(abs(gap), 0.9, na.rm = TRUE),
        max_abs_cell     = max(abs(gap), na.rm = TRUE)), 3)

## ---- grain ----
grain_row <- function(f) {
  r <- if (f == 1) dem else aggregate(dem, fact = f, fun = "mean")
  s <- terrain(r, v = "slope", unit = "degrees")
  data.frame(cell_m = f * 25,
             mean = global(s, "mean", na.rm = TRUE)[1, 1],
             p95  = global(s, function(v, ...) quantile(v, 0.95, na.rm = TRUE))[1, 1],
             max  = global(s, "max", na.rm = TRUE)[1, 1])
}
grain <- do.call(rbind, lapply(c(1, 2, 4, 8, 16), grain_row))
round(grain, 2)

## ---- roughness ----
sweep_noise <- function(nz) {
  set.seed(20260812)
  r  <- make_dem(nz)
  s8 <- terrain(r, v = "slope", unit = "degrees", neighbors = 8)
  s4 <- terrain(r, v = "slope", unit = "degrees", neighbors = 4)
  s1 <- terrain(aggregate(r, fact = 4, fun = "mean"), v = "slope",
                unit = "degrees")
  s2 <- terrain(aggregate(r, fact = 16, fun = "mean"), v = "slope",
                unit = "degrees")
  data.frame(noise_m = nz,
             n8_25m  = global(s8, "mean", na.rm = TRUE)[1, 1],
             n4_25m  = global(s4, "mean", na.rm = TRUE)[1, 1],
             n8_100m = global(s1, "mean", na.rm = TRUE)[1, 1],
             n8_400m = global(s2, "mean", na.rm = TRUE)[1, 1])
}
rough <- do.call(rbind, lapply(c(0, 0.5, 1.5, 3, 4), sweep_noise))
round(rough, 3)

## ---- fig-roughness ----
long <- data.frame(
  noise = rep(rough$noise_m, 4),
  slope = c(rough$n8_25m, rough$n4_25m, rough$n8_100m, rough$n8_400m),
  rule  = rep(c("25 m, eight neighbours", "25 m, four neighbours",
                "100 m, eight neighbours", "400 m, eight neighbours"),
              each = nrow(rough)))
long$rule <- factor(long$rule, levels = c("25 m, four neighbours",
                                          "25 m, eight neighbours",
                                          "100 m, eight neighbours",
                                          "400 m, eight neighbours"))

ggplot(long, aes(x = noise, y = slope, colour = rule)) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.2) +
  scale_colour_manual(values = c(te_rust, te_forest, te_gold, te_ink)) +
  labs(x = "vertical noise in the elevation model (metres)",
       y = "mean slope (degrees)",
       colour = NULL,
       title = "The landform is fixed; only the noise changes") +
  guides(colour = guide_legend(nrow = 2, byrow = TRUE)) +
  theme_datasheet() +
  theme(legend.position = "bottom")

## ---- aspect ----
asp <- terrain(dem, v = "aspect", unit = "degrees")
a   <- values(asp)[, 1]
ar  <- a * pi / 180

c(arithmetic_mean = mean(a, na.rm = TRUE),
  circular_mean   = (atan2(mean(sin(ar), na.rm = TRUE),
                           mean(cos(ar), na.rm = TRUE)) %% (2 * pi)) * 180 / pi)

## ---- flat ----
lake <- dem
flat_cells <- cellFromRowColCombine(lake, 100:160, 100:160)
values(lake)[flat_cells] <- 470

asp_lake   <- terrain(lake, v = "aspect", unit = "degrees")
slope_lake <- terrain(lake, v = "slope",  unit = "degrees")
inner      <- cellFromRowColCombine(lake, 105:155, 105:155)

values(asp_lake)[inner[1]]

c(every_flat_cell_the_same = all(values(asp_lake)[inner] == 90),
  slope_exactly_zero       = values(slope_lake)[inner[1]] == 0)

## ---- northness ----
northness <- cos(ar)
eastness  <- sin(ar)

set.seed(11)
idx <- sample(which(!is.na(northness)), 300)
plots <- data.frame(elev   = values(dem)[idx, 1],
                    aspect = a[idx],
                    north  = northness[idx],
                    east   = eastness[idx])

# richness really does depend on aspect, through northness alone
plots$rich <- 18 + 4 * plots$north - 0.02 * (plots$elev - 500) +
              rnorm(nrow(plots), 0, 2.2)

## ---- models ----
m_degrees <- lm(rich ~ aspect + elev, data = plots)
m_split   <- lm(rich ~ north + east + elev, data = plots)

round(coef(summary(m_degrees)), 4)
round(coef(summary(m_split)), 4)
c(r2_degrees = summary(m_degrees)$r.squared,
  r2_split   = summary(m_split)$r.squared)

## ---- amplitude ----
b <- coef(m_split)
c(amplitude       = sqrt(b[["north"]]^2 + b[["east"]]^2),
  preferred_deg   = (atan2(b[["east"]], b[["north"]]) %% (2 * pi)) * 180 / pi)

## ---- fig-aspect ----
sc <- rbind(
  data.frame(x = plots$aspect, y = plots$rich, panel = "aspect (degrees)"),
  data.frame(x = plots$north,  y = plots$rich, panel = "northness (cosine of aspect)"))
sc$panel <- factor(sc$panel, levels = unique(sc$panel))

ggplot(sc, aes(x = x, y = y)) +
  geom_point(aes(colour = panel), alpha = 0.5, size = 1.8) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE,
              colour = te_ink, linewidth = 0.8) +
  facet_wrap(~ panel, scales = "free_x") +
  scale_colour_manual(values = c(te_rust, te_forest)) +
  labs(x = NULL, y = "species richness",
       title = "The same predictor, encoded two ways") +
  theme_datasheet() +
  theme(legend.position = "none",
        strip.text = element_text(colour = te_ink, face = "bold"))
