# Checking an ideal free analysis
# https://tidyecology.com/posts/checking-an-ideal-free-analysis/
#
# 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 ----
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_ifd <- "#3a6b52"; col_desp <- "#b5651d"; col_ref <- "#555555"

## despotic vs ideal-free fitness
Qgood <- 60; Qpoor <- 40; N <- 100
ifd_intake <- (Qgood + Qpoor)/N               # everyone equal
n_dom <- 30
desp_dom  <- Qgood/n_dom                       # dominants alone in the good patch
desp_sub  <- Qpoor/(N - n_dom)                 # everyone else crowded in the poor patch
cv_ifd  <- 0
cv_desp <- sd(c(rep(desp_dom, n_dom), rep(desp_sub, N-n_dom))) /
           mean(c(rep(desp_dom, n_dom), rep(desp_sub, N-n_dom)))

## ---- despotic ----
Qgood <- 60; Qpoor <- 40; N <- 100; n_dom <- 30
ideal_free  <- (Qgood + Qpoor)/N               # everyone equal
despotic <- c(dominants = Qgood/n_dom, subordinates = Qpoor/(N - n_dom))
c(ideal_free_intake = ideal_free, despotic = despotic)

## ---- fig-despotic ----
di <- rbind(data.frame(i = 1:N, intake = ideal_free, dist = "ideal free"),
            data.frame(i = 1:N, intake = c(rep(desp_dom, n_dom), rep(desp_sub, N-n_dom)), dist = "despotic"))
ggplot(di, aes(i, intake, colour = dist)) +
  geom_point(size = 1.4) +
  scale_colour_manual(values = c("ideal free" = col_ifd, "despotic" = col_desp)) +
  labs(x = "Individual", y = "Per-capita intake", colour = NULL,
       title = "The ideal free distribution equalises fitness; despotism does not")

## ---- interference ----
# with interference of strength m, intake ~ Q * n^(-m); equalising gives n proportional to Q^(1/m)
interference_slope <- function(m) 1/m
sapply(c(0.7, 1.0, 1.5, 2.0), interference_slope)

## ---- fig-interference ----
dm <- data.frame(m = seq(0.5, 2.5, 0.05)); dm$slope <- 1/dm$m
ggplot(dm, aes(m, slope)) +
  geom_hline(yintercept = 1, colour = col_ref, linetype = "dashed") +
  geom_line(colour = col_desp, linewidth = 1) +
  labs(x = "Interference strength", y = "Matching slope it produces",
       title = "Interference alone can produce any amount of undermatching")
