How can one person’s genome record population sizes thousands of generations ago? Start with the four DNA windows in E.1. Estimate a three-epoch history, then compare one pair with all 28 pairs from four diploid individuals. At the end, compare a population size decline with a decline in gene flow.
Read Pritchard, Chapter 3.3, Fig. 3.63 alongside Population Size from One Genome in the lecture.
library(hpgR)
options(repr.plot.width = 9, repr.plot.height = 3.8)
olderSize <- 10000
boundary <- 5000
windowLength <- 4000L
mu <- 1.25e-8
rho <- 1e-8Four DNA windows¶
In the local-ancestry HMM, the hidden state records the source of a chromosome copy. Here it records the local common ancestor’s time bin. The window index moves along the chromosome. Time within a state counts generations backward. Recombination can change the state. Given ancestor time , the chance of at least one heterozygous site in callable bases is approximately . The model averages this emission within each bin.
model <- pairwiseCoalescentModel(10000, olderSize, boundary, windowLength, mu, rho)
model
y <- c(1L, 1L, 0L, 0L)
posterior <- hmmPosterior(t(model$emission[, y + 1L]), model$transition, model$initial)
c(likelihood = exp(posterior$log_likelihood),
olderAtFirstWindow = posterior$posterior[1, 2])
data.frame(window = seq_along(y), observed = y,
older = round(posterior$posterior[, 2], 3))Run EM on the same four windows¶
Start at and fix the older size at 10,000. In the E-step, forward–backward gives the posterior probability of each time bin at each window. The joint posterior of two adjacent states also gives the expected number of transitions between bins. There are three boundaries in the observation vector .
Let be the posterior probability of state at the first window, the expected number of transitions from to , and the expected number of windows with state and observed value . The M-step maximizes
Recompute the weights after every update. The likelihood of the observed windows should increase each time.
em <- fitPairwiseCoalescentEM(y, 10000, olderSize, boundary, windowLength, mu, rho)
round(em$first$transitions, 3)
data.frame(iteration = em$trace$iteration, recentSize = round(em$trace$size),
likelihood = round(exp(em$trace$logLikelihood), 6))
stopifnot(em$converged, all(diff(em$trace$logLikelihood) >= -1e-10))
direct <- fitPairwiseCoalescent(list(y), olderSize, boundary, windowLength, mu, rho)
round(c(EM = tail(em$trace$size, 1L), direct = direct$recentSize))Estimate size in three epochs¶
The four-window fit estimated one unknown size. Here all three sizes vary. The boundaries at 2,500 and 7,000 generations are supplied. Simulate 32 independent 300 kb blocks, each carrying the two copies of a diploid, under a bottleneck. Fit the 1 kb window observations by maximizing the HMM likelihood directly. Use more hidden time bins than size parameters, so two local ancestors can have different ages within the same demographic epoch.
epochBreaks <- c(2500, 7000)
truth <- c(10000, 2600, 12500)
blockLength <- 300000L
windowLength <- 1000L
schedule <- rep(truth[1:2], diff(c(0, epochBreaks)))
timeCuts <- c(400, 1200, 2500, 4200, 7000, 12000, 22000, 40000, 80000)
observations <- lapply(seq_len(32L), function(i) {
seed <- 12400L + 2L * i
ancestry <- simulateAncestry(1L, truth[3], blockLength, rho, seed = seed,
populationSizes = schedule)
dna <- ancestryData(mutateAncestry(ancestry, mu, seed = seed + 1L))$observed
pairwiseWindows(dna$haplotypes, dna$positions, blockLength, windowLength)[[1L]]
})
design <- list(startSizes = rep(10000, 3L), epochBreaks = epochBreaks,
windowLength = windowLength, mutationRate = mu, recombinationRate = rho,
timeCuts = timeCuts)
history <- do.call(fitPairwiseHistory, c(list(windows = observations), design))
blocks <- split(seq_along(observations), rep(1:8, each = 4L))
jackknife <- vapply(blocks, function(ids) {
fit <- do.call(fitPairwiseHistory, c(list(windows = observations[-ids]), design))
stopifnot(fit$convergence == 0L)
fit$sizes
}, numeric(3))
stopifnot(history$convergence == 0L)
se <- sqrt(7 / 8 * rowSums((jackknife - rowMeans(jackknife))^2))
round(rbind(generating = truth, fitted = history$sizes, blockSE = se))extent <- c(0, epochBreaks, 16000)
lower <- pmax(0, history$sizes - 2 * se)
upper <- history$sizes + 2 * se
plot(NA, xlim = range(extent), ylim = c(0, max(upper, truth) * 1.15),
xlab = "Generations before sampling", ylab = "Diploid effective size")
rect(head(extent, -1L), lower, tail(extent, -1L), upper, col = "#28568725", border = NA)
lines(extent, c(truth, tail(truth, 1L)), type = "s", lwd = 2.6, col = "#B22732")
lines(extent, c(history$sizes, tail(history$sizes, 1L)), type = "s", lwd = 2.6, col = "#285687")
legend("bottomright", c("Generating history", "Fitted history", "±2 block-jackknife SE"),
col = c("#B22732", "#285687", "#28568725"), lwd = c(2.6, 2.6, 7),
bty = "n", y.intersp = 2)
The fit estimates the level of each step. The step locations came from the design. Compare uncertainty separately for the recent, bottleneck and older periods. The jackknife omits groups of whole blocks so it keeps linked windows together.
Sample DNA under two size histories¶
Both populations had before 5,000 generations ago. Their recent sizes are 3,500 and 14,000. For each history we simulate two panels, each with 24 independent 300 kb regions from four diploid individuals. Recombination generates linked local trees. Mutations on those trees generate the sequences. We carry those same sequences through all the fits below.
For the DNA fits, a 1 kb window records whether the pair differs at any site. The finer HMM uses ten time bins, with more resolution near the present. Its SMC′ transition allows a recombined lineage to rejoin the branch it left. That recombination event can leave the local pairwise time unchanged.
recentTruth <- c(Smaller = 3500, Larger = 14000)
regionCount <- 24L
regionLength <- 300000L
windowLength <- 1000L
timeCuts <- c(500, 1500, 3000, boundary, 8000, 14000, 25000, 45000, 80000)
draws <- array(vector("list", 4L * regionCount), c(2, 2, regionCount))
for (j in seq_along(recentTruth)) {
for (panel in 1:2) {
for (i in seq_len(regionCount)) {
seed <- 12100L + 1000L * panel + 100L * j + 2L * i
ancestry <- simulateAncestry(4L, olderSize, regionLength, rho,
seed = seed, populationSizes = rep(recentTruth[j], boundary))
dna <- ancestryData(mutateAncestry(ancestry, mu, seed = seed + 1L))
windows <- pairwiseWindows(dna$observed$haplotypes,
dna$observed$positions, regionLength, windowLength)
draws[[j, panel, i]] <- list(windows = windows, intervals = dna$intervals)
}
}
}Compare the fitted and recorded local times¶
First use the first two copies in each region. For one region, plot the fitted probability that the local ancestor lived before the size change. Add the state read from the recorded trees at each window center. The fit uses only the DNA. This is the single-genome check on Which Local Ancestor Times Can PSMC Recover?.
region <- draws[[1, 1, 1]]
one <- lapply(draws[1, 1, ], function(region) region$windows[[1L]])
onePairSize <- fitPairwiseCoalescent(one, olderSize, boundary, windowLength, mu, rho,
timeCuts = timeCuts, smcPrime = TRUE)$recentSize
model <- pairwiseCoalescentModel(onePairSize, olderSize, boundary,
windowLength, mu, rho, timeCuts, smcPrime = TRUE)
y <- region$windows[[1]]
probability <- rowSums(hmmPosterior(t(model$emission[, y + 1L]),
model$transition, model$initial)$posterior[, c(0, timeCuts) >= boundary])
midpoint <- (seq_along(y) - .5) * windowLength
interval <- findInterval(midpoint, region$intervals$left)
stateTruth <- region$intervals$pair_time[interval] >= boundary
plot(midpoint / 1000, probability, type = "l", lwd = 2, col = "#285687", ylim = c(0, 1),
xlab = "Position (kb)", ylab = "Probability of older ancestry")
lines(midpoint / 1000, stateTruth, type = "s", lwd = 2, col = "#B22732")
rug(midpoint[y == 1] / 1000)
legend("right", c("Fitted probability", "Recorded state", "Heterozygous window"),
col = c("#285687", "#B22732", "black"), lty = c(1, 1, NA), pch = c(NA, NA, "|"),
lwd = 2, bty = "n", y.intersp = 2.15, cex = .77)
Fit one pair and all 28 pairs¶
This follows the comparison in MSMC2 Combines Many Pairs of Copies. The eight copies give 28 pairs within each population. We sum their log likelihoods. They share ancestors within a region, so we omit whole regions in turn when measuring uncertainty. The older size and epoch boundary stay fixed throughout. To check the effect of time resolution, we also fit the four-window model’s two states to the same DNA.
estimates <- expand.grid(panel = 1:2, population = names(recentTruth),
stringsAsFactors = FALSE)
estimates$truth <- recentTruth[estimates$population]
estimates[, c("coarse", "onePair", "allPairs", "regionSE")] <- NA_real_
for (row in seq_len(nrow(estimates))) {
j <- match(estimates$population[row], names(recentTruth))
panel <- draws[j, estimates$panel[row], ]
pairs <- lapply(panel, "[[", "windows")
one <- lapply(pairs, "[[", 1L)
all <- unlist(pairs, recursive = FALSE)
design <- list(olderSize = olderSize, boundary = boundary,
windowLength = windowLength, mutationRate = mu, recombinationRate = rho)
fine <- c(design, list(timeCuts = timeCuts, smcPrime = TRUE))
coarseFit <- do.call(fitPairwiseCoalescent, c(list(windows = all), design))
oneFit <- do.call(fitPairwiseCoalescent, c(list(windows = one), fine))
allFit <- do.call(fitPairwiseCoalescent, c(list(windows = all), fine))
leaveOut <- vapply(seq_along(panel), function(i) {
windows <- unlist(pairs[-i], recursive = FALSE)
do.call(fitPairwiseCoalescent, c(list(windows = windows), fine))$recentSize
}, numeric(1L))
estimates[row, 4:7] <- c(coarseFit$recentSize, oneFit$recentSize, allFit$recentSize,
sqrt((regionCount - 1) * mean((leaveOut - mean(leaveOut))^2)))
}
print(estimates, digits = 4, row.names = FALSE)
round(100 * colMeans(abs(estimates[4:6] / estimates$truth - 1)), 1) panel population truth coarse onePair allPairs regionSE
1 Smaller 3500 2633 3412 3114 193.8
2 Smaller 3500 2932 3522 3745 247.3
1 Larger 14000 7547 19262 13197 1389.0
2 Larger 14000 7273 10943 12566 952.3
oldPar <- par(mfrow = c(1, 2), mar = c(4, 4, 2.2, 1))
for (name in names(recentTruth)) {
a <- estimates[estimates$population == name, ]
results <- as.matrix(a[4:6])
plot(NA, xlim = c(.6, 2.4), ylim = range(c(0, results, a$truth, a$allPairs + 2 * a$regionSE)),
xaxt = "n", xlab = "Independent sequence panel", ylab = "Recent diploid effective size",
main = name)
axis(1, 1:2)
abline(h = a$truth[1], lwd = 2, col = "#B22732")
offsets <- c(-.18, 0, .18)
palette <- c("#717171", "#285687", "#008270")
for (k in 1:3) points(a$panel + offsets[k], results[, k], pch = 15 + k, col = palette[k])
arrows(a$panel + offsets[3], a$allPairs - 2 * a$regionSE,
a$panel + offsets[3], a$allPairs + 2 * a$regionSE,
code = 3, length = .045, angle = 90, col = palette[3])
legend("bottomright", c("Generating size", "Two states, all pairs", "One pair", "All 28 pairs"),
col = c("#B22732", palette), lty = c(1, NA, NA, NA),
pch = c(NA, 16:18), bty = "n", cex = .76, y.intersp = 2.1)
}
par(oldPar)
Compare the two panels to see how much the result changes with the sample. Compare the two HMMs on the same panel to see how much the transition approximation and time bins matter. This example fits one recent size per population. The research fit estimates a size curve across time.
Li and Durbin, PSMC · Wilton et al., SMC′ · Schiffels and Wang, MSMC2 · Chak et al., farming and foraging histories
Population size decline or reduced migration?¶
In the lecture, the Chabu have a lower recent fitted and longer runs of homozygosity than nearby farmers. Could isolation contribute to these patterns? Compare two demographic models by calculating their merger probabilities.
Reduced migration. Two demes have 5,000 diploid individuals each throughout. In forward time, the symmetric migration probability drops from 0.002 to 0.00002 at 3,500 generations ago. Tracing backward, a surviving pair changes between the same-deme and different-deme states when exactly one lineage migrates, with probability . After migration, a pair in the same deme merges with probability .
Population size decline. Use one random-mating population and set its size in each generation to , where is the first model’s merger probability at time for a pair still separate and originally sampled within one deme.
The single-population history is constructed to match the within-deme merger probabilities of the structured history. The migration probability changes in one step. The merger rate also depends on where the surviving lineages are distributed over the following generations.
generations <- seq_len(6500L)
demeSize <- 5000L
changeGeneration <- 3500L
migration <- ifelse(generations <= changeGeneration, .00002, .002)
changed <- pairCoalescenceRates(migration, 2L * demeSize)
withinRate <- changed[, "within"]
sizeFromWithinRate <- 1 / (2 * withinRate)
singlePopulationSize <- sizeFromWithinRate
twoDemeSize <- rep(2L * demeSize, length(generations))
stopifnot(isTRUE(all.equal(1 / (2 * singlePopulationSize), withinRate)))
pick <- c(500, 3500, 5000)
round(data.frame(generation = pick, twoDemeSize = twoDemeSize[pick],
sizeFromWithinRate = sizeFromWithinRate[pick]), 3)plotSizeComparison <- function() {
trueColor <- "#D14124"
inferredColor <- "#1D4F91"
axisColor <- "#4F555A"
oldPar <- par(no.readonly = TRUE)
on.exit({ layout(1); par(oldPar) })
layout(rbind(c(1, 2), c(3, 3)), heights = c(1, .13))
par(mar = c(3.45, 4, 3.35, 1.3), mgp = c(2.1, .60, 0), tcl = -.25)
drawHistory <- function(size, title, subtitle, showMigration = FALSE) {
plot(generations, size, type = "n", axes = FALSE, xaxs = "i", yaxs = "i",
xlim = c(0, 6500), ylim = c(4200, 11000), xlab = "", ylab = "")
ticks <- c(0, 2000, 3500, 5000, 6500)
axis(1, at = ticks, labels = formatC(ticks, big.mark = ",", format = "d"),
cex.axis = .93, col = axisColor, col.axis = axisColor)
sizes <- c(5000, 7500, 10000)
axis(2, at = sizes, labels = formatC(sizes, big.mark = ",", format = "d"),
las = 1, cex.axis = .93, col = axisColor, col.axis = axisColor)
abline(h = sizes, col = "#E6E9EB", lwd = .8)
if (showMigration) {
abline(v = changeGeneration, col = "#969DA3", lty = 3, lwd = 1.3)
text(c(changeGeneration / 2, (changeGeneration + max(generations)) / 2),
10925, c("m = 0.00002", "m = 0.002"), col = axisColor,
cex = .92, adj = c(.5, 1))
}
lines(generations, size, col = trueColor, lwd = 3.6)
lines(generations, sizeFromWithinRate, col = inferredColor, lwd = 2.8, lty = 2)
mtext(title, side = 3, line = 1.9, cex = 1.11, font = 2)
mtext(subtitle, side = 3, line = .78, cex = .93, col = axisColor)
mtext("Generations ago", side = 1, line = 1.65, cex = .94)
mtext("Population size", side = 2, line = 2.9, cex = .94)
}
drawHistory(singlePopulationSize, "Population Size Decline", "One random-mating population")
drawHistory(twoDemeSize, "Reduced Migration", "Two demes of 5,000 each",
showMigration = TRUE)
par(mar = rep(0, 4))
plot.new()
legend("center", c("Total size in the model", "Size from the within-group merger rate"),
col = c(trueColor, inferredColor), lwd = c(3.6, 2.8), lty = c(1, 2),
bty = "n", horiz = TRUE, seg.len = 2.1, x.intersp = .72, cex = .97)
}
plotOptions <- options(repr.plot.width = 9.2, repr.plot.height = 3.55)
plotSizeComparison()
options(plotOptions)
Compare pairs within and between populations¶
The size curves agree because the within-group merger rates agree. Now sample one copy from each deme. A merger requires the lineages to enter the same deme, so low migration can slow down between-deme mergers.
The relative cross-coalescence rate is the between-deme merger rate divided by the mean of the two within-deme rates. Symmetry makes those two within-deme rates equal here. In one random-mating population, group labels assigned to the sampled copies have no effect on the merger probability, giving a ratio of 1. The dashed green line shows a second two-deme model with constant migration of 0.002 per generation.
constant <- pairCoalescenceRates(rep(.002, length(generations)), 2L * demeSize)
acrossToWithin <- changed[, "across"] / withinRate
oldPar <- par(mar = c(4.2, 4.2, 2.2, 1.15))
plot(generations, acrossToWithin, type = "l", lwd = 2.5, col = "#1D4F91",
ylim = c(0, 1.05), xlab = "Generations ago",
ylab = "Relative cross-coalescence rate", main = "Compare Where Pairs Are Sampled")
lines(generations, constant[, "across"] / constant[, "within"], col = "#008270", lwd = 2, lty = 2)
abline(h = 1, col = "#D14124", lwd = 2)
abline(v = changeGeneration, col = "#888888", lty = 3)
legend("bottomright", c("Two demes, reduced migration", "Two demes, constant migration",
"One random-mating population"),
col = c("#1D4F91", "#008270", "#D14124"), lty = c(1, 2, 1), lwd = 2, bty = "n")
par(oldPar)
stopifnot(acrossToWithin[500] < .03, acrossToWithin[5000] > .99)
With Chabu and its neighbors, the corresponding comparison would use pairs within each population and pairs spanning the two populations. The plotted rates here are calculated from the two specified models. With genomic data, the rates must be inferred from sequence differences, as in the earlier HMM example.
- Li, H., & Durbin, R. (2011). Inference of human population history from individual whole-genome sequences. Nature, 475(7357), 493–496. 10.1038/nature10231
- Wilton, P. R., Carmi, S., & Hobolth, A. (2015). The SMC′ Is a Highly Accurate Approximation to the Ancestral Recombination Graph. Genetics, 200(1), 343–355. 10.1534/genetics.114.173898
- Schiffels, S., & Wang, K. (2020). MSMC and MSMC2: The Multiple Sequentially Markovian Coalescent. In Statistical Population Genomics (pp. 147–166). Springer US. 10.1007/978-1-0716-0199-0_7
- Chak, B., Wu, E., Perry, G. H., Dominy, N. J., Dumaine, A., Enard, D., Aguirre-Gamboa, R., Patin, E., Quintana-Murci, L., Henn, B. M., Moller, M., Myrick, J., Negash, A., Norman, P. J., Scelza, B., Uren, C., Shedd, N., Weng, Z., Ranasinghe, R., … Barreiro, L. B. (2026). Genomic signatures of recent human adaptation to the foraging-to-farming transition. Nature Ecology & Evolution. 10.1038/s41559-026-03227-7
- Mazet, O., Rodríguez, W., Grusea, S., Boitard, S., & Chikhi, L. (2015). On the importance of being structured: instantaneous coalescence rates and human evolution—lessons for ancestral population size inference? Heredity, 116(4), 362–371. 10.1038/hdy.2015.104