# Effective population size in R
# https://tidyecology.com/posts/effective-population-size/
#
# 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(ggplot2)

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"))
}

## ---- simulator ----
sim_ne <- function(n_m, n_f, gens = 40, reps = 200, seed = 1,
                   equalised = FALSE, w_shape = NULL) {
  set.seed(seed)
  n_tot <- n_m + n_f
  h_mat <- matrix(NA_real_, gens + 1, reps)
  vk <- numeric(reps)
  for (r in seq_len(reps)) {
    pop <- matrix(seq_len(2 * n_tot), ncol = 2, byrow = TRUE)
    for (g in 0:gens) {
      freq <- table(as.vector(pop))
      h_mat[g + 1, r] <- 1 - sum((freq / (2 * n_tot))^2)
      if (g == gens) break
      if (equalised) {
        n_pair <- min(n_m, n_f)
        per_pair <- ceiling(n_tot / n_pair)
        dads <- rep(seq_len(n_pair), each = per_pair)[seq_len(n_tot)]
        mums <- rep(n_m + seq_len(n_pair), each = per_pair)[seq_len(n_tot)]
      } else {
        w_m <- if (is.null(w_shape)) rep(1, n_m) else rgamma(n_m, w_shape, w_shape)
        w_f <- if (is.null(w_shape)) rep(1, n_f) else rgamma(n_f, w_shape, w_shape)
        dads <- sample(seq_len(n_m), n_tot, replace = TRUE, prob = w_m)
        mums <- sample(n_m + seq_len(n_f), n_tot, replace = TRUE, prob = w_f)
      }
      if (g == gens - 1) {
        vk[r] <- var(tabulate(c(dads, mums), nbins = n_tot))
      }
      from_dad <- pop[cbind(dads, sample(1:2, n_tot, replace = TRUE))]
      from_mum <- pop[cbind(mums, sample(1:2, n_tot, replace = TRUE))]
      pop <- cbind(from_dad, from_mum)
    }
  }
  h_bar <- rowMeans(h_mat)
  gen <- 0:gens
  slope <- coef(lm(log(h_bar) ~ gen))[[2]]
  list(h = h_bar, ne_hat = 1 / (2 * (1 - exp(slope))), vk = mean(vk))
}

## ---- scenarios ----
scen <- list(
  "even sex ratio, 50 + 50" = list(n_m = 50, n_f = 50),
  "skewed sex ratio, 10 + 90" = list(n_m = 10, n_f = 90),
  "equalised family size" = list(n_m = 50, n_f = 50, equalised = TRUE),
  "high variance in offspring" = list(n_m = 50, n_f = 50, w_shape = 0.3))

runs <- list()
tab <- NULL
for (nm in names(scen)) {
  a <- scen[[nm]]
  runs[[nm]] <- do.call(sim_ne, c(a, list(gens = 40, reps = 200, seed = 463)))
  tab <- rbind(tab, data.frame(
    scenario = nm, N = a$n_m + a$n_f,
    Vk = round(runs[[nm]]$vk, 3),
    Ne_measured = round(runs[[nm]]$ne_hat, 1),
    Ne_from_sex_ratio = 4 * a$n_m * a$n_f / (a$n_m + a$n_f),
    Ne_from_Vk = round((4 * (a$n_m + a$n_f) - 2) / (runs[[nm]]$vk + 2), 1)))
}
print(tab, row.names = FALSE)

## ---- fig-decay ----
decay_df <- do.call(rbind, lapply(names(runs), function(nm) {
  data.frame(generation = 0:40, h = runs[[nm]]$h,
             scenario = sprintf("%s (Ne %.0f)", nm, runs[[nm]]$ne_hat))
}))

ggplot(decay_df, aes(generation, h, colour = scenario)) +
  geom_line(linewidth = 0.9) +
  scale_y_log10() +
  scale_colour_manual(values = c(te_pal$forest, te_pal$gold, te_pal$sage,
                                 te_pal$clay), name = NULL) +
  labs(title = "Same census size, four rates of genetic loss",
       subtitle = "infinite-allele Wright-Fisher simulation, N = 100 adults throughout",
       x = "generation", y = "gene diversity (log scale)") +
  theme_te()

## ---- sexratio ----
sweep_m <- c(2, 5, 10, 25, 50)
sw <- t(sapply(sweep_m, function(m) {
  res <- sim_ne(m, 100 - m, gens = 30, reps = 150, seed = 4630 + m)
  c(males = m, Ne_measured = res$ne_hat,
    Ne_formula = 4 * m * (100 - m) / 100)
}))
print(round(sw, 1))

## ---- fig-sexratio ----
curve_df <- data.frame(males = 2:50)
curve_df$ne <- 4 * curve_df$males * (100 - curve_df$males) / 100

ggplot(curve_df, aes(males, ne)) +
  geom_line(colour = te_pal$sage, linewidth = 1.1) +
  geom_point(data = as.data.frame(sw), aes(males, Ne_measured),
             colour = te_pal$forest, size = 2.6) +
  labs(title = "The rarer sex sets the effective size",
       subtitle = "line: 4 Nm Nf/(Nm + Nf), points: measured from the diversity decay",
       x = "breeding males out of 100 adults", y = "effective size Ne") +
  theme_te()

## ---- cycle ----
h_cycle <- function(sizes, gens = 40, reps = 60, seed = 464) {
  set.seed(seed)
  h_mat <- matrix(NA_real_, gens + 1, reps)
  for (r in seq_len(reps)) {
    pop <- matrix(seq_len(2 * sizes[1]), ncol = 2, byrow = TRUE)
    for (g in 0:gens) {
      freq <- table(as.vector(pop))
      h_mat[g + 1, r] <- 1 - sum((freq / (2 * nrow(pop)))^2)
      if (g == gens) break
      n_next <- sizes[(g %% length(sizes)) + 1]
      par1 <- sample(nrow(pop), n_next, replace = TRUE)
      par2 <- sample(nrow(pop), n_next, replace = TRUE)
      pop <- cbind(pop[cbind(par1, sample(1:2, n_next, TRUE))],
                   pop[cbind(par2, sample(1:2, n_next, TRUE))])
    }
  }
  h_bar <- rowMeans(h_mat)
  gen <- 0:gens
  list(h = h_bar,
       ne_hat = 1 / (2 * (1 - exp(coef(lm(log(h_bar) ~ gen))[[2]]))))
}

cycle <- c(1000, 1000, 1000, 10)
cyc <- h_cycle(cycle)
cat("sizes in the cycle:", cycle, "\n")
cat("arithmetic mean:", mean(cycle),
    " harmonic mean:", round(length(cycle) / sum(1 / cycle), 2),
    " measured Ne:", round(cyc$ne_hat, 1), "\n")

## ---- fig-cycle ----
gen <- 0:40
ref_df <- data.frame(
  generation = rep(gen, 2),
  h = c(cyc$h[1] * (1 - 1 / (2 * mean(cycle)))^gen,
        cyc$h[1] * (1 - 1 / (2 * (length(cycle) / sum(1 / cycle))))^gen),
  which = rep(c("arithmetic mean, 752.5", "harmonic mean, 38.8"),
              each = length(gen)))

ggplot(data.frame(generation = gen, h = cyc$h), aes(generation, h)) +
  geom_line(data = ref_df, aes(generation, h, colour = which),
            linetype = "dashed", linewidth = 0.8) +
  geom_line(colour = te_pal$forest, linewidth = 1) +
  scale_y_log10() +
  scale_colour_manual(values = c(`arithmetic mean, 752.5` = te_pal$gold,
                                 `harmonic mean, 38.8` = te_pal$clay),
                      name = NULL) +
  labs(title = "The crash year sets the rate",
       subtitle = "solid: simulated cycle 1000, 1000, 1000, 10; dashed: constant-size expectations",
       x = "generation", y = "gene diversity (log scale)") +
  theme_te()
