# Species distribution modelling with GLM in R
# https://tidyecology.com/posts/species-distribution-model-glm/
#
# 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-05-10

## ---- setup ----
library(terra)
library(sf)
library(dplyr)
library(ggplot2)
library(patchwork)

## ---- helpers ----
as_df <- function(r, nm) {
  d <- as.data.frame(r, xy = TRUE)
  names(d)[3] <- nm
  d
}

## ---- theme-te ----
pal_paper <- "#f5f4ee"; pal_ink <- "#16241d"; pal_body <- "#2c3a31"
pal_forest <- "#275139"; pal_label <- "#46604a"; pal_line <- "#dad9ca"; pal_faint <- "#5d6b61"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(text = element_text(colour = pal_body),
          plot.title = element_text(colour = pal_ink, face = "bold", size = rel(1.05)),
          plot.subtitle = element_text(colour = pal_faint),
          axis.title = element_text(colour = pal_label), axis.text = element_text(colour = pal_body),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = pal_line, linewidth = 0.3),
          strip.text = element_text(colour = pal_ink, face = "bold"),
          legend.title = element_text(colour = pal_label),
          plot.background = element_rect(fill = pal_paper, colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          legend.key = element_rect(fill = pal_paper, colour = NA))
}

## ---- build-env ----
set.seed(42)
r_template <- rast(nrows = 80, ncols = 80, xmin = 0, xmax = 80, ymin = 0, ymax = 80)
xy <- xyFromCell(r_template, 1:ncell(r_template))

# temperature: warm in the south (low y), cool in the north, plus smooth noise
temp_trend <- 22 - 0.18 * xy[, "y"]
temp_noise <- rast(r_template); values(temp_noise) <- rnorm(ncell(r_template), 0, 2)
temp_noise <- focal(temp_noise, w = 9, fun = mean, na.rm = TRUE)
temp <- rast(r_template); values(temp) <- temp_trend
temp <- temp + temp_noise; names(temp) <- "temp"

# precipitation: dry in the west, wet in the east, plus smooth noise
prec_trend <- 500 + 5 * xy[, "x"]
prec_noise <- rast(r_template); values(prec_noise) <- rnorm(ncell(r_template), 0, 60)
prec_noise <- focal(prec_noise, w = 9, fun = mean, na.rm = TRUE)
prec <- rast(r_template); values(prec) <- prec_trend
prec <- prec + prec_noise; names(prec) <- "prec"

env <- c(temp, prec)
round(range(values(temp)), 1)   # temperature span
round(range(values(prec)), 0)   # precipitation span

## ---- fig-env ----
d_temp <- as_df(env[["temp"]], "value")
d_prec <- as_df(env[["prec"]], "value")
gg_temp <- ggplot(d_temp, aes(x, y, fill = value)) + geom_raster() +
  scale_fill_gradient(low = "#c9b458", high = "#1d5b4e", name = "C") +
  coord_equal(expand = FALSE) + labs(title = "Temperature", x = "Easting", y = "Northing") +
  theme_te(11)
gg_prec <- ggplot(d_prec, aes(x, y, fill = value)) + geom_raster() +
  scale_fill_gradient(low = "#c9b458", high = "#1d5b4e", name = "mm") +
  coord_equal(expand = FALSE) + labs(title = "Precipitation", x = "Easting", y = NULL) +
  theme_te(11)
(gg_temp | gg_prec) +
  plot_annotation(title = "Environmental predictors across the study region",
                  theme = theme(plot.title = element_text(colour = pal_ink, face = "bold", size = 14),
                                plot.background = element_rect(fill = pal_paper, colour = NA)))

## ---- true-niche ----
temp_opt <- 15; temp_tol <- 2.2
prec_opt <- 800; prec_tol <- 110
suit_true <- exp(-((values(temp) - temp_opt)^2) / (2 * temp_tol^2)) *
             exp(-((values(prec) - prec_opt)^2) / (2 * prec_tol^2))

set.seed(101)
pres_cells <- sample(ncell(r_template), 300, prob = suit_true, replace = FALSE)
pres_xy <- xy[pres_cells, ]

## ---- background ----
set.seed(202)
bg_cells <- sample(ncell(r_template), 1000)

pres_df <- data.frame(pa = 1, temp = values(temp)[pres_cells], prec = values(prec)[pres_cells])
bg_df   <- data.frame(pa = 0, temp = values(temp)[bg_cells],  prec = values(prec)[bg_cells])
dat <- rbind(pres_df, bg_df)
dat <- dat[complete.cases(dat), ]
c(rows = nrow(dat), presences = sum(dat$pa), background = sum(dat$pa == 0))

## ---- fit-glm ----
m <- glm(pa ~ poly(temp, 2) + poly(prec, 2), data = dat, family = binomial)
round(coef(m), 3)

## ---- dev-explained ----
dev_expl <- 1 - m$deviance / m$null.deviance
round(100 * dev_expl, 1)   # deviance explained, per cent

## ---- predict-raster ----
pred_r <- terra::predict(env, m, type = "response", na.rm = TRUE)
round(range(values(pred_r), na.rm = TRUE), 3)      # suitability range
round(cor(values(pred_r)[, 1], suit_true[, 1]), 3)      # agreement with the true surface

## ---- fig-suitability ----
d_pred <- as_df(pred_r, "suit")
d_pres <- as.data.frame(pres_xy); names(d_pres) <- c("x", "y")
ggplot(d_pred, aes(x, y)) +
  geom_raster(aes(fill = suit)) +
  geom_point(data = d_pres, colour = "#b5534e", size = 0.7, alpha = 0.8) +
  scale_fill_gradient(low = pal_paper, high = pal_forest, name = "Suitability", limits = c(0, NA)) +
  coord_equal(expand = FALSE) +
  labs(title = "Predicted habitat suitability with occurrence records",
       x = "Easting", y = "Northing") +
  theme_te(12)

## ---- response-curves ----
temp_seq <- seq(min(dat$temp), max(dat$temp), length.out = 100)
pr_t <- predict(m, data.frame(temp = temp_seq, prec = median(dat$prec)), type = "response")
prec_seq <- seq(min(dat$prec), max(dat$prec), length.out = 100)
pr_p <- predict(m, data.frame(temp = median(dat$temp), prec = prec_seq), type = "response")
c(temp_peak = round(temp_seq[which.max(pr_t)], 1),
  prec_peak = round(prec_seq[which.max(pr_p)], 0))

## ---- fig-response ----
d_resp <- rbind(data.frame(x = temp_seq, y = pr_t, predictor = "Temperature (C)"),
                data.frame(x = prec_seq, y = pr_p, predictor = "Precipitation (mm)"))
ggplot(d_resp, aes(x, y)) +
  geom_line(colour = pal_forest, linewidth = 1) +
  facet_wrap(~predictor, scales = "free_x") +
  labs(title = "Partial response curves from the fitted GLM",
       subtitle = "Other predictor held at its median",
       x = NULL, y = "Predicted suitability") +
  theme_te(12)
