Algorithmresearch
Pairwise sequentially Markovian coalescent
Also called PSMC.
Infer past effective population size from one diploid genome with an HMM whose hidden states are binned coalescence times along the sequence.
- Time
- Θ(r (n k^2 + g k^3 m)) worst · average · best
- Space
- Θ(n k + k^2) extra
- Where
- g = the number of line-search steps per size; k = the number of time intervals; m = the number of integration steps per interval; n = the number of bins; r = the number of EM iterations
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Heng Li, Richard Durbin, 2011
PSMC reads the history of a population from the genome of one diploid individual. The two copies of each chromosome have a common ancestor at some time in the past, and that time changes along the chromosome, because recombination gives different parts different ancestors. Where the time is long, the two copies differ at many sites; where it is short, they differ at few. PSMC is a hidden Markov model along the genome whose hidden state is the coalescence time, put into intervals, and whose observations are the heterozygous and homozygous parts of the genome. The rate of coalescence at time is the inverse of the effective population size at , so the sizes that best explain the observations, found by expectation maximization, give a history of . Li and Durbin introduced it in 2011.
In plain words
Look at two copies of a chromosome and mark where they differ. The marks are not spread evenly. Some long stretches have many marks, and other long stretches have almost none. A stretch with many marks goes back a long time to its common ancestor, so mutations had a long time to build up. A stretch with few marks has a recent common ancestor.
So the genome gives many samples of coalescence times, one per stretch, from one person. If the population was small at some time in the past, many stretches found their common ancestor then, because two lineages meet fast in a small population. If it was large, few did. PSMC counts how many stretches, in effect, have each coalescence time, and turns those counts into population sizes. It does this without seeing the stretch boundaries: the HMM averages over all ways to cut the genome into stretches.
The problem
Input. A sequence of bins of bases along the genome of one diploid individual. A bin is 1 if it has at least one heterozygous site, 0 if it has none, and missing if too few of its bases were called. Time breaks in units of generations, where is a reference size. The scaled mutation rate and recombination rate per bin.
Output. Relative sizes , with for in , that locally maximize the likelihood of the bins.
The model. Let , the cumulative rate of coalescence of two lineages.
- Hidden states. State means that the coalescence time at the bin is in . At the first bin, has the density , so .
- Emission. Given , a bin is heterozygous with probability : on the path of length between the two copies, mutations come at rate per unit of length. So .
- Transition. Between two neighbouring bins, with , a recombination happens with probability . Then, as in the sequentially Markov coalescent, one lineage is cut at an age uniform on and coalesces again with the other lineage, going back from at rate . Otherwise stays the same. Integrating over the interval of gives the matrix .
The algorithm
PSMC(o_1..o_n, t_0..t_k, θ, ρ, λ)- 1
for each of R iterations do - 2
build π, A and e from λ, θ and ρ - 3
forward pass: α_1 ← π ∘ e(o_1), then α_i ← (α_{i−1} A) ∘ e(o_i), scaled to sum 1 - 4
backward pass: β_n ← 1, then β_{i−1} ← A (e(o_i) ∘ β_i), with the same scales - 5
add up the expected counts: first state, transitions j → l, het and hom bins per state - 6
for j = 1, ..., k do change λ_j to raise Q(λ), the expected log-likelihood of the counts - 7
return λ
Here is the vector of for a heterozygous bin, of for a homozygous bin, and all ones for a missing bin. Lines L3 to L5 are the forward-backward algorithm: the posterior of state at bin is , and the expected number of transitions between bins and is , where is the scale of bin . The log-likelihood is .
is the expected complete-data log-likelihood
where , , and are the expected counts of line L5 and , , are computed from the new . Line L6 changes one at a time by a golden-section search and keeps a change only if goes up.
The transition in closed form, up to one integral. Write . With the cut at , the new time satisfies for and for . Averaging over uniform on ,
Call this . Then the joint probability that is in interval and is in interval is
and . The first integral has a closed form because is constant on the interval. The implementation computes the second by the composite Simpson rule, and in closed form, piece by piece. Li and Durbin give closed forms for the whole matrix.
Time intervals. The implementation spaces the breaks as for , dense near the present and sparse in the past, so that each interval holds a useful number of coalescences.
Example
Take intervals with breaks , a constant size , and per bin.
- Initial law. .
- Emission. For interval 1, , so . In the same way : older states give more heterozygous bins.
- Transition. The rows of are , and . A bin with an old common ancestor is more likely to have a recombination before the next bin, so the diagonal falls with the state.
For the five bins , the log-likelihood is , and the posterior of the third bin is . The two heterozygous bins pull the posterior of every bin toward the oldest state, because the states change rarely from one bin to the next.
For a fit, simulate bins with , , breaks and true sizes , and start EM at . Eight iterations raise the log-likelihood from to and give . The fit finds the small recent size, but with only 738 heterozygous bins the estimates are noisy. A human genome has about bins of 100 bases.
Correctness
Lines L3 to L5 compute, for the HMM , the exact likelihood of the bins and the exact posterior expectations of the counts of first states, transitions and emissions; this is the forward-backward algorithm, and a missing bin has emission 1 in every state. The transition formula follows from the model: with probability the time stays, and otherwise the new time has the law of averaged over the cut age, whose tail is . Its row sums are , so is a stochastic matrix.
For the sizes, when is built from the posterior under , which is the basic inequality of EM. Line L6 accepts a new only when , so the log-likelihood never goes down from one iteration to the next. Like all EM methods, it can stop at a local maximum. The full proof is below.
Proof: PSMC builds the HMM of the model, computes its likelihood exactly and never lowers itfull
Setting. The breaks are , and on . Let and . The coalescence time of the two copies at a bin has the density , so . Given , the bin is heterozygous with probability . Between two bins, with probability the next time is , and otherwise the next time is , drawn as follows: is uniform on , and given , for and for .
Lemma 1. For and , is when , and when . Also and .
Proof. If , every in has , so the integrand is , and the integral is . If , split at : on the integrand is , which gives , and on it is 1, which gives . With , and the value is . As , while is fixed, so .
Lemma 2. Let for the times of two neighbouring bins, with from the density . Then
and .
Proof. Condition on in . Without recombination, probability , the next time is . With recombination, the next time is , and
Integrating against over gives the formula. Summed over , the differences telescope to by Lemma 1, so .
So is the transition matrix of the interval of , and each row sums to 1. The code divides each row by its numerical sum, which is up to the error of the Simpson rule.
Lemma 3. For , , with the last factor 1 when . In particular, , and is the probability that a bin is heterozygous given .
Proof. On , , so the integrand is , an exponential whose integral over is the formula. With it gives . Given , has the density on , and the probability of a homozygous bin is the mean of .
Lemma 3 with gives the first term of Lemma 2. On , , and is the sum over of these terms. This is how the code computes , with every exponent shifted by so that none is positive.
Lemma 4. For observations , with , or for a heterozygous, homozygous or missing bin, lines L3 and L4 give , , and , where is the hidden state of bin .
Proof. By induction, and : the unscaled vector is by the Markov property, and its sum is . The product of the is by the chain rule. Backward, , again by induction from , because conditions on the next state. The two claims about posteriors follow by Bayes' rule, since given the observations before and after bin are independent. A missing bin multiplies every state by 1, which is the same as leaving it out of the product.
Lemma 5. Let , , and be the posterior expected counts under of line L5, and define as on the page with , , from . Then , where is the log-likelihood.
Proof. For a path of states, , so , with the expectation over the posterior of Lemma 4. Then
by Jensen's inequality, where is the entropy of , and equality holds at because then for every . Subtracting the two gives the claim.
Theorem. Each iteration of lines L1 to L6 returns sizes with , and the log-likelihoods that the implementation reports never decrease.
Proof. Line L6 starts from and replaces one coordinate only when the new value has a strictly larger . So at the end , and Lemma 5 gives . The model matrices are those of Lemmas 2 and 3 computed with the same Simpson rule at every iteration, so the argument applies to the HMM that the code builds.
The theorem does not say that EM reaches the maximum likelihood: it can stop at a local maximum or a saddle point, and the result depends on the start.
Complexity
- Forward-backward. Each bin costs a vector-matrix product, , so a pass costs and stores forward values.
- Building the model. The Simpson rule with points per interval, and at breaks for each point, costs per matrix.
- The M step. Line L6 evaluates about times for each of the sizes, each time with a new matrix, so it costs . It does not depend on .
- Total. time for iterations. For a genome, is in the tens of millions and is about 64, so the forward-backward passes dominate.
Properties
- One genome is enough. The many local trees along the genome act as many partly independent samples of the coalescence time.
- Inverse coalescence rate. What PSMC estimates is the inverse of the coalescence rate of two lineages at each time. It equals the size only for a single population with random mating.
- Approximate stationarity. With recombination probability per bin, the chain keeps the law only up to an error of order . The rows of the joint matrix sum to exactly, and its columns only nearly.
- Resolution. Few pairs of copies coalesce in the very recent past or in the deep past, so the sizes there have large errors. With human data, the method has little power for the last 20 000 years or so.
- Scale. The fit gives and in coalescent units. With a mutation rate per base per generation and a generation time , , a break is years, and . Errors in and move the curve along both axes.
Variants and improvements
- The PSMC program. It also estimates and , uses closed-form transitions, and groups the 64 atomic intervals into fewer free parameters, for example a pattern of the form
4+25*2+4+6, to keep the estimates stable. It adds a bootstrap over parts of the genome for confidence bands. - Faster transitions. The transition matrices of SMC models have structure that lets the forward step run in time per bin instead of (Harris and coauthors).
- More genomes. MSMC uses several haplotypes and estimates the time of the first coalescence among them, which gives better resolution for the recent past, and the cross-coalescence rate between two populations. SMC++ combines one genome with the frequency spectrum of many.
- Other methods. ARG-based methods, see ARG inference, infer whole genealogies and then sizes from them.
When to use it
Use it to get the broad size history of a population, or of a species with only a few sequenced genomes, away from the very recent and the very deep past. It needs a high-coverage genome of one diploid individual, a mutation rate and a generation time. For the recent past, or to estimate split times between populations, use methods with more genomes.
Pitfalls
- Structure looks like size change. In a structured population, the inverse coalescence rate changes over time even when no deme changes size. A peak in the curve can be the trace of old structure, not of a large population.
- Coverage and filtering. Missed heterozygous sites at low coverage lower and shift the curve. Bins with repeats or bad mapping must be marked missing, not homozygous.
- Fixed bins. A bin of 100 bases is heterozygous at most once. If per bin is not small, many differences are lost; for very diverse species, use smaller bins.
- Too many free parameters. With one size per atomic interval, the estimates in the sparse intervals swing wildly. Group intervals.
- Recent sizes. Sizes in the first interval are often overestimated or noisy. Do not read sharp changes there.
- Mutation rate and generation time. The years and sizes are only as good as and .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Random variates, exact probability mass functions and test helpers for
the stochastic pages of the biology area.
Every sampler takes a random.Random object as its first argument and never
uses the module-level random functions. Each sampler draws its random
numbers in the order that its docstring gives, so two runs with the same
seed give the same output.
Conventions:
- A reaction network with n species and m reactions is given by `stoich`, a
list of the m change vectors nu_1, ..., nu_m. So stoich[j][i] is the entry
S[i][j] of the n by m stoichiometric matrix S.
- `propensity(x)` takes the state as a tuple of n integer counts and returns
the m propensities a_1(x), ..., a_m(x) as a sequence of floats >= 0.
- nbinom_pmf uses the mean mu and the dispersion alpha, with
Var = mu + alpha mu^2. The size is r = 1 / alpha; alpha = 0 is Poisson.
- hypergeom_pmf(k, total, good, draws) is the probability of k good items
in `draws` draws without replacement from `total` items of which `good`
are good.
Requires Python 3.12 or later (random.Random.binomialvariate).
"""
from __future__ import annotations
import math
from statistics import NormalDist
from typing import Callable, List, Sequence, Tuple
State = Tuple[int, ...]
_POISSON_PART = 30.0
# Random variates
def poisson(rng, lam: float) -> int:
"""A Poisson(lam) variate.
For lam <= 30, inversion of the cumulative distribution with one
rng.random() draw. For lam > 30, the sum of p = ceil(lam / 30)
independent Poisson(lam / p) variates, drawn one after the other by
inversion (one rng.random() draw each).
"""
if lam < 0 or math.isnan(lam):
raise ValueError("lam must be >= 0")
if lam == 0:
return 0
if lam > _POISSON_PART:
parts = math.ceil(lam / _POISSON_PART)
part = lam / parts
return sum(_poisson_inversion(rng, part) for _ in range(parts))
return _poisson_inversion(rng, lam)
def _poisson_inversion(rng, lam: float) -> int:
u = rng.random()
k = 0
p = math.exp(-lam)
cdf = p
while u >= cdf:
k += 1
p *= lam / k
if p == 0.0:
# Rounding left u above the computed total mass; stop at the tail.
break
cdf += p
return k
def binomial(rng, n: int, p: float) -> int:
"""A Binomial(n, p) variate by rng.binomialvariate (one call)."""
if n < 0 or not 0.0 <= p <= 1.0:
raise ValueError("need n >= 0 and 0 <= p <= 1")
if n == 0 or p == 0.0:
return 0
if p == 1.0:
return n
return rng.binomialvariate(n, p)
def multinomial(rng, n: int, probs: Sequence[float]) -> List[int]:
"""A Multinomial(n, probs) vector by conditional binomials.
probs are weights >= 0 with a positive sum; they need not sum to 1. Cell
i gets Binomial(rest of n, probs[i] / rest of the weight), for i in
order; the last cell with positive weight gets the rest.
"""
if n < 0:
raise ValueError("n must be >= 0")
w = [float(q) for q in probs]
if any(q < 0 for q in w):
raise ValueError("weights must be >= 0")
total = sum(w)
if total <= 0:
raise ValueError("weights must have a positive sum")
last = max(i for i, q in enumerate(w) if q > 0)
out = [0] * len(w)
left = n
rest = total
for i in range(last):
if left == 0:
break
if w[i] == 0:
continue
x = binomial(rng, left, min(1.0, w[i] / rest))
out[i] = x
left -= x
rest -= w[i]
out[last] += left
return out
def categorical(rng, weights: Sequence[float]) -> int:
"""An index i with probability weights[i] / sum(weights).
One draw u = rng.random() * sum(weights), then a cumulative search from
index 0. Indices with weight 0 are never returned.
"""
total = 0.0
for w in weights:
if w < 0:
raise ValueError("weights must be >= 0")
total += w
if total <= 0:
raise ValueError("weights must have a positive sum")
u = rng.random() * total
acc = 0.0
last = -1
for i, w in enumerate(weights):
if w > 0:
acc += w
last = i
if u < acc:
return i
return last
def ssa_direct(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]], t_end: float,
max_events: int = 10 ** 6):
"""Gillespie's direct method from state x0 at time 0 up to time t_end.
Each step computes a = propensity(x) and a0 = sum(a). If a0 = 0 the run
stops. Otherwise it draws tau = rng.expovariate(a0) first. If
t + tau > t_end the run stops, and no second number is drawn. Else it
draws u = rng.random() * a0 and fires the first reaction j with
a_1 + ... + a_j > u (a linear search), then adds stoich[j] to x.
Returns (times, states, complete). times[0] = 0.0 and states[0] =
tuple(x0); entry k > 0 is the time and the state just after event k.
The state at t_end is states[-1]. complete is False only when the run
stopped because max_events events had fired before t_end.
"""
x = tuple(int(v) for v in x0)
times = [0.0]
states = [x]
t = 0.0
m = len(stoich)
for _ in range(max_events):
a = propensity(x)
a0 = 0.0
for v in a:
if v < 0:
raise ValueError("propensities must be >= 0")
a0 += v
if a0 <= 0.0:
return times, states, True
t += rng.expovariate(a0)
if t > t_end:
return times, states, True
u = rng.random() * a0
acc = 0.0
j = -1
for i in range(m):
if a[i] > 0:
acc += a[i]
j = i
if u < acc:
break
nu = stoich[j]
x = tuple(x[i] + nu[i] for i in range(len(x)))
times.append(t)
states.append(x)
return times, states, False
# Sample statistics and test helpers
def mean_var(xs) -> Tuple[float, float]:
"""The mean and the unbiased sample variance (divisor n - 1) by the
Welford method. The variance is 0.0 for fewer than two values."""
n = 0
mean = 0.0
m2 = 0.0
for x in xs:
n += 1
d = x - mean
mean += d / n
m2 += d * (x - mean)
if n == 0:
raise ValueError("empty sample")
return mean, (m2 / (n - 1) if n > 1 else 0.0)
def check_mean(m: float, mu: float, var: float, n: int, z: float = 4.0) -> bool:
"""True when |m - mu| <= z sqrt(var / n): a sample mean m of n
independent values with exact mean mu and exact variance var."""
return abs(m - mu) <= z * math.sqrt(var / n)
# Exact probability mass functions
def log_choose(n: int, k: int) -> float:
"""ln C(n, k), or -inf when k < 0 or k > n."""
if k < 0 or k > n:
return -math.inf
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
def binom_pmf(k: int, n: int, p: float) -> float:
"""P(K = k) for K ~ Binomial(n, p)."""
if k < 0 or k > n:
return 0.0
if p == 0.0:
return 1.0 if k == 0 else 0.0
if p == 1.0:
return 1.0 if k == n else 0.0
return math.exp(log_choose(n, k) + k * math.log(p) + (n - k) * math.log1p(-p))
def poisson_pmf(k: int, lam: float) -> float:
"""P(K = k) for K ~ Poisson(lam)."""
if k < 0:
return 0.0
if lam == 0:
return 1.0 if k == 0 else 0.0
return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))
def nbinom_pmf(k: int, mu: float, alpha: float) -> float:
"""P(K = k) for the negative binomial with mean mu and Var = mu + alpha mu^2."""
if k < 0:
return 0.0
if alpha == 0:
return poisson_pmf(k, mu)
if mu == 0:
return 1.0 if k == 0 else 0.0
r = 1.0 / alpha
return math.exp(math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
+ r * math.log(r / (r + mu)) + k * math.log(mu / (r + mu)))
def hypergeom_pmf(k: int, total: int, good: int, draws: int) -> float:
"""P(K = k) for k good items in `draws` draws without replacement from
`total` items of which `good` are good."""
if k < 0 or k > good or draws - k < 0 or draws - k > total - good:
return 0.0
return math.exp(log_choose(good, k) + log_choose(total - good, draws - k)
- log_choose(total, draws))
def logsumexp(xs) -> float:
"""ln(sum of exp(x)) without overflow; -inf for an empty input."""
xs = list(xs)
if not xs:
return -math.inf
top = max(xs)
if top == -math.inf:
return -math.inf
if top == math.inf:
return math.inf
return top + math.log(sum(math.exp(x - top) for x in xs))
# Tail probabilities
def _gamma_q(a: float, x: float) -> float:
"""The regularized upper incomplete gamma function Q(a, x)."""
if a <= 0:
raise ValueError("a must be > 0")
if x <= 0:
return 1.0
log_front = -x + a * math.log(x) - math.lgamma(a)
if x < a + 1.0:
# Series for P(a, x).
ap = a
term = 1.0 / a
total = term
for _ in range(100000):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * 1e-16:
break
return max(0.0, 1.0 - total * math.exp(log_front))
# Continued fraction for Q(a, x), by the modified Lentz method.
tiny = 1e-300
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b
h = d
for i in range(1, 100000):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < tiny:
d = tiny
c = b + an / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-16:
break
return math.exp(log_front) * h
def chi2_sf(x: float, df: float) -> float:
"""P(X > x) for X chi-squared with df degrees of freedom."""
if df <= 0:
raise ValueError("df must be > 0")
if x <= 0:
return 1.0
return _gamma_q(df / 2.0, x / 2.0)
_STD_NORMAL = NormalDist()
def normal_sf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
"""P(X > x) for X ~ Normal(mu, sigma^2), by statistics.NormalDist."""
return _STD_NORMAL.cdf(-(x - mu) / sigma)
psmc.py 341 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/psmc/. The authors are listed in prov/H1EZ3X.jsonl.
"""A small version of PSMC (Li and Durbin 2011).
The two copies of one diploid genome are cut into bins of s bases. A bin
is 1 (heterozygous: at least one site differs), 0 (homozygous) or None
(missing). The hidden state of a bin is the interval that holds the
coalescence time T of the two copies at that bin.
Units. Time is in units of 2 N0 generations. The relative population size
lambda(t) = N(t) / N0 is piecewise constant: lambdas[k] on [t_k, t_{k+1}),
where breaks = [t_0 = 0, t_1, ..., t_{K-1}, t_K = inf]. Two lineages
coalesce at rate 1 / lambda(t). theta = 4 N0 mu s and rho = 4 N0 r s are the
mutation and recombination rates per bin.
Model. T at the first bin has the coalescent law with rate 1 / lambda(t).
Given T = t, a bin is heterozygous with probability 1 - exp(-theta t). Between
two bins, a recombination happens with probability 1 - exp(-rho t); then,
as in the SMC, the cut point u is uniform on (0, t) and the new time is drawn
from the coalescent law started at age u. More than one recombination in a
bin counts as one. With this per-bin probability, the law of T at the first
bin is kept along the chain only up to an error of order rho squared.
Differences from the PSMC program: theta and rho are given, not fitted; the
transition matrix comes from numerical integration (composite Simpson rule)
instead of closed forms; the M step is a coordinate search; the times are not
grouped into shared parameters.
"""
from __future__ import annotations
import bisect
import math
from typing import List, Optional, Sequence, Tuple
Obs = Optional[int]
_TAIL = 40.0 # The last interval is integrated up to t_{K-1} + 40 lambda.
def time_breaks(k: int, t_max: float) -> List[float]:
"""K + 1 breaks spaced like those of PSMC: t_i = 0.1 (exp(i / (K - 1)
ln(1 + 10 t_max)) - 1) for i < K, so t_{K-1} = t_max, and t_K = inf."""
if k < 1 or t_max <= 0:
raise ValueError("need k >= 1 and t_max > 0")
if k == 1:
return [0.0, math.inf]
c = math.log1p(10.0 * t_max)
out = [0.1 * math.expm1(i * c / (k - 1)) for i in range(k)]
out.append(math.inf)
return out
class History:
"""A piecewise-constant size history with its cumulative coalescence
rate Lambda(t) = integral from 0 to t of 1 / lambda."""
def __init__(self, breaks: Sequence[float], lambdas: Sequence[float]):
if len(breaks) != len(lambdas) + 1 or breaks[0] != 0.0 or breaks[-1] != math.inf:
raise ValueError("need breaks 0 = t_0 < ... < t_K = inf and K sizes")
if any(b >= c for b, c in zip(breaks, breaks[1:])):
raise ValueError("breaks must increase")
if any(x <= 0 for x in lambdas):
raise ValueError("sizes must be > 0")
self.t = list(breaks)
self.lam = [float(x) for x in lambdas]
self.k = len(lambdas)
cum = [0.0]
for j in range(self.k - 1):
cum.append(cum[-1] + (self.t[j + 1] - self.t[j]) / self.lam[j])
cum.append(math.inf)
self.cum = cum
# ln of G(t_j) = integral from 0 to t_j of exp(Lambda(u)) du.
self.log_g = [-math.inf] + [self._log_g(self.t[j]) for j in range(1, self.k)]
def piece(self, t: float) -> int:
return min(bisect.bisect_right(self.t, t) - 1, self.k - 1)
def cum_rate(self, t: float) -> float:
if t == math.inf:
return math.inf
j = self.piece(t)
return self.cum[j] + (t - self.t[j]) / self.lam[j]
def inverse_cum_rate(self, y: float) -> float:
j = min(bisect.bisect_right(self.cum, y) - 1, self.k - 1)
return self.t[j] + self.lam[j] * (y - self.cum[j])
def _log_g(self, y: float) -> float:
"""ln of the integral from 0 to y of exp(Lambda(u)) du, computed with
every exponent <= 0."""
if y <= 0:
return -math.inf
top = self.cum_rate(y)
total = 0.0
for i in range(self.k):
lo = self.t[i]
if lo >= y:
break
hi = min(y, self.t[i + 1])
total += self.lam[i] * (math.exp(self.cum_rate(hi) - top)
- math.exp(self.cum[i] - top))
return top + math.log(total)
def interval_probs(self) -> List[float]:
"""pi_k = P(T in [t_k, t_{k+1}))."""
return [math.exp(-self.cum[k]) - (math.exp(-self.cum[k + 1]) if k + 1 < self.k else 0.0)
for k in range(self.k)]
def laplace(self, c: float, k: int) -> float:
"""The integral over [t_k, t_{k+1}) of p(t) exp(-c t), where
p(t) = exp(-Lambda(t)) / lambda(t) is the density of T."""
r = 1.0 / self.lam[k] + c
width = self.t[k + 1] - self.t[k]
tail = 0.0 if width == math.inf else math.exp(-r * width)
return math.exp(-self.cum[k] - c * self.t[k]) * (1.0 - tail) / (self.lam[k] * r)
def _h_values(h: History, t: float) -> List[float]:
"""H(t, t_l) for l = 0 .. K, where H(t, x) is the integral over u in
(0, t) of P(T' >= x | start at u), and T' is drawn from the coalescent
law started at age u."""
log_gt = h._log_g(t)
out = []
for l in range(h.k + 1):
x = h.t[l]
if x == math.inf:
out.append(0.0)
elif x >= t:
out.append(math.exp(log_gt - h.cum[l]) if log_gt > -math.inf else 0.0)
else:
g = math.exp(h.log_g[l] - h.cum[l]) if h.log_g[l] > -math.inf else 0.0
out.append(g + (t - x))
return out
def transition_joint(h: History, rho: float, steps: int = 64) -> List[List[float]]:
"""J[k][l] = P(T in interval k and T' in interval l) for the times T and
T' of two neighbouring bins, with T from the stationary law."""
if rho < 0:
raise ValueError("need rho >= 0")
k_n = h.k
joint = [[0.0] * k_n for _ in range(k_n)]
for k in range(k_n):
joint[k][k] += h.laplace(rho, k)
if rho == 0:
continue
lo = h.t[k]
hi = h.t[k + 1]
m = steps
if hi == math.inf:
hi = lo + _TAIL * h.lam[k]
m = 4 * steps
step = (hi - lo) / m
acc = [0.0] * k_n
for i in range(m + 1):
t = lo + i * step
if t == 0.0:
continue # The integrand is 0 at t = 0.
w = 1.0 if i in (0, m) else (4.0 if i % 2 else 2.0)
dens = math.exp(-h.cum_rate(t)) / h.lam[k]
front = w * dens * (-math.expm1(-rho * t)) / t
hv = _h_values(h, t)
for l in range(k_n):
acc[l] += front * (hv[l] - hv[l + 1])
for l in range(k_n):
joint[k][l] += acc[l] * step / 3.0
return joint
def model_matrices(breaks: Sequence[float], lambdas: Sequence[float], theta: float,
rho: float, steps: int = 64):
"""(pi, A, e): the initial law, the K x K transition matrix (rows scaled
to sum to 1) and e[k] = P(heterozygous bin | T in interval k)."""
h = History(breaks, lambdas)
pi = h.interval_probs()
joint = transition_joint(h, rho, steps)
a = []
for row in joint:
total = sum(row)
a.append([x / total for x in row])
e = [1.0 - h.laplace(theta, k) / pi[k] for k in range(h.k)]
return pi, a, e
def _emit(e: Sequence[float], o: Obs) -> List[float]:
if o is None:
return [1.0] * len(e)
if o == 1:
return list(e)
return [1.0 - x for x in e]
def forward_backward(obs: Sequence[Obs], pi, a, e):
"""Scaled forward-backward pass.
Returns (loglik, post, xi, het, hom, first): the log-likelihood, the
posterior of the state at each bin, the expected number of transitions
k -> l, the expected numbers of heterozygous and homozygous bins in each
state, and the posterior of the first state.
"""
n = len(obs)
k_n = len(pi)
if n == 0:
raise ValueError("empty sequence")
alpha = []
scale = []
b = _emit(e, obs[0])
cur = [pi[k] * b[k] for k in range(k_n)] # @line L3
for i in range(n):
if i > 0:
b = _emit(e, obs[i])
prev = alpha[-1]
cur = [sum(prev[k] * a[k][l] for k in range(k_n)) * b[l] for l in range(k_n)]
c = sum(cur)
if c <= 0:
raise ValueError("observations have probability 0")
scale.append(c)
alpha.append([x / c for x in cur])
loglik = sum(math.log(c) for c in scale)
beta = [1.0] * k_n # @line L4
post = [None] * n
xi = [[0.0] * k_n for _ in range(k_n)]
het = [0.0] * k_n
hom = [0.0] * k_n
for i in range(n - 1, -1, -1):
g = [alpha[i][k] * beta[k] for k in range(k_n)]
post[i] = g
if obs[i] == 1:
for k in range(k_n):
het[k] += g[k] # @line L5
elif obs[i] == 0:
for k in range(k_n):
hom[k] += g[k]
if i == 0:
break
b = _emit(e, obs[i])
nxt = [b[l] * beta[l] / scale[i] for l in range(k_n)]
for k in range(k_n):
ak = alpha[i - 1][k]
for l in range(k_n):
xi[k][l] += ak * a[k][l] * nxt[l]
beta = [sum(a[k][l] * nxt[l] for l in range(k_n)) for k in range(k_n)]
return loglik, post, xi, het, hom, post[0]
def log_likelihood(obs: Sequence[Obs], pi, a, e) -> float:
return forward_backward(obs, pi, a, e)[0]
def expected_complete_loglik(stats, breaks, lambdas, theta, rho, steps=64) -> float:
"""Q(lambda) for the expected counts stats = (xi, het, hom, first)."""
xi, het, hom, first = stats
pi, a, e = model_matrices(breaks, lambdas, theta, rho, steps)
q = 0.0
for k in range(len(pi)):
q += first[k] * math.log(pi[k])
q += het[k] * math.log(e[k]) + hom[k] * math.log1p(-e[k])
for l in range(len(pi)):
if xi[k][l] > 0:
q += xi[k][l] * math.log(a[k][l])
return q
def _golden_max(f, lo, hi, iters):
g = (math.sqrt(5.0) - 1.0) / 2.0
x1 = hi - g * (hi - lo)
x2 = lo + g * (hi - lo)
f1, f2 = f(x1), f(x2)
for _ in range(iters):
if f1 < f2:
lo, x1, f1 = x1, x2, f2
x2 = lo + g * (hi - lo)
f2 = f(x2)
else:
hi, x2, f2 = x2, x1, f1
x1 = hi - g * (hi - lo)
f1 = f(x1)
return (x1, f1) if f1 >= f2 else (x2, f2)
def psmc_fit(obs: Sequence[Obs], breaks: Sequence[float], theta: float, rho: float,
lambdas0: Sequence[float], iterations: int = 5, steps: int = 64,
search: float = 2.0, golden_iters: int = 16):
"""EM for the sizes lambda with theta and rho fixed.
Returns (lambdas, logliks), where logliks[i] is the log-likelihood of
the sizes before iteration i, and the last entry that of the result.
The M step changes one ln(lambda_j) at a time by golden-section search
on [ln lambda_j - search, ln lambda_j + search] and keeps a change only
if it raises Q, so the log-likelihood never decreases.
"""
lam = [float(x) for x in lambdas0]
logliks = []
for _ in range(iterations): # @line L1
pi, a, e = model_matrices(breaks, lam, theta, rho, steps) # @line L2
loglik, _, xi, het, hom, first = forward_backward(obs, pi, a, e)
logliks.append(loglik)
stats = (xi, het, hom, first)
best = expected_complete_loglik(stats, breaks, lam, theta, rho, steps)
for j in range(len(lam)): # @line L6
def q_of(x, j=j):
trial = lam[:]
trial[j] = math.exp(x)
return expected_complete_loglik(stats, breaks, trial, theta, rho, steps)
x0 = math.log(lam[j])
x, val = _golden_max(q_of, x0 - search, x0 + search, golden_iters)
if val > best:
lam[j] = math.exp(x)
best = val
pi, a, e = model_matrices(breaks, lam, theta, rho, steps)
logliks.append(log_likelihood(obs, pi, a, e))
return lam, logliks # @line L7
def simulate_pair(rng, length: int, breaks: Sequence[float], lambdas: Sequence[float],
theta: float, rho: float) -> Tuple[List[float], List[int]]:
"""Coalescence times and observations of `length` bins under the
continuous model. For each bin: one random() for the observation, then,
except after the last bin, one random() for recombination and, if there
is one, one random() for u and one expovariate for the new time."""
h = History(breaks, lambdas)
t = h.inverse_cum_rate(rng.expovariate(1.0))
times, obs = [], []
for i in range(length):
times.append(t)
obs.append(1 if rng.random() < -math.expm1(-theta * t) else 0)
if i + 1 < length and rng.random() < -math.expm1(-rho * t):
u = rng.random() * t
t = h.inverse_cum_rate(h.cum_rate(u) + rng.expovariate(1.0))
return times, obs
def to_real_units(breaks: Sequence[float], lambdas: Sequence[float], theta: float,
mu: float, bin_size: int, generation_time: float):
"""Scale the result: N0 = theta / (4 mu s); time t_k becomes 2 N0 t_k
generations, or years with the generation time; size k is N0 lambda_k."""
n0 = theta / (4.0 * mu * bin_size)
years = [2.0 * n0 * t * generation_time for t in breaks]
sizes = [n0 * x for x in lambdas]
return n0, years, sizes
test_psmc.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/psmc/. The authors are listed in prov/H1EZ3X.jsonl.
import itertools
import math
import random
import pytest
from biostoch import chi2_sf
from psmc import (
History,
forward_backward,
log_likelihood,
model_matrices,
psmc_fit,
simulate_pair,
time_breaks,
to_real_units,
transition_joint,
)
BREAKS = [0.0, 0.3, 0.8, 1.8, math.inf]
SIZES = [1.0, 0.4, 2.0, 1.0]
def test_time_breaks():
t = time_breaks(5, 15.0)
assert t[0] == 0.0 and t[-1] == math.inf and len(t) == 6
assert t[4] == pytest.approx(15.0)
assert all(a < b for a, b in zip(t, t[1:]))
assert time_breaks(1, 3.0) == [0.0, math.inf]
def test_history_rates():
h = History(BREAKS, SIZES)
# Lambda at 1.0: 0.3 / 1 + 0.5 / 0.4 + 0.2 / 2.
assert h.cum_rate(1.0) == pytest.approx(0.3 + 1.25 + 0.1)
for y in (0.0, 0.2, 1.0, 1.7, 5.0):
assert h.cum_rate(h.inverse_cum_rate(y)) == pytest.approx(y)
pi = h.interval_probs()
assert sum(pi) == pytest.approx(1.0)
flat = History([0.0, 0.5, 1.0, math.inf], [1.0, 1.0, 1.0]).interval_probs()
assert flat == pytest.approx([1 - math.exp(-0.5), math.exp(-0.5) - math.exp(-1.0), math.exp(-1.0)])
def test_transition_margins():
h = History(BREAKS, SIZES)
pi = h.interval_probs()
for rho in (0.5, 0.1, 0.01):
joint = transition_joint(h, rho)
for k in range(4):
assert sum(joint[k]) == pytest.approx(pi[k], abs=1e-6)
# With a recombination probability 1 - exp(-rho t) per bin, pi is
# kept only up to an error of order rho squared.
col = sum(joint[j][k] for j in range(4))
assert abs(col - pi[k]) <= 0.15 * rho * rho
_, a, _ = model_matrices(BREAKS, SIZES, 0.1, 0.0)
assert a == [[1.0 if k == l else 0.0 for l in range(4)] for k in range(4)]
def test_transition_against_simulation():
rng = random.Random(2011)
h = History(BREAKS, SIZES)
rho, reps = 0.8, 20000
joint = transition_joint(h, rho)
counts = [[0] * 4 for _ in range(4)]
for _ in range(reps):
t = h.inverse_cum_rate(rng.expovariate(1.0))
k = h.piece(t)
if rng.random() < -math.expm1(-rho * t):
u = rng.random() * t
t = h.inverse_cum_rate(h.cum_rate(u) + rng.expovariate(1.0))
counts[k][h.piece(t)] += 1
obs = [counts[k][l] for k in range(4) for l in range(4)]
exp = [reps * joint[k][l] for k in range(4) for l in range(4)]
assert min(exp) > 5
stat = sum((o - x) ** 2 / x for o, x in zip(obs, exp))
assert chi2_sf(stat, 15) > 0.001
def test_emission():
h = History(BREAKS, SIZES)
pi, _, e = model_matrices(BREAKS, SIZES, 0.1, 0.3)
# Compare with a direct Simpson integral of p(t) (1 - exp(-theta t)).
k, m = 1, 2000
lo, hi = BREAKS[k], BREAKS[k + 1]
step = (hi - lo) / m
total = 0.0
for i in range(m + 1):
t = lo + i * step
w = 1 if i in (0, m) else (4 if i % 2 else 2)
total += w * math.exp(-h.cum_rate(t)) / h.lam[k] * -math.expm1(-0.1 * t)
assert e[k] == pytest.approx(total * step / 3 / pi[k], rel=1e-9)
assert all(0 < x < 1 for x in e)
assert e == sorted(e)
def brute_force_loglik(obs, pi, a, e):
k_n = len(pi)
total = 0.0
for path in itertools.product(range(k_n), repeat=len(obs)):
p = pi[path[0]]
for i, s in enumerate(path):
if i:
p *= a[path[i - 1]][s]
if obs[i] == 1:
p *= e[s]
elif obs[i] == 0:
p *= 1 - e[s]
total += p
return math.log(total)
def test_forward_backward_against_enumeration():
breaks = [0.0, 0.4, 1.2, math.inf]
pi, a, e = model_matrices(breaks, [1.0, 0.5, 2.0], 0.4, 0.6)
obs = [0, 1, None, 1, 0, 0]
loglik, post, xi, het, hom, first = forward_backward(obs, pi, a, e)
assert loglik == pytest.approx(brute_force_loglik(obs, pi, a, e), rel=1e-12)
for g in post:
assert sum(g) == pytest.approx(1.0)
assert sum(map(sum, xi)) == pytest.approx(len(obs) - 1)
assert sum(het) == pytest.approx(2.0) and sum(hom) == pytest.approx(3.0)
# The posterior at bin 2 against enumeration with the state fixed.
k_n = 3
joint = []
for s in range(k_n):
tot = 0.0
for path in itertools.product(range(k_n), repeat=len(obs)):
if path[2] != s:
continue
p = pi[path[0]]
for i, q in enumerate(path):
if i:
p *= a[path[i - 1]][q]
p *= e[q] if obs[i] == 1 else (1 - e[q] if obs[i] == 0 else 1.0)
tot += p
joint.append(tot)
z = sum(joint)
assert post[2] == pytest.approx([x / z for x in joint], rel=1e-10)
def test_em_never_decreases_and_moves_toward_the_truth():
rng = random.Random(7)
breaks = [0.0, 0.5, 1.5, math.inf]
truth = [0.3, 1.0, 1.0]
theta, rho = 0.2, 0.05
_, obs = simulate_pair(rng, 3000, breaks, truth, theta, rho)
lam, logliks = psmc_fit(obs, breaks, theta, rho, [1.0, 1.0, 1.0], iterations=2, steps=16)
assert all(b >= a - 1e-9 for a, b in zip(logliks, logliks[1:]))
assert logliks[-1] > logliks[0]
# The recent size starts at 1.0 and the truth is 0.3.
assert lam[0] < 1.0
def test_real_units():
n0, years, sizes = to_real_units([0.0, 0.5, math.inf], [1.0, 2.0], 0.06, 1.25e-8, 100, 25)
assert n0 == pytest.approx(12000.0)
assert years[1] == pytest.approx(2 * 12000 * 0.5 * 25)
assert sizes == pytest.approx([12000.0, 24000.0])
def test_bad_input():
with pytest.raises(ValueError):
History([0.0, 1.0], [1.0])
with pytest.raises(ValueError):
History([0.0, 1.0, math.inf], [1.0, -1.0])
pi, a, e = model_matrices([0.0, math.inf], [1.0], 0.1, 0.1)
assert a == [[1.0]]
assert log_likelihood([None, None], pi, a, e) == pytest.approx(0.0)
History
Li and Durbin published PSMC in Nature in 2011 with genomes of individuals from several human populations, and it became the standard method to infer size history from single genomes. They based the transition on the sequentially Markov coalescent of McVean and Cardin (2005) and fitted it with the EM algorithm for HMMs. Schiffels and Durbin extended it to several haplotypes as MSMC in 2014.
References
- Heng Li and Richard Durbin, Inference of human population history from individual whole-genome sequences, Nature 475(7357), 2011, pp. 493-496 and the Supplementary Information (the hidden Markov model of the coalescence time, its transition and emission probabilities, the time intervals and the scaling to years)
- Gilean A. T. McVean and Niall J. Cardin, Approximating the coalescent with recombination, Philosophical Transactions of the Royal Society B 360(1459), 2005, pp. 1387-1393 (the sequentially Markov coalescent, on which the transition of PSMC is based)
- Lawrence R. Rabiner, A tutorial on hidden Markov models and selected applications in speech recognition, Proceedings of the IEEE 77(2), 1989, pp. 257-286 (the scaled forward-backward procedure and the re-estimation of HMM parameters)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag H1EZ3X Edit this page History Report an error Markdown