# Siblings in an assignment baseline
# https://tidyecology.com/posts/siblings-in-an-assignment-baseline/
#
# 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-09-20

## ---- setup ----
library(ggplot2)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body))
}

## ---- engine ----
geno_loglik <- function(geno, p) {
  as.vector(geno %*% log(p) + (2 - geno) %*% log(1 - p)) +
    rowSums(geno == 1) * log(2)
}

est_freq <- function(geno, k = 0.5) {
  (colSums(geno) + k) / (2 * nrow(geno) + 2 * k)
}

sim_freqs <- function(n_loci, n_src, fst) {
  p_anc <- runif(n_loci, 0.05, 0.95)
  shape_a <- p_anc * (1 - fst) / fst
  shape_b <- (1 - p_anc) * (1 - fst) / fst
  matrix(rbeta(n_loci * n_src, rep(shape_a, n_src), rep(shape_b, n_src)),
         n_loci, n_src)
}

sim_geno <- function(p, n_ind) {
  matrix(rbinom(n_ind * length(p), 2, rep(p, each = n_ind)), n_ind, length(p))
}

loo_loglik <- function(ll, geno_list, who, k = 0.5) {
  for (s in seq_along(geno_list)) {
    g_s <- geno_list[[s]]
    tot <- colSums(g_s)
    rows <- which(who == s)
    for (q in seq_along(rows)) {
      p_out <- (tot - g_s[q, ] + k) / (2 * (nrow(g_s) - 1) + 2 * k)
      ll[rows[q], s] <- geno_loglik(g_s[q, , drop = FALSE], p_out)
    }
  }
  ll
}

# new: n_fam full-sib families of fam_size offspring (fam_size = 1 gives unrelated fish)
sim_families <- function(p, n_fam, fam_size) {
  if (fam_size == 1) return(list(geno = sim_geno(p, n_fam), fam = seq_len(n_fam)))
  n_l <- length(p)
  mum <- sim_geno(p, n_fam); dad <- sim_geno(p, n_fam)
  fam_id <- rep(seq_len(n_fam), each = fam_size)
  n_off <- n_fam * fam_size
  geno <- matrix(rbinom(n_off * n_l, 1, as.vector(mum[fam_id, ] / 2)), n_off) +
    matrix(rbinom(n_off * n_l, 1, as.vector(dad[fam_id, ] / 2)), n_off)
  list(geno = geno, fam = fam_id)
}

## ---- effective-copies ----
n_loci <- 100; n_src <- 3; fst_target <- 0.03; n_ind <- 40
designs <- data.frame(name = c("40 unrelated", "20 x 2", "8 x 5", "4 x 10"),
                      n_fam = c(40, 20, 8, 4), fam_size = c(1, 2, 5, 10))
designs$m_eff <- 4 * designs$n_fam * designs$fam_size / (designs$fam_size + 1)

set.seed(56001)
p_check <- runif(n_loci, 0.1, 0.9)
m_sim <- sapply(seq_len(nrow(designs)), function(d) {
  raw <- replicate(600, colSums(sim_families(p_check, designs$n_fam[d],
                                             designs$fam_size[d])$geno)) / (2 * n_ind)
  mean(p_check * (1 - p_check) / apply(raw, 1, var))
})
designs$m_sim <- m_sim
print(designs, row.names = FALSE, digits = 3)

## ---- nulls ----
n_fresh <- 100; n_null <- 3000; alpha <- 0.05

null_post <- function(geno, copies = 2 * nrow(geno)) {
  n <- nrow(geno); raw <- colSums(geno) / (2 * n); ph <- est_freq(geno)
  p_star <- matrix(rbeta(n_null * n_loci, rep(raw * copies + 0.5, each = n_null),
                         rep((1 - raw) * copies + 0.5, each = n_null)), n_null, n_loci)
  sort(geno_loglik(matrix(rbinom(n_null * n_loci, 2, as.vector(p_star)), n_null, n_loci), ph))
}

null_from <- function(p_gen, n_fam, fam_size) {  # simulate the baseline step from p_gen (vector, or one row per null fish)
  php <- if (is.matrix(p_gen)) as.vector(p_gen) else rep(p_gen, each = n_null)
  if (fam_size == 1) {
    tot <- rbinom(n_null * n_loci, 2 * n_fam, php)
  } else {
    n_hom <- rbinom(n_null * n_loci, 2 * n_fam, php^2)
    n_het <- rbinom(n_null * n_loci, 2 * n_fam - n_hom, 2 * php * (1 - php) / (1 - php^2))
    tot <- fam_size * n_hom + rbinom(n_null * n_loci, fam_size * n_het, 0.5)
  }
  p_re <- matrix((tot + 0.5) / (2 * n_fam * fam_size + 1), n_null, n_loci)
  g_new <- matrix(rbinom(n_null * n_loci, 2, php), n_null, n_loci)
  sort(rowSums(g_new * log(p_re) + (2 - g_new) * log(1 - p_re)) + rowSums(g_new == 1) * log(2))
}
null_design <- function(geno, n_fam, fam_size) null_from(est_freq(geno), n_fam, fam_size)

p_value <- function(null_sorted, obs) findInterval(obs, null_sorted) / length(null_sorted)

## ---- scoring ----
self_rates <- function(bl) {
  gl <- lapply(bl, `[[`, "geno"); fl <- lapply(bl, `[[`, "fam")
  who <- rep(seq_along(gl), sapply(gl, nrow)); g_all <- do.call(rbind, gl)
  ph <- sapply(gl, est_freq)
  ll_in <- sapply(seq_along(gl), function(s) geno_loglik(g_all, ph[, s]))
  hit <- function(ll, w) mean(apply(ll, 1, which.max) == w)
  ll_lfo <- ll_in                                  # leave the whole family out
  for (s in seq_along(gl)) {
    tot <- colSums(gl[[s]]); rows <- which(who == s)
    for (f in unique(fl[[s]])) {
      in_f <- which(fl[[s]] == f)
      p_out <- (tot - colSums(gl[[s]][in_f, , drop = FALSE]) + 0.5) /
        (2 * (nrow(gl[[s]]) - length(in_f)) + 1)
      ll_lfo[rows[in_f], s] <- geno_loglik(gl[[s]][in_f, , drop = FALSE], p_out)
    }
  }
  gp <- lapply(seq_along(gl), function(s) gl[[s]][!duplicated(fl[[s]]), , drop = FALSE])
  who_p <- rep(seq_along(gp), sapply(gp, nrow)); g_p <- do.call(rbind, gp)
  ll_p <- sapply(seq_along(gp), function(s) geno_loglik(g_p, est_freq(gp[[s]])))
  c(naive = hit(ll_in, who), loo = hit(loo_loglik(ll_in, gl, who), who),
    lfo = hit(ll_lfo, who), purge = hit(loo_loglik(ll_p, gp, who_p), who_p))
}

score_design <- function(p_set, fresh, n_fam, fam_size, wide = TRUE, mis = FALSE) {
  bl <- lapply(1:n_src, function(s) sim_families(p_set[, s], n_fam, fam_size))
  ph <- sapply(bl, function(b) est_freq(b$geno))
  m_copies <- 4 * n_fam * fam_size / (fam_size + 1)
  g_fresh <- do.call(rbind, fresh[1:n_src]); who_f <- rep(1:n_src, sapply(fresh[1:n_src], nrow))
  ll_f <- sapply(1:n_src, function(s) geno_loglik(g_fresh, ph[, s]))
  res <- c(size_post = 0, size_wide = NA, size_des = 0, size_as_4x10 = NA,
           size_as_20x2 = NA, size_as_unrel = NA, ll_obs = 0, ll_truth = 0,
           ll_post = 0, ll_des = 0, sd_post = 0, sd_des = 0)
  if (wide && fam_size > 1) res["size_wide"] <- 0
  if (mis) res[c("size_as_4x10", "size_as_20x2", "size_as_unrel")] <- 0
  out_post <- out_des <- out_4x10 <- out_20x2 <- out_unrel <- matrix(FALSE, nrow(fresh[[4]]), n_src)
  res_post <- res_des <- matrix(FALSE, nrow(g_fresh), n_src)   # residents of all sources vs each null
  for (s in 1:n_src) {
    g <- bl[[s]]$geno
    obs <- geno_loglik(fresh[[s]], ph[, s]); o4 <- geno_loglik(fresh[[4]], ph[, s])
    np <- null_post(g); nd <- null_design(g, n_fam, fam_size)
    res["size_post"] <- res["size_post"] + mean(p_value(np, obs) < alpha) / n_src
    res["size_des"] <- res["size_des"] + mean(p_value(nd, obs) < alpha) / n_src
    if (!is.na(res["size_wide"])) res["size_wide"] <- res["size_wide"] +
      mean(p_value(null_post(g, m_copies), obs) < alpha) / n_src
    if (mis) {
      n_4x10 <- null_design(g, 4, 10); n_20x2 <- null_design(g, 20, 2)
      res["size_as_4x10"] <- res["size_as_4x10"] + mean(p_value(n_4x10, obs) < alpha) / n_src
      res["size_as_20x2"] <- res["size_as_20x2"] + mean(p_value(n_20x2, obs) < alpha) / n_src
      n_unrel <- null_design(g, 40, 1)
      res["size_as_unrel"] <- res["size_as_unrel"] + mean(p_value(n_unrel, obs) < alpha) / n_src
      out_4x10[, s] <- p_value(n_4x10, o4) < alpha; out_20x2[, s] <- p_value(n_20x2, o4) < alpha
      out_unrel[, s] <- p_value(n_unrel, o4) < alpha
    }
    res[c("ll_obs", "ll_truth", "ll_post", "ll_des", "sd_post", "sd_des")] <-
      res[c("ll_obs", "ll_truth", "ll_post", "ll_des", "sd_post", "sd_des")] +
      c(mean(obs), mean(geno_loglik(fresh[[s]], p_set[, s])), mean(np), mean(nd), sd(np), sd(nd)) / n_src
    out_post[, s] <- p_value(np, o4) < alpha; out_des[, s] <- p_value(nd, o4) < alpha
    res_post[, s] <- p_value(np, ll_f[, s]) < alpha; res_des[, s] <- p_value(nd, ll_f[, s]) < alpha
  }
  sr <- self_rates(bl)
  if (fam_size == 1) sr[c("lfo", "purge")] <- NA
  pw_mis <- if (mis) c(power_as_4x10 = mean(rowSums(out_4x10) == n_src),
                       power_as_20x2 = mean(rowSums(out_20x2) == n_src),
                       power_as_unrel = mean(rowSums(out_unrel) == n_src)) else
    c(power_as_4x10 = NA, power_as_20x2 = NA, power_as_unrel = NA)
  c(res, power_post = mean(rowSums(out_post) == n_src), power_des = mean(rowSums(out_des) == n_src),
    pw_mis, all3_post = mean(rowSums(res_post) == n_src), all3_des = mean(rowSums(res_des) == n_src),
    sr, truth = mean(apply(ll_f, 1, which.max) == who_f))
}

run_sets <- function(n_sets, fst, dsg, ...) {
  do.call(rbind, lapply(seq_len(n_sets), function(i) {
    p_set <- sim_freqs(n_loci, n_src + 1, fst)          # the fourth source is never sampled
    fresh <- lapply(1:(n_src + 1), function(s) sim_geno(p_set[, s], n_fresh))
    do.call(rbind, lapply(seq_len(nrow(dsg)), function(d) data.frame(
      set = i, design = dsg$name[d],
      t(score_design(p_set, fresh, dsg$n_fam[d], dsg$fam_size[d],
                     mis = dsg$fam_size[d] == 5, ...)))))
  }))
}
mean_se <- function(tab, col, dsg) {
  v <- tab[[col]][tab$design == dsg]
  c(mean = mean(v), se = sd(v) / sqrt(length(v)))
}

## ---- main-grid ----
designs_main <- rbind(designs[, c("name", "n_fam", "fam_size")],
                      data.frame(name = c("13 unrelated", "7 unrelated"),
                                 n_fam = c(13, 7), fam_size = 1))
n_sets <- 24
set.seed(56010)
grid_main <- run_sets(n_sets, fst_target, designs_main)
ms <- function(col, dsg) mean_se(grid_main, col, dsg)
size_tab <- do.call(rbind, lapply(designs_main$name, function(nm) rbind(
  data.frame(design = nm, null = "source post's null", t(ms("size_post", nm))),
  data.frame(design = nm, null = "beta on effective copies", t(ms("size_wide", nm))),
  data.frame(design = nm, null = "whole-design null", t(ms("size_des", nm))))))
size_tab <- size_tab[!is.na(size_tab$mean), ]
sz <- function(nm, nl) size_tab$mean[size_tab$design == nm & size_tab$null == nl]
se_max <- max(size_tab$se)
per_set_85 <- grid_main$size_post[grid_main$design == "8 x 5"]

## ---- fig-size ----
size_tab$design <- factor(size_tab$design, levels = rev(designs_main$name))
size_tab$null <- factor(size_tab$null, levels = c("source post's null", "beta on effective copies",
                                                  "whole-design null"))
p_size <- ggplot(size_tab, aes(mean, design, colour = null)) +
  geom_vline(xintercept = alpha, colour = te_body, linetype = "dashed", linewidth = 0.4) +
  geom_errorbar(aes(xmin = pmax(mean - 2 * se, 0), xmax = mean + 2 * se), orientation = "y",
                width = 0.3, linewidth = 0.4, position = position_dodge(width = 0.6)) +
  geom_point(size = 2.6, position = position_dodge(width = 0.6)) +
  scale_colour_manual(values = c(te_rust, te_gold, te_forest), name = NULL) +
  scale_x_continuous(limits = c(0, NA)) +
  labs(x = "genuine residents excluded from their own source", y = "baseline per source",
       title = "Families make the exclusion test reject residents") +
  guides(colour = guide_legend(nrow = 1)) +
  theme_datasheet() + theme(legend.position = "bottom")
p_size

## ---- shift ----
shift_tab <- do.call(rbind, lapply(designs_main$name, function(nm) {
  x <- grid_main[grid_main$design == nm, ]
  data.frame(design = nm, resident_vs_truth = mean(x$ll_truth), resident_vs_estimate = mean(x$ll_obs),
             source_null = mean(x$ll_post), design_null = mean(x$ll_des),
             gap_source_sd = mean((x$ll_post - x$ll_obs) / x$sd_post),
             gap_design_sd = mean((x$ll_des - x$ll_obs) / x$sd_des))
}))
print(shift_tab, row.names = FALSE, digits = 3)
sh <- function(nm, col) shift_tab[[col]][shift_tab$design == nm]

## ---- oracle ----
null_predraw <- function(geno, n_fam, fam_size) {    # draw the centre from a beta posterior first
  pc <- est_freq(geno); m <- 4 * n_fam * fam_size / (fam_size + 1)
  null_from(matrix(rbeta(n_null * n_loci, rep(pc * m + 0.5, each = n_null),
                         rep((1 - pc) * m + 0.5, each = n_null)), n_null, n_loci), n_fam, fam_size)
}
set.seed(56025)
oracle <- t(replicate(10, {
  p_o <- sim_freqs(n_loci, n_src, fst_target)
  rowMeans(sapply(1:n_src, function(s) {
    g <- sim_families(p_o[, s], 4, 10)$geno
    obs <- geno_loglik(sim_geno(p_o[, s], n_fresh), est_freq(g))
    c(plug_in = mean(p_value(null_design(g, 4, 10), obs) < alpha),
      true_centre = mean(p_value(null_from(p_o[, s], 4, 10), obs) < alpha),
      predraw = mean(p_value(null_predraw(g, 4, 10), obs) < alpha))
  }))
}))
oracle_mean <- colMeans(oracle)
oracle_se <- apply(oracle, 2, sd) / sqrt(nrow(oracle))
predraw_gain <- oracle[, "plug_in"] - oracle[, "predraw"]
print(rbind(mean = oracle_mean, se = oracle_se), digits = 3)
c(gain = mean(predraw_gain), se = sd(predraw_gain) / sqrt(length(predraw_gain)))

## ---- fig-shift ----
set.seed(56020)
p_ex <- sim_freqs(n_loci, n_src, fst_target)
ex_rows <- do.call(rbind, lapply(c(1, 4), function(d) {
  g <- sim_families(p_ex[, 1], designs$n_fam[d], designs$fam_size[d])$geno
  obs <- geno_loglik(sim_geno(p_ex[, 1], 400), est_freq(g))
  rbind(data.frame(design = designs$name[d], what = "fresh residents", ll = obs),
        data.frame(design = designs$name[d], what = "source post's null", ll = null_post(g)),
        data.frame(design = designs$name[d], what = "whole-design null",
                   ll = null_design(g, designs$n_fam[d], designs$fam_size[d])))
}))
ex_rows$design <- factor(ex_rows$design, levels = c("40 unrelated", "4 x 10"))
cut_rows <- aggregate(ll ~ design + what, ex_rows[ex_rows$what != "fresh residents", ],
                      function(v) quantile(v, alpha))
ex_share <- tapply(seq_len(nrow(ex_rows)), ex_rows$design, function(i) {
  x <- ex_rows[i, ]; o <- x$ll[x$what == "fresh residents"]
  c(post = mean(o < quantile(x$ll[x$what == "source post's null"], alpha)),
    des = mean(o < quantile(x$ll[x$what == "whole-design null"], alpha)))
})
ex_cols <- c("fresh residents" = te_ink, "source post's null" = te_rust, "whole-design null" = te_forest)
p_shift <- ggplot(ex_rows, aes(ll, colour = what)) +
  geom_density(linewidth = 0.9, adjust = 1.2, key_glyph = "path") +
  geom_rug(data = cut_rows, aes(x = ll, colour = what), sides = "b", linewidth = 1.2,
           length = unit(0.06, "npc")) +
  facet_wrap(~ design, ncol = 1) +
  scale_colour_manual(values = ex_cols, name = NULL) +
  labs(x = "log-likelihood under the fish's own source", y = "density",
       title = "Residents sit below the source post's null") +
  theme_datasheet() +
  theme(legend.position = "bottom", strip.text = element_text(colour = te_ink, face = "bold"))
p_shift

## ---- fst-high ----
designs_high <- designs[c(1, 3, 4), c("name", "n_fam", "fam_size")]
n_sets_high <- 16
set.seed(56030)
grid_high <- run_sets(n_sets_high, 0.10, designs_high, wide = FALSE)
mh <- function(col, dsg) mean_se(grid_high, col, dsg)
high_tab <- do.call(rbind, lapply(designs_high$name, function(nm) rbind(
  data.frame(design = nm, null = "source post's null", size = mh("size_post", nm)[1],
             size_se = mh("size_post", nm)[2], power = mh("power_post", nm)[1],
             power_se = mh("power_post", nm)[2]),
  data.frame(design = nm, null = "whole-design null", size = mh("size_des", nm)[1],
             size_se = mh("size_des", nm)[2], power = mh("power_des", nm)[1],
             power_se = mh("power_des", nm)[2]))))
print(high_tab, row.names = FALSE, digits = 3)
hv <- function(nm, nl, col) high_tab[[col]][high_tab$design == nm & high_tab$null == nl]

## ---- misspecified ----
mis_cols <- c("size_as_4x10", "size_des", "size_as_20x2", "size_as_unrel")
pow_cols <- c("power_as_4x10", "power_des", "power_as_20x2", "power_as_unrel")
mis_tab <- data.frame(
  assumed = c("4 families of 10", "8 families of 5 (true)", "20 families of 2", "40 unrelated"),
  size_03 = sapply(mis_cols, function(v) ms(v, "8 x 5")[1]),
  size_10 = sapply(mis_cols, function(v) mh(v, "8 x 5")[1]),
  se_10 = sapply(mis_cols, function(v) mh(v, "8 x 5")[2]),
  catch_10 = sapply(pow_cols, function(v) mh(v, "8 x 5")[1]),
  catch_se_10 = sapply(pow_cols, function(v) mh(v, "8 x 5")[2]))
print(mis_tab, row.names = FALSE, digits = 3)

## ---- self-assignment ----
self_long <- do.call(rbind, lapply(designs$name, function(nm) {
  x <- grid_main[grid_main$design == nm, ]
  data.frame(design = nm,
             method = c("naive", "leave one out", "leave family out", "purge, then leave one out",
                        "fresh residents (truth)"),
             rate = c(mean(x$naive), mean(x$loo), mean(x$lfo), mean(x$purge), mean(x$truth)),
             se = c(sd(x$naive), sd(x$loo), sd(x$lfo), sd(x$purge), sd(x$truth)) / sqrt(nrow(x)))
}))
self_long <- self_long[!is.na(self_long$rate), ]
sv <- function(nm, mth) self_long$rate[self_long$design == nm & self_long$method == mth]
tr <- function(nm) mean(grid_main$truth[grid_main$design == nm])
optimism <- sapply(designs$name, function(nm) sv(nm, "leave one out") - tr(nm))
lfo_gap <- sapply(designs$name[-1], function(nm) sv(nm, "leave family out") - tr(nm))

## ---- fig-self ----
self_long$design <- factor(self_long$design, levels = rev(designs$name))
self_long$method <- factor(self_long$method, levels = c("naive", "leave one out", "leave family out",
                                                        "purge, then leave one out",
                                                        "fresh residents (truth)"))
p_self <- ggplot(self_long, aes(rate, design, colour = method, shape = method)) +
  geom_errorbar(aes(xmin = rate - 2 * se, xmax = rate + 2 * se), orientation = "y",
                width = 0.3, linewidth = 0.4, position = position_dodge(width = 0.7)) +
  geom_point(size = 2.6, position = position_dodge(width = 0.7)) +
  scale_colour_manual(values = c(te_rust, te_gold, te_forest, te_body, te_ink), name = NULL) +
  scale_shape_manual(values = c(16, 16, 17, 15, 18), name = NULL) +
  labs(x = "correct assignment rate", y = "baseline per source",
       title = "Leave-one-out flatters a family baseline") +
  guides(colour = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
  theme_datasheet() + theme(legend.position = "bottom")
p_self
