# Related founders and marker kinship in a studbook
# https://tidyecology.com/posts/related-founders-and-marker-kinship/
#
# 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-14

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

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),
          strip.text       = element_text(colour = te_ink, face = "bold"))
}

## ---- founders ----
n_found <- 12
n_pop   <- 30
n_gen   <- 10
g_head  <- 6
n_rep   <- 150
n_loci  <- c(30, 100, 200, 1000)
n_ref   <- 24
founder_parents <- function(structure) {
  switch(structure,
    equal     = list(mum = rep(1:4, each = 3), dad = rep(1:4, each = 3)),
    one_large = list(mum = rep(1:5, c(6, 2, 2, 1, 1)), dad = rep(1:5, c(6, 2, 2, 1, 1))),
    half_sib  = list(mum = 1:12, dad = c(rep(1, 6), 2:7)))
}
founder_kinship <- function(parents) {
  k_f <- (outer(parents$mum, parents$mum, "==") +
          outer(parents$dad, parents$dad, "==")) / 8
  diag(k_f) <- 0.5
  k_f
}
gd_of  <- function(kin) 1 - mean(kin)
fge_of <- function(kin) 1 / (2 * mean(kin))

structures <- c("equal", "one_large", "half_sib")
k_ped <- diag(0.5, n_found)
start_tab <- t(sapply(structures, function(s) {
  k_f <- founder_kinship(founder_parents(s))
  c(gd_true = gd_of(k_f), fge_true = fge_of(k_f))
}))
gd_ped  <- gd_of(k_ped)
fge_ped <- fge_of(k_ped)

## ---- markers ----
wild_genotypes <- function(parents, p_wild) {
  n_loc <- length(p_wild)
  n_mum <- max(parents$mum); n_dad <- max(parents$dad)
  hap_mum <- matrix(runif(2 * n_mum * n_loc) < rep(p_wild, each = 2 * n_mum), ncol = n_loc)
  hap_dad <- matrix(runif(2 * n_dad * n_loc) < rep(p_wild, each = 2 * n_dad), ncol = n_loc)
  geno <- matrix(0, length(parents$mum), n_loc)
  for (i in seq_along(parents$mum)) {
    from_mum <- 2 * parents$mum[i] - 1 + (runif(n_loc) < 0.5)
    from_dad <- 2 * parents$dad[i] - 1 + (runif(n_loc) < 0.5)
    geno[i, ] <- hap_mum[cbind(from_mum, seq_len(n_loc))] +
                 hap_dad[cbind(from_dad, seq_len(n_loc))]
  }
  geno
}
marker_kinship <- function(geno, p_hat, estimate_diag = FALSE) {
  keep <- p_hat > 0 & p_hat < 1
  cent <- sweep(geno[, keep, drop = FALSE], 2, 2 * p_hat[keep])
  k_hat <- tcrossprod(cent) / (2 * sum(2 * p_hat[keep] * (1 - p_hat[keep])))
  if (!estimate_diag) diag(k_hat) <- 0.5
  k_hat
}
reweighted_freq <- function(geno, n_iter = 3) {
  p_hat <- colMeans(geno) / 2
  for (it in seq_len(n_iter)) {
    k_w <- marker_kinship(geno, p_hat)
    k_w[k_w < 0] <- 0
    w_found <- solve(k_w + diag(0.01, nrow(k_w)), rep(1, nrow(k_w)))
    w_found <- w_found / sum(w_found)
    p_hat <- pmin(pmax(as.vector(crossprod(w_found, geno)) / 2, 0), 1)
  }
  p_hat
}

## ---- management ----
pair_by_mk <- function(kin, male) {
  mk_rank <- rowMeans(kin)
  males <- which(male)[order(mk_rank[male])]
  fems  <- which(!male)[order(mk_rank[!male])]
  n_pair <- min(length(males), length(fems))
  pairs <- matrix(0L, n_pair, 2)
  for (k in seq_len(n_pair)) {
    below <- fems[kin[males[k], fems] < 1 / 16]
    chosen <- if (length(below)) below[1] else fems[which.min(kin[males[k], fems])]
    pairs[k, ] <- c(males[k], chosen)
    fems <- fems[fems != chosen]
  }
  pairs
}
greedy_young <- function(kin, pairs, n_off) {
  s_i <- pairs[, 1]; d_i <- pairs[, 2]
  k_between <- (kin[s_i, s_i] + kin[s_i, d_i] + kin[d_i, s_i] + kin[d_i, d_i]) / 4
  added <- (1 + kin[cbind(s_i, d_i)]) / 2
  n_young <- integer(nrow(pairs))
  for (k in seq_len(n_off)) {
    j <- which.min(added + runif(length(added), 0, 1e-9))
    n_young[j] <- n_young[j] + 1L
    added <- added + 2 * k_between[, j]
  }
  n_young
}
equal_young <- function(male, n_off) {
  males <- sample(which(male)); fems <- sample(which(!male))
  n_pair <- min(length(males), length(fems))
  n_young <- rep(n_off %/% n_pair, n_pair)
  extra <- n_off - sum(n_young)
  if (extra) { j <- sample.int(n_pair, extra); n_young[j] <- n_young[j] + 1L }
  list(pairs = cbind(males[seq_len(n_pair)], fems[seq_len(n_pair)]), n_young = n_young)
}
kin_next <- function(kin, dam, sire) {
  k_half <- (kin[dam, , drop = FALSE] + kin[sire, , drop = FALSE]) / 2
  k_off  <- (k_half[, dam, drop = FALSE] + k_half[, sire, drop = FALSE]) / 2
  diag(k_off) <- (1 + kin[cbind(dam, sire)]) / 2
  k_off
}
run_programme <- function(k_true, k_used, male_found, n_gen, rule = "mk") {
  male <- male_found
  traj <- matrix(0, n_gen, 3, dimnames = list(NULL, c("fge", "gd_rep", "f")))
  for (g in seq_len(n_gen)) {
    if (rule == "mk") {
      pairs <- pair_by_mk(k_used, male)
      n_young <- greedy_young(k_used, pairs, n_pop)
    } else {
      plan <- equal_young(male, n_pop); pairs <- plan$pairs; n_young <- plan$n_young
    }
    fam <- rep(seq_len(nrow(pairs)), n_young)
    f_new  <- k_true[cbind(pairs[fam, 1], pairs[fam, 2])]
    k_true <- kin_next(k_true, pairs[fam, 2], pairs[fam, 1])
    k_used <- kin_next(k_used, pairs[fam, 2], pairs[fam, 1])
    traj[g, ] <- c(fge_of(k_true), gd_of(k_used), mean(f_new))
    male <- sample(rep(c(TRUE, FALSE), length.out = n_pop))
  }
  traj
}

## ---- maingrid ----
set.seed(5320)

one_founder_set <- function(structure) {
  parents <- founder_parents(structure)
  k_true  <- founder_kinship(parents)
  male_found <- sample(rep(c(TRUE, FALSE), n_found / 2))
  p_wild  <- runif(max(n_loci), 0.05, 0.5)
  geno    <- wild_genotypes(parents, p_wild)
  ref_geno <- matrix(rbinom(n_ref * max(n_loci), 2, rep(p_wild, each = n_ref)), n_ref)
  used <- list(pedigree = k_ped, oracle = k_true)
  for (n_l in n_loci) {
    g_l <- geno[, seq_len(n_l)]
    used[[paste("known", n_l)]]      <- marker_kinship(g_l, p_wild[seq_len(n_l)])
    used[[paste("founders", n_l)]]   <- marker_kinship(g_l, colMeans(g_l) / 2)
    used[[paste("reweighted", n_l)]] <- marker_kinship(g_l, reweighted_freq(g_l))
    used[[paste("reference", n_l)]]  <- marker_kinship(g_l, colMeans(ref_geno[, seq_len(n_l)]) / 2)
  }
  runs <- lapply(used, function(k_u) run_programme(k_true, k_u, male_found, n_gen))
  runs$efs <- run_programme(k_true, k_true, male_found, n_gen, rule = "efs")
  runs
}
main_sims <- lapply(setNames(structures, structures), function(s)
  replicate(n_rep, one_founder_set(s), simplify = FALSE))

arm_names <- names(main_sims[[1]][[1]])
arm_stat <- function(structure, arm, g = g_head, col = "fge") {
  v <- sapply(main_sims[[structure]], function(r) r[[arm]][g, col])
  c(mean = mean(v), se = sd(v) / sqrt(length(v)))
}
rel_to_oracle <- function(structure, arm, g = g_head) {
  d <- sapply(main_sims[[structure]], function(r)
    r[[arm]][g, "fge"] / r[["oracle"]][g, "fge"])
  c(mean = mean(d), se = sd(d) / sqrt(length(d)))
}
gd_true_of <- function(structure, arm, g = g_head) {
  mean(sapply(main_sims[[structure]], function(r) 1 - 1 / (2 * r[[arm]][g, "fge"])))
}
summ <- do.call(rbind, lapply(structures, function(s) do.call(rbind, lapply(arm_names, function(a) {
  fg <- arm_stat(s, a); rl <- rel_to_oracle(s, a)
  data.frame(structure = s, arm = a, fge = fg["mean"], fge_se = fg["se"],
             rel = rl["mean"], rel_se = rl["se"],
             gd_true = gd_true_of(s, a),
             gd_rep = arm_stat(s, a, col = "gd_rep")["mean"],
             f = arm_stat(s, a, col = "f")["mean"], row.names = NULL)
}))))
pick <- function(s, a, col = "fge") summ[summ$structure == s & summ$arm == a, col]
max_se <- max(summ$fge_se)

## ---- numbers ----
cost_ped <- 1 - sapply(structures, function(s) pick(s, "pedigree", "rel"))
se_ped   <- sapply(structures, function(s) pick(s, "pedigree", "rel_se"))
efs_ped_gap <- max(abs(sapply(structures, function(s) pick(s, "pedigree") - pick(s, "efs"))))
gd_true_ped <- sapply(structures, function(s) pick(s, "pedigree", "gd_true"))
gd_rep_ped  <- sapply(structures, function(s) pick(s, "pedigree", "gd_rep"))
f_ped    <- sapply(structures, function(s) pick(s, "pedigree", "f"))
f_oracle <- sapply(structures, function(s) pick(s, "oracle", "f"))
gd_loss_large <- pick("one_large", "oracle", "gd_true") - pick("one_large", "pedigree", "gd_true")

## ---- fig-cost ----
struct_lab <- c(equal = "four litters of three", one_large = "litter of six, 2, 2, 1, 1",
                half_sib = "six paternal half sibs")
cost_df <- summ[summ$arm %in% c("pedigree", "efs"), ]
cost_df$structure <- factor(struct_lab[cost_df$structure], levels = rev(struct_lab))
cost_df$arm <- factor(c(pedigree = "mean kinship on pedigree", efs = "equal family sizes")[cost_df$arm],
                      levels = c("mean kinship on pedigree", "equal family sizes"))
p_cost <- ggplot(cost_df, aes(rel, structure, colour = arm)) +
  geom_vline(xintercept = 1, linetype = "dashed", colour = te_body, linewidth = 0.5) +
  geom_errorbar(aes(xmin = rel - 2 * rel_se, xmax = rel + 2 * rel_se), orientation = "y",
                width = 0.2, position = position_dodge(width = 0.5)) +
  geom_point(size = 2.8, position = position_dodge(width = 0.5)) +
  scale_colour_manual(values = c(te_rust, te_gold), name = NULL) +
  labs(x = "true FGE relative to true matrix", y = NULL, title = "Decisions") +
  theme_datasheet() + theme(legend.position = "right")
rep_df <- summ[summ$arm %in% c("pedigree", "known 200", "founders 200", "reference 200"), ]
rep_df$arm <- factor(c(pedigree = "pedigree", `known 200` = "200 SNPs, known freq.",
                       `founders 200` = "200 SNPs, founder freq.",
                       `reference 200` = "200 SNPs, reference freq.")[rep_df$arm],
                     levels = c("pedigree", "200 SNPs, founder freq.", "200 SNPs, known freq.",
                                "200 SNPs, reference freq."))
rep_df$structure <- factor(struct_lab[rep_df$structure], levels = struct_lab)
p_rep <- ggplot(rep_df, aes(gd_true, gd_rep, colour = arm, shape = structure)) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = te_body, linewidth = 0.5) +
  geom_point(size = 3) +
  scale_colour_manual(values = c(te_rust, "#8c8b7c", te_forest, "#6f8fa8"), name = NULL) +
  scale_shape_manual(values = c(16, 17, 1), name = NULL) +
  scale_x_continuous(limits = c(0.845, 0.9)) +
  scale_y_continuous(limits = c(0.845, 0.96)) +
  labs(x = "true gene diversity", y = "reported gene diversity", title = "Reports") +
  theme_datasheet() + theme(legend.position = "right", legend.box = "vertical")
(p_cost / p_rep) + plot_layout(heights = c(1, 1.5)) + plot_annotation(theme = theme_datasheet())

## ---- snpnumbers ----
rel_at <- function(s, src, n_l) pick(s, paste(src, n_l), "rel")
rel_se_at <- function(s, src, n_l) pick(s, paste(src, n_l), "rel_se")
known_equal <- sapply(n_loci, function(n_l) rel_at("equal", "known", n_l))
known_large <- sapply(n_loci, function(n_l) rel_at("one_large", "known", n_l))
found_large <- sapply(n_loci, function(n_l) rel_at("one_large", "founders", n_l))
reco <- function(s, src, n_l) {
  (rel_at(s, src, n_l) - pick(s, "pedigree", "rel")) / (1 - pick(s, "pedigree", "rel"))
}

## ---- fig-snps ----
src_lab <- c(known = "known wild frequencies", founders = "founder frequencies",
             reweighted = "reweighted founder frequencies", reference = "24 wild reference animals")
snp_df <- do.call(rbind, lapply(structures, function(s) do.call(rbind, lapply(names(src_lab), function(src)
  data.frame(structure = s, src = src, n_l = n_loci,
             rel = sapply(n_loci, function(n_l) rel_at(s, src, n_l)))))))
snp_df$src <- factor(src_lab[snp_df$src], levels = src_lab)
snp_df$structure <- factor(struct_lab[snp_df$structure], levels = struct_lab)
ped_df <- data.frame(structure = factor(struct_lab, levels = struct_lab),
                     rel = sapply(structures, function(s) pick(s, "pedigree", "rel")))
ggplot(snp_df, aes(n_l, rel, colour = src)) +
  geom_hline(yintercept = 1, colour = te_body, linewidth = 0.4) +
  geom_hline(data = ped_df, aes(yintercept = rel), linetype = "dashed", colour = te_rust,
             linewidth = 0.7) +
  geom_line(linewidth = 0.9) +
  geom_point(size = 2.2) +
  facet_wrap(~ structure, nrow = 1) +
  scale_x_log10(breaks = n_loci) +
  scale_colour_manual(values = c(te_forest, "#8c8b7c", te_gold, "#6f8fa8"), name = NULL) +
  labs(x = "SNPs (log scale)", y = "true FGE relative to true matrix") +
  theme_datasheet() + theme(legend.position = "bottom") +
  guides(colour = guide_legend(nrow = 2))

## ---- classes ----
set.seed(7320)
n_rep_class <- 200
class_est <- replicate(n_rep_class, {
  parents <- founder_parents("one_large"); k_true <- founder_kinship(parents)
  p_wild <- runif(200, 0.05, 0.5); geno <- wild_genotypes(parents, p_wild)
  ref_geno <- matrix(rbinom(n_ref * 200, 2, rep(p_wild, each = n_ref)), n_ref)
  big <- parents$mum == 1
  pair_class <- ifelse(outer(big, big, "&"), "within the litter of six",
                ifelse(k_true > 0, "within a pair of sibs", "unrelated"))
  up <- upper.tri(k_true)
  ests <- list(known = marker_kinship(geno, p_wild),
               founders = marker_kinship(geno, colMeans(geno) / 2),
               reweighted = marker_kinship(geno, reweighted_freq(geno)),
               reference = marker_kinship(geno, colMeans(ref_geno) / 2))
  sapply(ests, function(k_h) tapply(k_h[up], pair_class[up], mean))
}, simplify = "array")
class_mean <- apply(class_est, 1:2, mean)
p_share_big <- 6 / n_found

## ---- rowsums ----
set.seed(9320)
n_rep_row <- 100
row_est <- replicate(n_rep_row, {
  parents <- founder_parents("one_large"); k_true <- founder_kinship(parents)
  p_wild <- runif(1000, 0.05, 0.5); geno <- wild_genotypes(parents, p_wild)
  big <- parents$mum == 1
  out <- c(row_sum = max(abs(rowSums(marker_kinship(geno, colMeans(geno) / 2, estimate_diag = TRUE)))))
  for (n_l in c(200, 1000)) {
    g_l <- geno[, seq_len(n_l)]
    mk_f <- rowMeans(marker_kinship(g_l, colMeans(g_l) / 2))
    mk_k <- rowMeans(marker_kinship(g_l, p_wild[seq_len(n_l)]))
    out[paste0("gap_f", n_l)] <- mean(mk_f[big]) - mean(mk_f[!big])
    out[paste0("gap_k", n_l)] <- mean(mk_k[big]) - mean(mk_k[!big])
  }
  out["gap_true"] <- mean(rowMeans(k_true)[big]) - mean(rowMeans(k_true)[!big])
  out
})
row_gap <- rowMeans(row_est)
row_sum_max <- max(row_est["row_sum", ])

## ---- fp-guard-1 ----
stopifnot(row_sum_max < 1e-10)

## ---- fig-classes ----
class_df <- do.call(rbind, lapply(dimnames(class_est)[[2]], function(src)
  data.frame(pair = rep(dimnames(class_est)[[1]], n_rep_class), src = src,
             est = as.vector(class_est[, src, ]))))
class_df$src <- factor(src_lab[class_df$src], levels = src_lab)
class_df$pair <- factor(class_df$pair, levels = c("unrelated", "within a pair of sibs",
                                                  "within the litter of six"))
ggplot(class_df, aes(src, est, fill = src)) +
  geom_hline(yintercept = c(0, 0.25), linetype = "dashed", colour = te_body, linewidth = 0.5) +
  geom_boxplot(colour = te_ink, outlier.size = 0.8, width = 0.6, linewidth = 0.4) +
  facet_wrap(~ pair, nrow = 1) +
  scale_fill_manual(values = c(te_forest, "#8c8b7c", te_gold, "#6f8fa8"), name = NULL) +
  labs(x = NULL, y = "estimated founder kinship") +
  theme_datasheet() +
  theme(axis.text.x = element_blank(), legend.position = "bottom") +
  guides(fill = guide_legend(nrow = 2))

## ---- sibsize ----
set.seed(8320)
n_rep_sib <- 100
big_sizes <- c(2, 4, 6, 8, 10)
sib_parents <- function(k_big) {
  ids <- c(rep(1, k_big), 1 + seq_len(n_found - k_big))
  list(mum = ids, dad = ids)
}
sib_res <- do.call(rbind, lapply(big_sizes, function(k_big) {
  runs <- replicate(n_rep_sib, {
    parents <- sib_parents(k_big); k_true <- founder_kinship(parents)
    male_found <- sample(rep(c(TRUE, FALSE), n_found / 2))
    p_wild <- runif(200, 0.05, 0.5); geno <- wild_genotypes(parents, p_wild)
    arms <- list(oracle = k_true, pedigree = k_ped,
                 `known 200` = marker_kinship(geno, p_wild),
                 `founders 200` = marker_kinship(geno, colMeans(geno) / 2),
                 `reweighted 200` = marker_kinship(geno, reweighted_freq(geno)))
    sapply(arms, function(k_u) unname(run_programme(k_true, k_u, male_found, g_head)[g_head, "fge"]))
  })
  rel <- sweep(runs, 2, runs["oracle", ], "/")
  data.frame(k_big = k_big, arm = rownames(runs)[-1],
             rel = rowMeans(rel)[-1], se = apply(rel, 1, sd)[-1] / sqrt(n_rep_sib),
             row.names = NULL)
}))
sib_get <- function(k_big, arm) sib_res$rel[sib_res$k_big == k_big & sib_res$arm == arm]

## ---- horizon ----
hor_arms <- c("pedigree", "known 200", "founders 200", "reweighted 200", "reference 200")
hor_df <- do.call(rbind, lapply(hor_arms, function(a) data.frame(arm = a, gen = seq_len(n_gen),
  rel = sapply(seq_len(n_gen), function(g) rel_to_oracle("one_large", a, g)["mean"]))))
hor_get <- function(a, g) hor_df$rel[hor_df$arm == a & hor_df$gen == g]

## ---- fig-sibsize ----
arm_lab <- c(pedigree = "pedigree", `known 200` = "200 SNPs, known freq.",
             `founders 200` = "200 SNPs, founder freq.", `reweighted 200` = "200 SNPs, reweighted",
             `reference 200` = "200 SNPs, reference")
arm_cols <- setNames(c(te_rust, te_forest, "#8c8b7c", te_gold, "#6f8fa8"), arm_lab)
sib_res$arm_f <- factor(arm_lab[sib_res$arm], levels = arm_lab)
hor_df$arm_f  <- factor(arm_lab[hor_df$arm], levels = arm_lab)
p_sib <- ggplot(sib_res, aes(k_big, rel, colour = arm_f)) +
  geom_hline(yintercept = 1, colour = te_body, linewidth = 0.4) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.2) +
  scale_colour_manual(values = arm_cols, limits = unname(arm_lab), labels = unname(arm_lab), name = NULL) +
  guides(colour = "none") +
  scale_x_continuous(breaks = big_sizes) +
  labs(x = "size of the one litter", y = "true FGE relative to true matrix",
       title = "Litter size") +
  theme_datasheet()
p_hor <- ggplot(hor_df, aes(gen, rel, colour = arm_f)) +
  geom_hline(yintercept = 1, colour = te_body, linewidth = 0.4) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.2) +
  scale_colour_manual(values = arm_cols, limits = unname(arm_lab), labels = unname(arm_lab), name = NULL) +
  guides(colour = guide_legend(nrow = 2)) +
  scale_x_continuous(breaks = seq(2, n_gen, 2)) +
  labs(x = "generation", y = NULL, title = "Horizon, unequal founders") +
  theme_datasheet()
(p_sib | p_hor) + plot_layout(guides = "collect") +
  plot_annotation(theme = theme_datasheet()) &
  theme(legend.position = "bottom")

## ---- diagcheck ----
set.seed(6320)
n_rep_diag <- 150
diag_runs <- sapply(c("equal", "one_large"), function(s) rowMeans(replicate(n_rep_diag, {
  parents <- founder_parents(s); k_true <- founder_kinship(parents)
  male_found <- sample(rep(c(TRUE, FALSE), n_found / 2))
  p_wild <- runif(200, 0.05, 0.5); geno <- wild_genotypes(parents, p_wild)
  p_f <- colMeans(geno) / 2
  arms <- list(oracle = k_true,
               known_fixed = marker_kinship(geno, p_wild),
               known_est   = marker_kinship(geno, p_wild, estimate_diag = TRUE),
               found_fixed = marker_kinship(geno, p_f),
               found_est   = marker_kinship(geno, p_f, estimate_diag = TRUE))
  sapply(arms, function(k_u) unname(run_programme(k_true, k_u, male_found, g_head)[g_head, "fge"]))
})))
diag_rel <- sweep(diag_runs, 2, diag_runs["oracle", ], "/")
