A mutation on a terminal branch is a singleton; a mutation on an internal branch is present in every sample descended from that branch. Start with a known tree, then use the frequency spectrum from the shared forward sample to fit ancestral size, growth and bottleneck parameters.
Keep the observed DNA RDS under data/population_history/.
library(hpgR)
options(repr.plot.width = 9, repr.plot.height = 4.5, repr.plot.pointsize = 13,
repr.plot.bg = "white", warn = 1)
blue <- "#265991"; orange <- "#D65F22"
drawFigure <- function(name, draw, width = 9, height = 3.6) {
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
observed <- readRDS("data/population_history/observed.rds")
mu <- populationHistoryDesign()$design$mutation_rateA specified-tree calculation¶
Suppose copies 1 and 2 share an internal branch. Put one mutation on that branch and one on each terminal branch. This gives five segregating sites, four singletons and one doubleton. These constructed sites are a schematic for reading SFS bins, not another population simulation.
carriers <- list(c(1, 2), 1, 2, 3, 4)
G <- matrix(0L, nrow = 4, ncol = length(carriers))
for (site in seq_along(carriers)) G[carriers[[site]], site] <- 1L
rownames(G) <- paste0('copy ', 1:4)
colnames(G) <- paste0('site ', 1:5)
G
stopifnot(identical(as.integer(colSums(G)), c(2L, 1L, 1L, 1L, 1L)))
Let count sites with derived copies. The same matrix gives and , the average pairwise difference. Averaged over neutral constant-size genealogies, ; a single small tree can differ from that expectation.
derived_count <- colSums(G)
S <- sum(derived_count > 0 & derived_count < nrow(G))
pi_region <- mean(as.vector(dist(G, method = 'manhattan')))
spectrum <- tabulate(derived_count, nbins = nrow(G) - 1)
theta_W <- S / sum(1 / seq_len(nrow(G) - 1))
stopifnot(S == 5, abs(pi_region - 8 / 3) < 1e-12)
barplot(spectrum, names.arg = seq_along(spectrum), col = '#306C9A',
xlab = 'Derived copies at a site', ylab = 'Number of sites')
c(S = S, pi_region = pi_region, theta_W = theta_W)
The shared-branch mutation contributes more to pairwise diversity than a singleton; both count once toward . To check why an SFS alone cannot identify a labeled tree, change only which samples carry the first site’s derived allele.
G_control <- G
G_control[, 1] <- c(1, 0, 1, 0)
stopifnot(identical(colSums(G_control), colSums(G)),
ptiKey(ptiConsensus(G)$supported_clades[[1]]) == "1,2",
ptiKey(ptiConsensus(G_control)$supported_clades[[1]]) == "1,3")
cat("Same SFS; supported clade changes from {H1,H2} to {H1,H3}.\n")Same SFS; supported clade changes from {H1,H2} to {H1,H3}.
Fit a population size history from the same sample¶
Use the first twelve rows of the same haplotype matrix across all eight 10-kb chromosomes. These are : both chromosome copies from each of the first six sampled people. Let count sites with allele 1 in exactly of these twelve copies, for .
Ancestral size and growth duration define the candidate history . The fixed history inputs are founder size , bottleneck duration generations and present size , with exponential growth from 20 to over generations:
Here counts generations since growth began. The growth curve is specified; is its duration in generations. The known sample and calibration inputs are , bases and per base per generation.
Under the neutral infinite-sites coalescent, each candidate history predicts an expected SFS:
Here sums the lengths of all branches with exactly sampled descendants in a local genealogy, in generations. For example, sums all terminal branch lengths. The expectation averages over the random genealogies generated by the candidate history. The fitted quantities are ancestral size and growth duration; each candidate history generates a distribution of possible trees. Linearity of expectation sums mutation opportunities across the analyzed chromosomes.
For fitting, use a Poisson composite likelihood with these means:
Vary and to maximize this composite log likelihood; all fixed
inputs stay unchanged. The expectation calculation calls Daniel Nachun’s
.sfs_expected_single_pop through expectedHistorySFS().
Shared genealogies couple the SFS bins. The Poisson factors provide a working likelihood for the fit. The expectation uses infinite sites and ancestral equilibrium; the forward DNA includes recurrent mutation and finite burn-in. Compare the predicted spectrum with the observed counts to assess this approximation.
Resampling whole chromosomes and refitting measures chromosome-to-chromosome variation within this realized sample. The shared pedigree and the model approximation also contribute to uncertainty.
spectra <- t(vapply(1:8,function(j)sfs(observed$haplotypes[1:12,
((j-1)*10000+1):(j*10000),drop=FALSE]),integer(11)))
growth <- fitHistorySpectrum(spectra,mu,10000)
set.seed(20261107)
bootstrap <- replicate(40,fitHistorySpectrum(spectra[sample.int(8,8,replace=TRUE),],
mu,10000)$estimate)
interval <- apply(bootstrap,1,quantile,c(.025,.975))
print(data.frame(parameter=names(growth$estimate),truth=c(100,40),
estimate=unname(growth$estimate),lower=interval[1,],upper=interval[2,]),row.names=FALSE)
drawFigure("sfs_history_fit",function(){
par(mar=c(4.6,4.8,2.5,.8))
truth_expected<-expectedHistorySFS(12,c(100,head(c(20,
populationSizeSchedule(populationHistoryDesign()$candidates$recent_founding,
populationHistoryDesign()$design)[-1]),-1)),mu,80000)
plot(1:11,growth$observed,pch=16,log="y",xlab="Sampled copies carrying allele 1",
ylab="Sites across the same eight chromosomes",ylim=range(growth$observed,
growth$expected,growth$constantExpected,truth_expected))
lines(1:11,growth$constantExpected,col="gray50",lwd=2)
lines(1:11,growth$expected,col=blue,lwd=3)
lines(1:11,truth_expected,col="#B33B32",lwd=2)
legend("topright",c("Observed DNA","Fitted constant size","Fitted size history",
"True-history approximation"),col=c("black","gray50",blue,"#B33B32"),
pch=c(16,NA,NA,NA),lty=c(NA,1,1,1),lwd=c(NA,2,3,2),bty="n",cex=.75)
},width=7,height=4.5)
parameter truth estimate lower upper
ancestralSize 100 102.3788 85.96609 124.8254
growthGenerations 40 30.0000 25.00000 35.1250

Estimate bottleneck size and date¶
Use the same twelve haplotypes and eight chromosome spectra. The classical SFS composite likelihood follows Pritchard, Section 3.3, Equation 3.22, and the Handbook of Statistical Genomics, Chapter 8, Equation 8.15. The count form separates total variation from the relative spectrum:
Keep bottleneck duration generations and present size supplied. Estimate bottleneck size and growth duration . The growth phase now starts at the unknown bottleneck size:
Here counts generations since growth began. The preceding fit fixed ; this fit estimates it alongside and . The expected spectrum is
At every bottleneck-size and growth-duration pair, optimize ancestral size:
The bottleneck ended generations before sampling and began generations before sampling. These event dates describe the size trajectory; dates a sampled genealogy’s root.
Search and , with ancestral size between (at least 2) and 10,000. The package composes Dan Nachun’s inspected .sfs_expected_single_pop expectation, through expectedHistorySFS(), with ordinary likelihood profiling. The expected spectrum is affine in ancestral tail size, so two kernel calls per grid cell cache that dependence for the fits and chromosome bootstrap.
The plot shows the informative part of the full search. Contours label composite log-likelihood drops; points show 200 whole-chromosome refits. The printed ranges are marginal 2.5–97.5% chromosome-bootstrap quantiles. This describes genomic variation conditional on this sampled pedigree, the supplied rates and the demographic model. Finite ancestral burn-in and recurrent mutations in the forward DNA also affect the fit.
bottleneck <- fitBottleneckSpectrum(spectra, mu, 10000,
bootstrapReplicates = 200, seed = 20261108)
print(data.frame(parameter = names(bottleneck$estimate),
truth = c(20, 40, 100, 60), estimate = unname(bottleneck$estimate),
lower = bottleneck$interval[1, ], upper = bottleneck$interval[2, ]),
row.names = FALSE)
drawFigure("bottleneck_size_time", function() {
profile <- bottleneck$profile
dates <- sort(unique(profile$growthGenerations)) + 20
sizes <- sort(unique(profile$bottleneckSize))
drop <- matrix(max(profile$logLikelihood) - profile$logLikelihood,
nrow = length(sizes))
colors <- colorRampPalette(c("#1C4A73", "#8AB4D0", "#E4EDF4", "white"))(100)
layout(matrix(c(1, 2), 1), widths = c(6, 1.1))
par(mar = c(4.7, 4.5, 1.5, .5), cex = 1.05)
image(dates, sizes, t(pmin(drop, 15)), col = colors,
xlim = c(25, 100), ylim = c(2, 60), zlim = c(0, 15),
xlab = "Bottleneck began (generations before sample)",
ylab = "Bottleneck size (diploid individuals)")
contour(dates, sizes, t(drop), levels = c(2, 5, 10),
add = TRUE, col = "gray40", labcex = .8)
points(bottleneck$bootstrap[, "bottleneckBegan"],
bottleneck$bootstrap[, "bottleneckSize"],
pch = 16, cex = .55, col = adjustcolor("black", .3))
points(bottleneck$estimate[["bottleneckBegan"]],
bottleneck$estimate[["bottleneckSize"]], pch = 4,
col = "white", cex = 1.5, lwd = 5)
points(bottleneck$estimate[["bottleneckBegan"]],
bottleneck$estimate[["bottleneckSize"]], pch = 4,
col = "black", cex = 1.5, lwd = 2)
points(60, 20, pch = 8, col = "#C62828", cex = 1.8, lwd = 2.5)
legend("topright", c("True history", "Fitted history", "Chromosome refits"),
pch = c(8, 4, 16), col = c("#C62828", "black", "gray40"),
pt.cex = c(1.4, 1.2, .6), pt.lwd = c(2, 2, 1), bty = "n", cex = .8)
par(mar = c(4.7, .5, 1.5, 3.8), cex = 1.05)
image(c(0, 1), seq(0, 15, length.out = 100),
matrix(rep(seq(0, 15, length.out = 100), each = 2), 2),
col = colors, axes = FALSE, xlab = "", ylab = "", zlim = c(0, 15))
axis(4, at = c(0, 5, 10, 15), labels = c("0", "5", "10", "15+"), las = 1)
mtext("Composite log-likelihood drop", side = 4, line = 2.4, cex = .8)
}, width = 7.4, height = 5)
parameter truth estimate lower upper
bottleneckSize 20 28.00000 6.00000 36.0500
growthGenerations 40 25.00000 20.00000 50.1250
ancestralSize 100 86.18105 74.66579 438.4663
bottleneckBegan 60 45.00000 40.00000 70.1250

Check the jointly fitted history against the observed spectrum¶
Compare the joint fit’s expected SFS with the same twelve-haplotype counts used for fitting. Black points show the observations; blue shows the fitted-history expectation. The red curve is the expectation under the generating history.
This is an in-sample fit diagnostic. The earlier reserved-chromosome and independent-simulation checks assess separate validation questions.
generatingHistory <- populationHistoryDesign()
generatingSizes <- populationSizeSchedule(
generatingHistory$candidates$recent_founding, generatingHistory$design)
generatingParents <- head(c(generatingHistory$candidates$recent_founding$founder,
generatingSizes[-1L]), -1L)
trueSpectrum <- expectedHistorySFS(12,
c(generatingHistory$design$ancestral_size, generatingParents),
mu, ncol(observed$haplotypes))
stopifnot(identical(as.numeric(bottleneck$observed), as.numeric(colSums(spectra))))
print(data.frame(alleleCount = seq_along(bottleneck$observed),
observed = bottleneck$observed, jointFit = bottleneck$expected,
generatingHistory = trueSpectrum), row.names = FALSE)
drawFigure("sfs_joint_history_check", function() {
par(mar = c(4.6, 4.9, 1.5, 1.0), bg = "white")
bins <- seq_along(bottleneck$observed)
plot(bins, bottleneck$observed, type = "n", log = "y",
xlab = "Sampled copies carrying allele 1",
ylab = "Sites across the same eight chromosomes",
ylim = range(bottleneck$observed, bottleneck$expected, trueSpectrum),
xaxt = "n")
axis(1, at = bins)
lines(bins, trueSpectrum, col = "#C62828", lwd = 3)
lines(bins, bottleneck$expected, col = "#265991", lwd = 3)
points(bins, bottleneck$observed, pch = 16, cex = 1.05)
legend("topright", c("Observed SFS", "Fitted-history expectation",
"Generating-history expectation"),
col = c("black", "#265991", "#C62828"),
pch = c(16, NA, NA), lty = c(NA, 1, 1),
lwd = c(NA, 3, 3), bty = "n", cex = .95)
}, width = 9.2, height = 3.5)
alleleCount observed jointFit generatingHistory
1 695 682.68758 780.67178
2 221 230.76808 221.06666
3 133 162.67914 145.55135
4 135 133.34348 119.33831
5 150 114.77703 105.10239
6 115 101.09418 95.36233
7 91 90.26959 87.82096
8 72 81.37124 81.56512
9 43 73.88452 76.16169
10 71 67.48905 71.37654
11 77 61.96801 67.06969

Sources. Pritchard, An Owner’s Guide to the Human Genome, Sections 2.2 and 3.3; the expected frequency spectrum uses the demographic calculation in Daniel Nachun’s demographyTools.