# Tweedie regression for biomass and cover with zeros
# https://tidyecology.com/posts/tweedie-regression-biomass/
#
# 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-07

## ---- dgp ----
set.seed(4230)
n   <- 400
x   <- round(runif(n, -2, 2), 3)               # standardised environmental gradient
b0  <- -0.3; b1 <- 0.9                          # true log-mean model
p   <- 1.55                                     # true Tweedie power in (1, 2)
phi <- 1.4                                      # true dispersion
mu  <- exp(b0 + b1 * x)
lam <- mu^(2 - p) / (phi * (2 - p))             # Poisson rate of clumps
shp <- (2 - p) / (p - 1)                        # gamma shape per clump
scl <- phi * (p - 1) * mu^(p - 1)               # gamma scale
N   <- rpois(n, lam)
y   <- vapply(seq_len(n), function(i)
         if (N[i] == 0) 0 else sum(rgamma(N[i], shape = shp, scale = scl[i])), numeric(1))
p228_zf   <- round(mean(y == 0), 3)
p228_mean <- round(mean(y), 2)
p228_p0   <- round(mean(exp(-lam)), 3)

## ---- tw-fit ----
suppressWarnings(suppressMessages(library(mgcv)))
f_tw <- gam(y ~ x, family = tw(), method = "REML")
p228_slope <- round(coef(f_tw)[2], 3)
p228_se    <- round(summary(f_tw)$p.table[2, 2], 3)
p228_phat  <- round(f_tw$family$getTheta(TRUE), 2)
p228_phi   <- round(f_tw$scale, 2)

## ---- two-part ----
pres <- as.integer(y > 0)
mb   <- glm(pres ~ x, family = binomial)                       # presence
mg   <- glm(y[pres == 1] ~ x[pres == 1], family = Gamma(link = "log"))  # positive part
xs   <- seq(-2, 2, length = 160)
m_tw <- as.vector(exp(predict(f_tw, data.frame(x = xs))))
m_dp <- plogis(coef(mb)[1] + coef(mb)[2] * xs) * exp(coef(mg)[1] + coef(mg)[2] * xs)
p228_presslope <- round(coef(mb)[2], 3)
p228_gamslope  <- round(coef(mg)[2], 3)
p228_meandiff  <- round(max(abs(m_tw - m_dp)), 3)

## ---- fig-fit ----
suppressWarnings(suppressMessages(library(ggplot2)))
theme_te <- function() {
  theme_minimal(base_size = 12) + theme(
    panel.grid.minor = element_blank(),
    panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
    plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
    panel.background = element_rect(fill = "#f5f4ee", colour = NA),
    axis.text  = element_text(colour = "#46604a"),
    axis.title = element_text(colour = "#2c3a31"),
    plot.title = element_text(colour = "#16241d", face = "bold"),
    plot.subtitle = element_text(colour = "#5d6b61"),
    legend.position = "top", legend.title = element_blank(),
    legend.text = element_text(colour = "#2c3a31"))
}
dl <- data.frame(xs, m_tw, m_dp)
ggplot() +
  geom_point(data = data.frame(x, y), aes(x, y), colour = "#275139", alpha = 0.4, size = 1.5) +
  geom_line(data = dl, aes(xs, m_tw, colour = "Tweedie mean"), linewidth = 1.1) +
  geom_line(data = dl, aes(xs, m_dp, colour = "Two-part mean"), linewidth = 1.1, linetype = "dashed") +
  scale_colour_manual(values = c("Tweedie mean" = "#275139", "Two-part mean" = "#b5534e")) +
  labs(x = "Environmental gradient (standardised)", y = "Biomass",
       title = "Tweedie regression for biomass with exact zeros") +
  theme_te()

## ---- log-constant ----
cs <- c(0.1, 1, 10)
p228_logc <- round(sapply(cs, function(cc) coef(lm(log(y + cc) ~ x))[2]), 3)

## ---- profile ----
pg <- seq(1.2, 1.9, by = 0.05)
ll <- sapply(pg, function(pp) {
  fp <- gam(y ~ x, family = Tweedie(p = pp, link = "log"), method = "REML")
  # for fixed p the coefficients do not depend on the dispersion, so only phi is maximised
  -optimize(function(ph) -sum(ldTweedie(y, mu = fitted(fp), p = pp, phi = ph)[, 1]),
            c(0.05, 20))$objective
})
p228_ppeak <- pg[which.max(ll)]

## ---- fig-profile ----
dp <- data.frame(pg, rll = ll - max(ll))
ggplot(dp, aes(pg, rll)) +
  geom_line(colour = "#275139", linewidth = 1.1) +
  geom_point(colour = "#275139", size = 2) +
  geom_vline(xintercept = p228_phat, colour = "#b5534e", linetype = "dashed") +
  labs(x = "Tweedie power parameter p", y = "Relative profile log-likelihood",
       title = "Estimating the Tweedie power") +
  theme_te()

## ---- monte-carlo ----
set.seed(77)
B <- 400
st <- sp <- so <- numeric(B)
for (b in 1:B) {
  Nb <- rpois(n, lam)
  yb <- vapply(seq_len(n), function(i)
          if (Nb[i] == 0) 0 else sum(rgamma(Nb[i], shape = shp, scale = scl[i])), numeric(1))
  fb <- gam(yb ~ x, family = tw(), method = "REML")
  st[b] <- coef(fb)[2]; sp[b] <- fb$family$getTheta(TRUE)
  so[b] <- coef(lm(log(yb + 1) ~ x))[2]
}
p228_twbias <- round(100 * (mean(st) - b1) / b1, 1)
p228_pbar   <- round(mean(sp), 2)
p228_obias  <- round(100 * (mean(so) - b1) / b1, 1)
