# Partitioning the invasion growth rate
# https://tidyecology.com/posts/partitioning-invasion-growth/
#
# 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 ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12))
theme_set(theme_te)
col_full <- "#3a6b52"; col_flat <- "#b5651d"; col_ref <- "#555555"; col_alt <- "#8aa29e"

delta <- 0.1
states <- list(c(3, 0.5), c(0.5, 3))
inv_growth <- function(d, st = states) mean(log(sapply(st, function(s) (1 - d) + d * s[1] / s[2])))
r_full <- inv_growth(delta)
mean_ratio <- mean(sapply(states, `[`, 1)) / mean(sapply(states, `[`, 2))
r_flat <- log((1 - delta) + delta * mean_ratio)     # environment frozen at its mean
storage <- r_full - r_flat
r2 <- inv_growth(delta, lapply(states, rev))         # species 2 rare: outputs swapped

covEC <- function(p) {
  E <- log(sapply(states, `[`, 1))                                   # own environmental response
  C <- log(sapply(states, function(s) s[1]*p + s[2]*(1 - p)))        # competition experienced
  mean(E*C) - mean(E)*mean(C)
}
cov_rare <- covEC(0.001); cov_common <- covEC(0.999)

## ---- invasion ----
delta <- 0.1
states <- list(c(3, 0.5), c(0.5, 3))                # negatively correlated outputs
inv_growth <- function(d, st = states) {
  mean(log(sapply(st, function(s) (1 - d) + d * s[1] / s[2])))
}
c(species1 = inv_growth(0.1), species2 = inv_growth(0.1, lapply(states, rev)))  # species 2 rare: outputs swapped

## ---- partition ----
# fluctuation-free growth: environment held at its mean output for each species
mean_ratio <- mean(sapply(states, `[`, 1)) / mean(sapply(states, `[`, 2))
r_flat <- log((1 - delta) + delta * mean_ratio)
c(full = inv_growth(0.1), fluctuation_free = r_flat, storage_effect = inv_growth(0.1) - r_flat)

## ---- fig-partition ----
dp <- data.frame(part = factor(c("fluctuation-free", "storage effect", "full growth"),
                               levels = c("fluctuation-free", "storage effect", "full growth")),
                 val = c(r_flat, storage, r_full))
ggplot(dp, aes(part, val, fill = part)) +
  geom_col(width = 0.6) +
  geom_hline(yintercept = 0, colour = col_ref, linewidth = 0.4) +
  scale_fill_manual(values = c("fluctuation-free" = col_flat, "storage effect" = col_full,
                               "full growth" = col_alt), guide = "none") +
  labs(x = NULL, y = "Rare invader's growth rate",
       title = "The storage effect is the whole of the invasion growth")

## ---- covariance ----
covEC <- function(p) {
  E <- log(sapply(states, `[`, 1))                              # environmental response
  C <- log(sapply(states, function(s) s[1]*p + s[2]*(1 - p)))   # competition experienced
  mean(E*C) - mean(E)*mean(C)
}
c(rare = covEC(0.001), common = covEC(0.999))

## ---- fig-cov ----
dc <- data.frame(state = c("rare", "common"), cov = c(cov_rare, cov_common))
ggplot(dc, aes(state, cov, fill = state)) +
  geom_col(width = 0.55) +
  geom_hline(yintercept = 0, colour = col_ref, linewidth = 0.4) +
  scale_fill_manual(values = c("rare" = col_full, "common" = col_flat), guide = "none") +
  labs(x = NULL, y = "Cov(environment, competition)",
       title = "Rare species escape the crowding their good years would bring")
