# Hardy-Weinberg expectations in R
# https://tidyecology.com/posts/hardy-weinberg-and-genotype-frequencies/
#
# 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 ----
library(ggplot2)

sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

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"))
}

## ---- counts ----
obs <- c(AA = 63, AB = 94, BB = 43)
n_ind <- sum(obs)
n_A <- 2 * obs["AA"] + obs["AB"]
n_B <- 2 * obs["BB"] + obs["AB"]
p_hat <- as.numeric(n_A / (2 * n_ind))

cat("individuals:", n_ind, " A alleles:", n_A, " B alleles:", n_B,
    " p:", round(p_hat, 4), "\n")

expfreq <- c(AA = p_hat^2, AB = 2 * p_hat * (1 - p_hat), BB = (1 - p_hat)^2)
expected <- expfreq * n_ind
print(round(rbind(observed = obs, expected = expected), 2))

## ---- fis ----
chi2 <- sum((obs - expected)^2 / expected)
p_chi <- pchisq(chi2, df = 1, lower.tail = FALSE)

het_obs <- as.numeric(obs["AB"] / n_ind)
het_exp <- as.numeric(expfreq["AB"])
f_is <- 1 - het_obs / het_exp

cat("chi-square:", round(chi2, 4), " df 1, p:", round(p_chi, 4), "\n")
cat("Ho:", round(het_obs, 4), " He:", round(het_exp, 4),
    " Fis:", round(f_is, 4), "\n")

## ---- exact ----
hwe_exact <- function(n_aa, n_ab, n_bb) {
  n <- n_aa + n_ab + n_bb
  na <- 2 * n_aa + n_ab
  nb <- 2 * n_bb + n_ab
  het <- seq(na %% 2, min(na, nb), by = 2)
  hom_a <- (na - het) / 2
  hom_b <- (nb - het) / 2
  logp <- lfactorial(n) - lfactorial(hom_a) - lfactorial(het) -
    lfactorial(hom_b) + het * log(2) +
    lfactorial(na) + lfactorial(nb) - lfactorial(2 * n)
  prob <- exp(logp)
  list(het = het, prob = prob,
       p_value = sum(prob[prob <= prob[het == n_ab] * (1 + 1e-9)]))
}

ex_big <- hwe_exact(obs["AA"], obs["AB"], obs["BB"])
cat("null probabilities sum to:", round(sum(ex_big$prob), 12), "\n")
cat("exact p:", round(ex_big$p_value, 4),
    " chi-square p:", round(p_chi, 4), "\n")

## ---- rare ----
rare <- c(AA = 41, AB = 7, BB = 2)
n_rare <- sum(rare)
p_rare <- as.numeric((2 * rare["AA"] + rare["AB"]) / (2 * n_rare))
exp_rare <- c(p_rare^2, 2 * p_rare * (1 - p_rare), (1 - p_rare)^2) * n_rare
chi2_rare <- sum((rare - exp_rare)^2 / exp_rare)
ex_rare <- hwe_exact(rare["AA"], rare["AB"], rare["BB"])

cat("minor allele frequency:", round(1 - p_rare, 4), "\n")
cat("expected counts:", round(exp_rare, 3), "\n")
cat("chi-square p:", round(pchisq(chi2_rare, 1, lower.tail = FALSE), 4),
    " exact p:", round(ex_rare$p_value, 4), "\n")

## ---- fig-exact-null ----
null_df <- data.frame(het = ex_rare$het, prob = ex_rare$prob)
ggplot(null_df, aes(het, prob)) +
  geom_col(fill = te_pal$sage, colour = te_pal$forest, width = 1.4) +
  geom_col(data = subset(null_df, het == 7), fill = te_pal$clay,
           colour = te_pal$forest, width = 1.4) +
  scale_x_continuous(breaks = null_df$het) +
  labs(title = "Only odd heterozygote counts are possible",
       subtitle = "41 / 7 / 2 genotypes, conditioning on 89 A and 11 B alleles",
       x = "heterozygotes in the sample", y = "probability under HWE") +
  theme_te()

## ---- wahlund ----
p_sub <- c(0.2, 0.8)
ho_sub <- 2 * p_sub * (1 - p_sub)
p_bar <- mean(p_sub)
he_tot <- 2 * p_bar * (1 - p_bar)
ho_pool <- mean(ho_sub)
var_p <- mean((p_sub - p_bar)^2)

cat("Ho pooled:", ho_pool, " He from pooled frequency:", he_tot,
    " Fis:", round(1 - ho_pool / he_tot, 4), "\n")
cat("He - Ho:", he_tot - ho_pool, "  2 * var(p):", 2 * var_p, "\n")
print(all.equal(he_tot - ho_pool, 2 * var_p))
cat("var(p) / (pbar * qbar):", var_p / (p_bar * (1 - p_bar)), "\n")

## ---- pooled-sample ----
set.seed(459)

draw_geno <- function(n, p, f = 0) {
  probs <- c(p^2 + f * p * (1 - p),
             2 * p * (1 - p) * (1 - f),
             (1 - p)^2 + f * p * (1 - p))
  as.vector(rmultinom(1, n, probs))
}

mix <- draw_geno(100, p_sub[1]) + draw_geno(100, p_sub[2])
names(mix) <- c("AA", "AB", "BB")
p_mix <- as.numeric((2 * mix["AA"] + mix["AB"]) / (2 * sum(mix)))
fis_mix <- 1 - as.numeric(mix["AB"] / sum(mix)) / (2 * p_mix * (1 - p_mix))

print(mix)
cat("p:", round(p_mix, 4), " Fis:", round(fis_mix, 4),
    " exact p:", signif(hwe_exact(mix[1], mix[2], mix[3])$p_value, 3), "\n")

## ---- dropout ----
set.seed(460)

true_geno <- draw_geno(300, 0.5)
lost <- rbinom(1, true_geno[2], 0.3)
lost_a <- rbinom(1, lost, 0.5)
scored <- c(true_geno[1] + lost_a, true_geno[2] - lost,
            true_geno[3] + lost - lost_a)
names(scored) <- names(true_geno) <- c("AA", "AB", "BB")
print(rbind(truth = true_geno, scored = scored))

p_sc <- as.numeric((2 * scored["AA"] + scored["AB"]) / (2 * sum(scored)))
fis_sc <- 1 - as.numeric(scored["AB"] / sum(scored)) / (2 * p_sc * (1 - p_sc))
cat("mis-scored heterozygotes:", lost, " p:", round(p_sc, 4),
    " Fis:", round(fis_sc, 4),
    " exact p:", signif(hwe_exact(scored[1], scored[2], scored[3])$p_value, 3),
    "\n")
p_true <- as.numeric((2 * true_geno["AA"] + true_geno["AB"]) / (2 * sum(true_geno)))
cat("truth, same sample: p:", sprintf("%.4f", p_true), " Fis:",
    round(1 - as.numeric(true_geno["AB"] / sum(true_geno)) / (2 * p_true * (1 - p_true)), 4),
    " exact p:",
    round(hwe_exact(true_geno[1], true_geno[2], true_geno[3])$p_value, 4), "\n")

## ---- power ----
set.seed(461)

power_hwe <- function(n, f, p = 0.3, nsim = 2000, alpha = 0.05) {
  rej <- 0
  for (i in seq_len(nsim)) {
    g <- draw_geno(n, p, f)
    rej <- rej + (hwe_exact(g[1], g[2], g[3])$p_value < alpha)
  }
  rej / nsim
}

grid_n <- c(25, 50, 100, 200, 400, 800)
pow <- data.frame(n = rep(grid_n, 2),
                  f_true = rep(c(0.1, 0.2), each = length(grid_n)))
pow$power <- mapply(power_hwe, pow$n, pow$f_true)
print(pow)

## ---- fig-power ----
ggplot(pow, aes(n, power, colour = factor(f_true))) +
  geom_hline(yintercept = 0.8, linetype = "dashed", colour = te_pal$line) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.2) +
  scale_x_log10(breaks = grid_n) +
  scale_colour_manual(values = c(`0.1` = te_pal$gold, `0.2` = te_pal$forest),
                      name = "true F") +
  labs(title = "A modest heterozygote deficit needs a large sample",
       subtitle = "exact test, alpha 0.05, minor allele frequency 0.3",
       x = "individuals genotyped (log scale)", y = "power") +
  theme_te()
