Read the genealogy at one position in the same forward sample. Then
compare discrete Wright–Fisher waiting times with the Kingman coalescent
and use the mutation clock to connect an ancestor’s age to sequence
differences. Keep both RDS inputs under data/population_history/.
library(hpgR)
options(repr.plot.width = 9, repr.plot.height = 4.2, repr.plot.pointsize = 13,
repr.plot.bg = "white", warn = 1)
blue <- "#265991"; orange <- "#D65F22"
drawFigure <- function(name, draw, width = 9, height = 3) {
directory <- Sys.getenv("P8149_FIGURE_DIR")
if (nzchar(directory)) {
dir.create(directory, recursive = TRUE, showWarnings = FALSE)
pdf(file.path(directory, paste0(name, ".pdf")), width = width, height = height,
family = "Helvetica", pointsize = 13, useDingbats = FALSE, bg = "white")
tryCatch(draw(), finally = dev.off())
}
if ("IRkernel" %in% loadedNamespaces()) draw()
invisible(NULL)
}
Source
ancestry_truth <- readRDS("data/population_history/ancestry_truth.rds")
observed <- readRDS("data/population_history/observed.rds")Follow the earlier simulation at a fixed site¶
Replay the original size history, founder sampling, mutation, recombination and seed. Record which parental copy supplied site 5,000 during every meiosis. Recording consumes no additional random draws. Check that all sampled DNA exactly matches the earlier observed matrix before opening its ancestry.
The displayed window is generations 14–20 after founding, during the 20-individual bottleneck. Gray dots show all 40 copies in each generation; blue paths connect the ancestors of the twelve sampled haplotypes. Time runs downward. The DNA is sampled later, after expansion to 1,000 individuals.
specification <- populationHistoryDesign()
population_design <- specification$design
recorded_example <- populationAncestryExample()
simulation <- recorded_example$simulation
stopifnot(identical(simulation$observed, observed))
tree <- populationTree(simulation, site = 5000L, samples = 1:12)
tree_summary <- pgTreeSummaries(tree)
print(c(chromosome = 1, site = 5000, sampled_haplotypes = tree$n,
pair_age = tree_summary$pair_time, root_age = tree_summary$TMRCA))
stopifnot(identical(recorded_example$trees, ancestry_truth$trees),
identical(recorded_example$four, ancestry_truth$four))
chromosome site sampled_haplotypes pair_age root_age
1 5000 12 461 461
treePositions <- function(tree) {
children <- split(tree$edges$child, tree$edges$parent)
leaves <- function(id) {
child <- children[[as.character(id)]]
if (!length(child)) return(id)
unlist(lapply(child, leaves), use.names = FALSE)
}
ordered <- leaves(tree$root)
x <- setNames(numeric(nrow(tree$nodes)), tree$nodes$id)
x[as.character(ordered)] <- seq_along(ordered)
for (id in tree$nodes$id[order(tree$nodes$time)]) {
child <- children[[as.character(id)]]
if (length(child)) x[as.character(id)] <- mean(x[as.character(child)])
}
x
}
drawRecordedTree <- function(tree, cutoff = Inf) {
x <- treePositions(tree)
age <- setNames(tree$nodes$time, tree$nodes$id)
summary <- pgTreeSummaries(tree)
plot(NA, xlim = c(.5, tree$n + 3), ylim = c(0, max(60, summary$TMRCA) * 1.12),
xaxt = "n", xlab = "Sampled DNA copy", ylab = "Generations before sampling")
if (summary$TMRCA > 60) {
abline(h = 60, col = "gray65", lty = 3)
text(3.5, 60, "Founding", pos = 1, cex = .85, col = "gray45")
}
for (i in seq_len(nrow(tree$edges))) {
parent <- as.character(tree$edges$parent[i]); child <- as.character(tree$edges$child[i])
highlight <- any(1:2 %in% tree$descendants[[child]]) &&
age[child] < summary$pair_time
color <- if (highlight) blue else "gray55"
if (age[child] < cutoff) segments(x[child], age[child], x[child],
min(age[parent],cutoff), col = color, lwd = 2)
if (age[parent] <= cutoff) segments(x[child], age[parent], x[parent], age[parent],
col = color, lwd = 2)
}
samples <- as.character(tree$sample_nodes)
axis(1, x[samples], tree$sample_ids, tick = FALSE, cex.axis = .85)
shared <- which(vapply(tree$descendants, function(d) all(1:2 %in% d), logical(1)))
pair_node <- names(tree$descendants)[shared[which.min(age[shared])]]
if (summary$pair_time <= cutoff) points(x[pair_node], summary$pair_time, pch = 18, col = blue, cex = 1.2)
if (summary$TMRCA <= cutoff) points(x[as.character(tree$root)], summary$TMRCA, pch = 16, col = orange, cex = 1.1)
legend("topright", as.expression(list(
bquote(T[1*","*2] == .(summary$pair_time)),
bquote(T[plain(MRCA)] == .(summary$TMRCA)))),
col = c(blue, orange), lty = c(1, NA), pch = c(18, 16), bty = "n",
cex = .85, y.intersp = 1.8, inset = .02)
}
drawFigure("p5_recorded_paths", function() {
par(mar = c(4.3, 4.6, 2.2, .7), bg = "white")
end <- population_design$bottleneck_generations
generations <- seq.int(end - 6L, end)
pools <- lapply(generations, function(g) seq_len(40L))
transmission <- simulation$records$copyParents$parents
burnin <- population_design$burnin_generations
copies <- as.vector(rbind(2L * simulation$truth$sample_indices - 1L,
2L * simulation$truth$sample_indices))[1:12]
for (g in seq.int(60L, end + 1L)) copies <- transmission[[burnin + g]][copies, 1L]
ancestors <- vector("list", length(generations))
ancestors[[length(generations)]] <- unique(copies)
for (i in seq.int(length(generations) - 1L, 1L))
ancestors[[i]] <- unique(transmission[[burnin + generations[i+1L]]][ancestors[[i+1L]], 1L])
maximum <- max(lengths(pools))
plot(NA, xlim = c(.5, maximum + .5), ylim = c(end + .6, generations[1L] - .6),
xaxt = "n", yaxt = "n", xlab = "Copy index within the generation",
ylab = "Generation after founding", main = "Bottleneck: 20 individuals")
axis(1, c(1, 10, 20, 30, 40))
axis(2, generations, generations, las = 1)
for (i in seq_along(pools))
points(seq_along(pools[[i]]), rep(generations[i], length(pools[[i]])),
pch = 16, cex = .65, col = "gray80")
for (i in seq_len(length(generations) - 1L)) {
child <- ancestors[[i + 1L]]
parent <- transmission[[burnin + generations[i+1L]]][child, 1L]
arrows(match(parent, pools[[i]]), rep(generations[i], length(child)),
match(child, pools[[i + 1L]]), rep(generations[i + 1L], length(child)),
length = .055, col = blue, lwd = 1.8)
}
for (i in seq_along(ancestors))
points(match(ancestors[[i]], pools[[i]]), rep(generations[i], length(ancestors[[i]])),
pch = 16, cex = .85, col = blue)
}, width = 6.8, height = 5.4)

Read ages and branch lengths on the recorded tree¶
Collapse paths with a single child while keeping branching ancestors and all twelve sampled-copy labels. Integer-time simultaneous mergers remain. The simulation recorded the ancestral burn-in as well as the founder event and expansion, so ancestors older than founding are part of the same record.
is the age of H1 and H2’s common ancestor. is the root age for all twelve copies. Here both are 461 generations: H1 and H2 meet at the root. A branch spans its parent age minus its child age. A node age and a waiting interval are different quantities.
drawFigure("p5_recorded_tree", function() {
par(mar = c(4.3, 4.8, 1.2, 1), bg = "white")
drawRecordedTree(tree)
})
stopifnot(sum(tree_summary$branch_generations) == tree_summary$total_branch_length,
sum(tree_summary$waiting_times) == tree_summary$TMRCA)

directory <- Sys.getenv("P8149_FIGURE_DIR")
if (nzchar(directory)) {
pdf(file.path(directory,"coalescent_genealogy.pdf"),width=9,height=4.5,
family="Helvetica",pointsize=13,useDingbats=FALSE,bg="white")
for (cutoff in c(0,sort(unique(tree$nodes$time[tree$nodes$time>0])))) {
par(mar=c(4.4,4.8,1.5,.8))
drawRecordedTree(tree,cutoff=cutoff)
}
dev.off()
}
if ("IRkernel" %in% loadedNamespaces()) drawRecordedTree(tree)

Founder identity and allele differences¶
As a mechanism check, isolate the same 20-individual, 20-generation bottleneck. Set mutation to zero and follow founder labels and binary alleles through the same parental draws. This control checks ; it is not a new observed DNA dataset.
founder_check <- founderDiversityExample(N = population_design$founder_size,
generations = population_design$bottleneck_generations)
drawFigure("founder_ibd_diversity_check", function() {
x <- founder_check$summary
par(mar = c(4.5, 4.7, 2, 1), bg = "white")
plot(x$generation, x$nonIBD, type = "l", col = blue, lwd = 3,
ylim = c(0, 1.05), xlab = "Generations of neutral copying",
ylab = expression(1-F[t]~~"or"~~H[t]/H[0]))
lines(x$generation, x$diversityRatio, col = orange, lwd = 3)
lines(x$generation, x$expectation, lty = 2, lwd = 2)
legend("bottomleft", c("1 - F from founder labels", "H / H0 from allele differences",
"Wright-Fisher expectation"), col = c(blue, orange, "black"),
lty = c(1, 1, 2), lwd = c(3, 3, 2), bty = "n", cex = .85)
mtext("Bottleneck control: N = 20; mutation off; 200 runs", side = 3, line = .5,
col = "#B33B32", cex = .85)
}, height = 3.8)

Simulate the sample’s ancestors¶
Two distinct lineages choose the same parent copy with probability in each discrete generation. For constant size, their waiting time has geometric survival . Its mean is generations.
The large-population Kingman coalescent joins a uniformly chosen pair at each ancestral event. With lineages and constant size, the waiting time is exponential with rate . When size varies with ancestral age , use the current rate
Update this rate when population size changes and continue to the sample MRCA. A branch of length receives a Poisson number of mutations with mean ; its descendants inherit those mutations. The later comparison uses independent random genealogies from each model.
A pair sampled before founding¶
For a constant-size reference, use the same ancestral , mutation rate and 10,000-base chromosome length. Turn recombination off to isolate a single genealogy. The mean pairwise age is 200 generations. The Poisson clock predicts 100 differences on average. This calculation is conditional on the nonrecombining infinite-sites approximation.
set.seed(9001)
Ne <- population_design$ancestral_size
mu <- population_design$mutation_rate
L <- population_design$sites_per_chromosome
T2 <- rgeom(3000, prob = 1 / (2 * Ne)) + 1
differences <- rpois(length(T2), lambda = 2 * mu * L * T2)
stopifnot(all(T2 >= 1), all(differences >= 0))
print(c(mean_wait = mean(T2), model_wait = 2 * Ne,
mean_differences = mean(differences), model_differences = 4 * Ne * mu * L))
drawFigure("p5_pair_waiting", function() {
par(mfrow = c(1, 2), mar = c(4.3, 4.4, 1.3, .7), bg = "white")
plot(ecdf(T2), xlim = c(0, 1000), verticals = TRUE, do.points = FALSE,
xlab = "Generations before sampling", ylab = "Cumulative probability", main = "")
curve(1 - (1 - 1 / (2 * Ne))^floor(x), add = TRUE, col = blue, lwd = 2)
curve(1 - exp(-x / (2 * Ne)), add = TRUE, col = orange, lty = 2, lwd = 2)
legend("bottomright", c("WF sample", "Geometric", "Exponential"),
col = c("black", blue, orange), lty = c(1, 1, 2), bty = "n", cex = .85,
y.intersp = 1.8, inset = c(.02, .04))
hist(differences, breaks = 35, col = "#A7C4D9", border = "white",
xlab = "Pairwise differences in 10 kb", main = "")
abline(v = 4 * Ne * mu * L, col = orange, lwd = 2)
})
mean_wait model_wait mean_differences model_differences
199.14800 200.00000 99.53933 100.00000

Compare discrete WF ancestry with the Kingman approximation¶
Draw 200 genealogies per model, with twelve sampled haplotypes and the same founder, bottleneck and expansion history. The discrete Wright–Fisher calculation follows sampled ancestors backward, one generation at a time. Kingman uses continuous waiting times with the same generation-specific population sizes.
The second experiment multiplies all population sizes and durations by ten: ancestral size 100 to 1,000, founders 20 to 200, final size 1,000 to 10,000, bottleneck duration 20 to 200 generations and growth duration 40 to 400 generations. The sample stays at twelve copies. Divide the mutation rate by ten to keep mutation exposure comparable in the sequence comparison below.
This tests the Kingman approximation as the sample becomes a smaller fraction of the population. The plot shows actual generations; compare the two models within each panel. Each branch receives the same symmetric binary mutation model.
matched_main <- matchedHistoryDraws(replicates = 200L, baseSeed = 7814900L)
matched_scaled <- matchedHistoryDraws(replicates = 200L, scale = 10L, baseSeed = 8814900L)
matched <- rbind(matched_main$results, matched_scaled$results)
stopifnot(!anyDuplicated(c(matched$ancestry_seed, matched$mutation_seed)))
print(aggregate(cbind(pair_time, TMRCA, S, pi_region, multifurcation) ~ scale + model,
matched, mean), row.names = FALSE)
drawFigure("p5_matched_genealogies", function() {
par(mfrow = c(1, 2), mar = c(4.4, 4.5, 3.2, .7))
for (scale in c(1, 10)) {
z <- matched[matched$scale == scale, ]
title <- if (scale == 1)
"20 founders; growth to 1,000\n20 bottleneck + 40 growth generations" else
"200 founders; growth to 10,000\n200 bottleneck + 400 growth generations"
plot(ecdf(z$TMRCA[z$model == "Discrete WF"]),
verticals = TRUE, do.points = FALSE, col = blue, lwd = 2.5,
xlim = c(0, 1400 * scale), xlab = "Sample MRCA age (generations)",
ylab = "Cumulative probability", main = title, cex.main = .95)
lines(ecdf(z$TMRCA[z$model == "Kingman"]),
verticals = TRUE, do.points = FALSE, col = orange, lwd = 2.5)
legend("bottomright", c("WF ancestry (by generation)", "Kingman coalescent"),
col = c(blue, orange), lty = 1, lwd = 2.5, bty = "n", cex = .75)
}
}, height = 3.8)
scale model pair_time TMRCA S pi_region multifurcation
1 Discrete WF 128.3500 278.0400 228.320 70.03432 0.185
10 Discrete WF 1448.4200 2739.5950 227.415 70.48591 0.025
1 Kingman 148.5218 290.1132 231.140 73.49530 0.000
10 Kingman 1323.1169 2656.7747 224.020 68.04977 0.000

Simultaneous mergers¶
Discrete generations can merge more than two lineages at once. Kingman joins one pair per event. Compare the frequency of multifurcating nodes in the same repeated histories; the tenfold size-and-time scaling reduces them. For distinct copies in one generation, the no-merger probability is .
mergers <- aggregate(multifurcation ~ scale + model, matched, mean)
print(mergers, row.names = FALSE)
drawFigure("p5_recent_mergers", function() {
par(mar = c(4.5, 4.8, 1.2, .8))
z <- mergers[mergers$model == "Discrete WF", ]
barplot(100 * z$multifurcation, names.arg = c("Main history", "10x scale"),
col = blue, border = NA, ylab = "Trees with a multifurcation (%)", ylim = c(0, 50))
}, width = 5, height = 3.5)
scale model multifurcation
1 Discrete WF 0.185
10 Discrete WF 0.025
1 Kingman 0.000
10 Kingman 0.000

Sequence variation on these genealogies¶
Both models use symmetric recurrent binary mutations on integer sites. The red curve is the infinite-sites coalescent expectation under the actual size schedule, computed from the demographic SFS expectation. It is an approximation to the finite-site mutations, not for a constant population. A root state of zero specifies the mutation overlay; main-DNA analyses use the original forward states, including mutations older than the sample MRCA.
Both ancestry comparisons use the same Poisson branch-mutation overlay. It approximates the main forward simulator’s per-generation parental mutation step.
drawFigure("p5_matched_sequences", function() {
par(mfrow = c(1, 2), mar = c(4.4, 4.6, 1.8, .7))
means <- rbind(colMeans(matched_main$sfs[1:200, ]), colMeans(matched_main$sfs[201:400, ]))
matplot(1:11, t(means), type = "b", pch = c(16, 1), lty = 1, lwd = 2,
col = c(blue, orange), xlab = "Copies carrying allele 1", ylab = "Mean variable sites per 10 kb")
lines(1:11, matched_main$expectation, col = "#B33B32", lwd = 2)
legend("topright", c("Discrete WF", "Kingman", "Generating-history expectation"),
col = c(blue, orange, "#B33B32"), lty = 1, bty = "n", cex = .72)
boxplot(pi_region ~ model, data = matched[matched$scale == 1, ],
col = c(blue, orange), ylab = "Mean pairwise differences", xlab = "")
})

Constant-size summaries of a changing history¶
Apply and to the same repeated histories. Red lines show their infinite-sites expectations under the generating history; neither must equal the ancestral size of 100. For the fixed pair, also compare with its recorded age. Recurrent mutation makes this Poisson clock approximate.
drawFigure("forward_coalescent_comparison", function() {
par(mfrow = c(1, 2), mar = c(5, 4.7, 2, .7))
for (scale in c(1, 10)) {
bank <- if (scale == 1) matched_main else matched_scaled
z <- bank$results; denom <- 4 * bank$mutationRate * bank$length
wh <- 2 * (1:11) * (12 - (1:11)) / (12 * 11)
boxplot(list(z$pi_region[z$model == "Discrete WF"] / denom,
z$pi_region[z$model == "Kingman"] / denom,
z$S[z$model == "Discrete WF"] / (sum(1/(1:11))*denom),
z$S[z$model == "Kingman"] / (sum(1/(1:11))*denom)),
names = c("WF\nH", "Coal\nH", "WF\nW", "Coal\nW"),
col = c(blue, orange), outline = FALSE, ylab = "Constant-size summary",
main = paste("History scale =", scale))
target <- c(sum(bank$expectation*wh), sum(bank$expectation)/sum(1/(1:11))) / denom
segments(c(.6,2.6), target, c(2.4,4.4), target, col = "#B33B32", lwd = 2)
}
}, height = 3.6)
clock <- matched_main$results[matched_main$results$model == "Kingman", ]
clock$estimate <- clock$pair_differences / (2 * population_design$mutation_rate * 10000)
drawFigure("pairwise_time_recovery", function() {
par(mar = c(4.6, 4.8, 1.5, .8))
maximum <- max(clock$pair_time, clock$estimate)*1.05
plot(clock$pair_time, clock$estimate, pch = 16, col = adjustcolor(blue,.4),
xlim = c(0,maximum), ylim = c(0,maximum), xlab = "Recorded pair age (generations)",
ylab = "Pair age estimated from differences")
abline(0,1,col="#B33B32",lwd=2)
}, width = 5.2, height = 4.2)


The recorded tree describes the same sampled DNA at chromosome 1, site 5,000. Its ancestral ages can be read directly from the forward transmission record. The later repeated simulations check how well a coalescent approximation reproduces discrete inheritance. Population size and sample fraction affect that approximation, especially for recent mergers.