Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 kk intervals, and whose observations are the heterozygous and homozygous parts of the genome. The rate of coalescence at time tt is the inverse of the effective population size at tt, so the sizes that best explain the observations, found by expectation maximization, give a history of N(t)N(t). 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 o1,…,ono_1, \ldots, o_n of bins of ss 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 0=t0<t1<⋯<tk−1<tk=∞0 = t_0 < t_1 < \cdots < t_{k-1} < t_k = \infty in units of 2N02N_0 generations, where N0N_0 is a reference size. The scaled mutation rate θ=4N0μs\theta = 4N_0 \mu s and recombination rate ρ=4N0rs\rho = 4N_0 r s per bin.

Output. Relative sizes λ1,…,λk\lambda_1, \ldots, \lambda_k, with N(t)=N0λjN(t) = N_0 \lambda_j for tt in [tj−1,tj)[t_{j-1}, t_j), that locally maximize the likelihood of the bins.

The model. Let Λ(t)=∫0tdu/λ(u)\Lambda(t) = \int_0^t du / \lambda(u), the cumulative rate of coalescence of two lineages.

  • Hidden states. State jj means that the coalescence time TT at the bin is in [tj−1,tj)[t_{j-1}, t_j). At the first bin, TT has the density p(t)=e−Λ(t)/λ(t)p(t) = e^{-\Lambda(t)} / \lambda(t), so πj=e−Λ(tj−1)−e−Λ(tj)\pi_j = e^{-\Lambda(t_{j-1})} - e^{-\Lambda(t_j)}.
  • Emission. Given T=tT = t, a bin is heterozygous with probability 1−e−θt1 - e^{-\theta t}: on the path of length 2t2t between the two copies, mutations come at rate θ/2\theta/2 per unit of length. So ej=1−1πj∫tj−1tjp(t)e−θt dte_j = 1 - \frac{1}{\pi_j}\int_{t_{j-1}}^{t_j} p(t) e^{-\theta t}\, dt.
  • Transition. Between two neighbouring bins, with T=tT = t, a recombination happens with probability 1−e−ρt1 - e^{-\rho t}. Then, as in the sequentially Markov coalescent, one lineage is cut at an age uu uniform on (0,t)(0, t) and coalesces again with the other lineage, going back from uu at rate 1/λ1/\lambda. Otherwise TT stays the same. Integrating over the interval of TT gives the k×kk \times k matrix AA.

The algorithm

  1. PSMC(o_1..o_n, t_0..t_k, θ, ρ, λ)
  2. 1for each of R iterations do
  3. 2build π, A and e from λ, θ and ρ
  4. 3forward pass: α_1 ← π ∘ e(o_1), then α_i ← (α_{i−1} A) ∘ e(o_i), scaled to sum 1
  5. 4backward pass: β_n ← 1, then β_{i−1} ← A (e(o_i) ∘ β_i), with the same scales
  6. 5add up the expected counts: first state, transitions j → l, het and hom bins per state
  7. 6for j = 1, ..., k do change λ_j to raise Q(λ), the expected log-likelihood of the counts
  8. 7return λ

Here e(o)e(o) is the vector of eje_j for a heterozygous bin, of 1−ej1 - e_j for a homozygous bin, and all ones for a missing bin. Lines L3 to L5 are the forward-backward algorithm: the posterior of state jj at bin ii is αi(j)βi(j)\alpha_i(j)\beta_i(j), and the expected number of transitions j→lj \to l between bins i−1i - 1 and ii is αi−1(j)Ajl el(oi)βi(l)/ci\alpha_{i-1}(j) A_{jl}\, e_l(o_i) \beta_i(l) / c_i, where cic_i is the scale of bin ii. The log-likelihood is ∑iln⁡ci\sum_i \ln c_i.

Q(λ)Q(\lambda) is the expected complete-data log-likelihood

Q(λ)=∑jFjln⁡πj+∑j,lXjlln⁡Ajl+∑j(Hjln⁡ej+Mjln⁡(1−ej)),Q(\lambda) = \sum_j F_j \ln \pi_j + \sum_{j,l} X_{jl} \ln A_{jl} + \sum_j \left(H_j \ln e_j + M_j \ln(1 - e_j)\right),

where FF, XX, HH and MM are the expected counts of line L5 and π\pi, AA, ee are computed from the new λ\lambda. Line L6 changes one ln⁡λj\ln \lambda_j at a time by a golden-section search and keeps a change only if QQ goes up.

The transition in closed form, up to one integral. Write G(x)=∫0xeΛ(u)duG(x) = \int_0^x e^{\Lambda(u)} du. With the cut at uu, the new time T′T' satisfies P(T′≥x)=e−(Λ(x)−Λ(u))P(T' \ge x) = e^{-(\Lambda(x) - \Lambda(u))} for x≥ux \ge u and 11 for x<ux < u. Averaging over uu uniform on (0,t)(0, t),

∫0tP(T′≥x∣u) du={e−Λ(x)G(t),x≥t,e−Λ(x)G(x)+(t−x),x<t.\int_0^t P(T' \ge x \mid u)\, du = \begin{cases} e^{-\Lambda(x)} G(t), & x \ge t, \\ e^{-\Lambda(x)} G(x) + (t - x), & x < t. \end{cases}

Call this H(t,x)H(t, x). Then the joint probability that TT is in interval jj and T′T' is in interval ll is

Jjl=[j=l]∫tj−1tjp(t)e−ρt dt+∫tj−1tjp(t) 1−e−ρtt (H(t,tl−1)−H(t,tl)) dt,J_{jl} = [j = l] \int_{t_{j-1}}^{t_j} p(t) e^{-\rho t}\, dt + \int_{t_{j-1}}^{t_j} p(t)\, \frac{1 - e^{-\rho t}}{t}\, \big(H(t, t_{l-1}) - H(t, t_l)\big)\, dt,

and Ajl=Jjl/πjA_{jl} = J_{jl} / \pi_j. The first integral has a closed form because λ\lambda is constant on the interval. The implementation computes the second by the composite Simpson rule, and GG in closed form, piece by piece. Li and Durbin give closed forms for the whole matrix.

Time intervals. The implementation spaces the breaks as tj=0.1(ejln⁡(1+10tmax⁡)/(k−1)−1)t_j = 0.1\left(e^{j \ln(1 + 10 t_{\max})/(k-1)} - 1\right) for j<kj < k, dense near the present and sparse in the past, so that each interval holds a useful number of coalescences.

Example

Take k=3k = 3 intervals with breaks 0,0.5,1.5,∞0, 0.5, 1.5, \infty, a constant size λ=(1,1,1)\lambda = (1, 1, 1), θ=0.05\theta = 0.05 and ρ=0.01\rho = 0.01 per bin.

  • Initial law. π=(1−e−0.5, e−0.5−e−1.5, e−1.5)=(0.39347,0.38340,0.22313)\pi = (1 - e^{-0.5},\ e^{-0.5} - e^{-1.5},\ e^{-1.5}) = (0.39347, 0.38340, 0.22313).
  • Emission. For interval 1, ∫00.5e−te−0.05tdt=(1−e−0.525)/1.05=0.38899\int_0^{0.5} e^{-t} e^{-0.05t} dt = (1 - e^{-0.525})/1.05 = 0.38899, so e1=1−0.38899/0.39347=0.01137e_1 = 1 - 0.38899/0.39347 = 0.01137. In the same way e=(0.01137,0.04477,0.11643)e = (0.01137, 0.04477, 0.11643): older states give more heterozygous bins.
  • Transition. The rows of AA are (0.998361,0.001036,0.000603)(0.998361, 0.001036, 0.000603), (0.001060,0.995370,0.003570)(0.001060, 0.995370, 0.003570) and (0.001052,0.006090,0.992858)(0.001052, 0.006090, 0.992858). 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 0,0,1,1,00, 0, 1, 1, 0, the log-likelihood is −5.8766-5.8766, and the posterior of the third bin is (0.0177,0.2396,0.7427)(0.0177, 0.2396, 0.7427). 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 20 00020\,000 bins with θ=0.1\theta = 0.1, ρ=0.02\rho = 0.02, breaks 0,0.214,0.887,3,∞0, 0.214, 0.887, 3, \infty and true sizes (0.3,1,1,1)(0.3, 1, 1, 1), and start EM at (1,1,1,1)(1, 1, 1, 1). Eight iterations raise the log-likelihood from −2663.5-2663.5 to −2645.3-2645.3 and give λ=(0.17,1.10,0.87,0.65)\lambda = (0.17, 1.10, 0.87, 0.65). The fit finds the small recent size, but with only 738 heterozygous bins the estimates are noisy. A human genome has about 3×1073 \times 10^7 bins of 100 bases.

Correctness

Lines L3 to L5 compute, for the HMM (π,A,e)(\pi, A, e), 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 e−ρte^{-\rho t} the time stays, and otherwise the new time has the law of T′T' averaged over the cut age, whose tail is H(t,x)/tH(t, x)/t. Its row sums are πj\pi_j, so AA is a stochastic matrix.

For the sizes, ℓ(λ′)−ℓ(λ)≥Q(λ′)−Q(λ)\ell(\lambda') - \ell(\lambda) \ge Q(\lambda') - Q(\lambda) when QQ is built from the posterior under λ\lambda, which is the basic inequality of EM. Line L6 accepts a new λ′\lambda' only when Q(λ′)>Q(λ)Q(\lambda') > Q(\lambda), 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 0=t0<⋯<tk=∞0 = t_0 < \cdots < t_k = \infty, and λ(t)=λj>0\lambda(t) = \lambda_j > 0 on Ij=[tj−1,tj)I_j = [t_{j-1}, t_j). Let Λ(t)=∫0tdu/λ(u)\Lambda(t) = \int_0^t du/\lambda(u) and G(x)=∫0xeΛ(u)duG(x) = \int_0^x e^{\Lambda(u)} du. The coalescence time TT of the two copies at a bin has the density p(t)=e−Λ(t)/λ(t)p(t) = e^{-\Lambda(t)}/\lambda(t), so P(T≥x)=e−Λ(x)P(T \ge x) = e^{-\Lambda(x)}. Given T=tT = t, the bin is heterozygous with probability 1−e−θt1 - e^{-\theta t}. Between two bins, with probability e−ρte^{-\rho t} the next time is tt, and otherwise the next time is T′T', drawn as follows: uu is uniform on (0,t)(0, t), and given uu, P(T′≥x)=e−(Λ(x)−Λ(u))P(T' \ge x) = e^{-(\Lambda(x) - \Lambda(u))} for x≥ux \ge u and 11 for x<ux < u.

Lemma 1. For t>0t > 0 and x≥0x \ge 0, H(t,x)=∫0tP(T′≥x∣u) duH(t, x) = \int_0^t P(T' \ge x \mid u)\, du is e−Λ(x)G(t)e^{-\Lambda(x)} G(t) when x≥tx \ge t, and e−Λ(x)G(x)+(t−x)e^{-\Lambda(x)} G(x) + (t - x) when x<tx < t. Also H(t,0)=tH(t, 0) = t and H(t,∞)=0H(t, \infty) = 0.

Proof. If x≥tx \ge t, every uu in (0,t)(0, t) has u≤xu \le x, so the integrand is eΛ(u)−Λ(x)e^{\Lambda(u) - \Lambda(x)}, and the integral is e−Λ(x)G(t)e^{-\Lambda(x)} G(t). If x<tx < t, split at xx: on (0,x)(0, x) the integrand is eΛ(u)−Λ(x)e^{\Lambda(u) - \Lambda(x)}, which gives e−Λ(x)G(x)e^{-\Lambda(x)} G(x), and on (x,t)(x, t) it is 1, which gives t−xt - x. With x=0x = 0, G(0)=0G(0) = 0 and the value is tt. As x→∞x \to \infty, Λ(x)→∞\Lambda(x) \to \infty while G(t)G(t) is fixed, so H(t,x)→0H(t, x) \to 0. □\square

Lemma 2. Let Jjl=P(T∈Ij,Tnext∈Il)J_{jl} = P(T \in I_j, T_{\text{next}} \in I_l) for the times of two neighbouring bins, with TT from the density pp. Then

Jjl=[j=l]∫Ijp(t)e−ρtdt+∫Ijp(t)1−e−ρtt(H(t,tl−1)−H(t,tl))dt,J_{jl} = [j = l] \int_{I_j} p(t) e^{-\rho t} dt + \int_{I_j} p(t) \frac{1 - e^{-\rho t}}{t} \big(H(t, t_{l-1}) - H(t, t_l)\big) dt,

and ∑lJjl=πj=P(T∈Ij)\sum_l J_{jl} = \pi_j = P(T \in I_j).

Proof. Condition on T=tT = t in IjI_j. Without recombination, probability e−ρte^{-\rho t}, the next time is t∈Ijt \in I_j. With recombination, the next time is T′T', and

P(T′∈Il∣t)=1t∫0t(P(T′≥tl−1∣u)−P(T′≥tl∣u))du=H(t,tl−1)−H(t,tl)t.P(T' \in I_l \mid t) = \frac{1}{t}\int_0^t \big(P(T' \ge t_{l-1} \mid u) - P(T' \ge t_l \mid u)\big) du = \frac{H(t, t_{l-1}) - H(t, t_l)}{t}.

Integrating against p(t)p(t) over IjI_j gives the formula. Summed over ll, the differences telescope to H(t,0)−H(t,∞)=tH(t, 0) - H(t, \infty) = t by Lemma 1, so ∑lJjl=∫Ijp(t)(e−ρt+1−e−ρt)dt=πj\sum_l J_{jl} = \int_{I_j} p(t)(e^{-\rho t} + 1 - e^{-\rho t}) dt = \pi_j. □\square

So Ajl=Jjl/πjA_{jl} = J_{jl}/\pi_j is the transition matrix of the interval of TT, and each row sums to 1. The code divides each row by its numerical sum, which is πj\pi_j up to the error of the Simpson rule.

Lemma 3. For c≥0c \ge 0, ∫Ijp(t)e−ctdt=e−Λ(tj−1)−ctj−1λj(1/λj+c)(1−e−(1/λj+c)(tj−tj−1))\int_{I_j} p(t) e^{-ct} dt = \frac{e^{-\Lambda(t_{j-1}) - c t_{j-1}}}{\lambda_j (1/\lambda_j + c)} \left(1 - e^{-(1/\lambda_j + c)(t_j - t_{j-1})}\right), with the last factor 1 when tj=∞t_j = \infty. In particular, πj=e−Λ(tj−1)−e−Λ(tj)\pi_j = e^{-\Lambda(t_{j-1})} - e^{-\Lambda(t_j)}, and ej=1−1πj∫Ijp(t)e−θtdte_j = 1 - \frac{1}{\pi_j} \int_{I_j} p(t) e^{-\theta t} dt is the probability that a bin is heterozygous given T∈IjT \in I_j.

Proof. On IjI_j, Λ(t)=Λ(tj−1)+(t−tj−1)/λj\Lambda(t) = \Lambda(t_{j-1}) + (t - t_{j-1})/\lambda_j, so the integrand is 1λje−Λ(tj−1)−ctj−1e−(1/λj+c)(t−tj−1)\frac{1}{\lambda_j} e^{-\Lambda(t_{j-1}) - c t_{j-1}} e^{-(1/\lambda_j + c)(t - t_{j-1})}, an exponential whose integral over IjI_j is the formula. With c=0c = 0 it gives πj\pi_j. Given T∈IjT \in I_j, TT has the density p/πjp/\pi_j on IjI_j, and the probability of a homozygous bin is the mean of e−θTe^{-\theta T}. □\square

Lemma 3 with c=ρc = \rho gives the first term of Lemma 2. On IiI_i, ∫Ii∩(0,x)eΛ(u)du=λi(eΛ(min⁡(x,ti))−eΛ(ti−1))\int_{I_i \cap (0, x)} e^{\Lambda(u)} du = \lambda_i (e^{\Lambda(\min(x, t_i))} - e^{\Lambda(t_{i-1})}), and G(x)G(x) is the sum over ii of these terms. This is how the code computes GG, with every exponent shifted by −Λ(x)-\Lambda(x) so that none is positive.

Lemma 4. For observations o1,…,ono_1, \ldots, o_n, with bi(j)=ejb_i(j) = e_j, 1−ej1 - e_j or 11 for a heterozygous, homozygous or missing bin, lines L3 and L4 give ∏ici=P(o1,…,on)\prod_i c_i = P(o_1, \ldots, o_n), αi(j)βi(j)=P(Si=j∣o)\alpha_i(j)\beta_i(j) = P(S_i = j \mid o), and αi−1(j)Ajlbi(l)βi(l)/ci=P(Si−1=j,Si=l∣o)\alpha_{i-1}(j) A_{jl} b_i(l) \beta_i(l)/c_i = P(S_{i-1} = j, S_i = l \mid o), where SiS_i is the hidden state of bin ii.

Proof. By induction, αi(j)=P(Si=j∣o1,…,oi)\alpha_i(j) = P(S_i = j \mid o_1, \ldots, o_i) and ci=P(oi∣o1,…,oi−1)c_i = P(o_i \mid o_1, \ldots, o_{i-1}): the unscaled vector (αi−1A)∘bi(\alpha_{i-1} A) \circ b_i is P(Si=j,oi∣o1..oi−1)P(S_i = j, o_i \mid o_1..o_{i-1}) by the Markov property, and its sum is cic_i. The product of the cic_i is P(o)P(o) by the chain rule. Backward, βi(j)=P(oi+1,…,on∣Si=j)/P(oi+1,…,on∣o1,…,oi)\beta_i(j) = P(o_{i+1}, \ldots, o_n \mid S_i = j) / P(o_{i+1}, \ldots, o_n \mid o_1, \ldots, o_i), again by induction from βn=1\beta_n = 1, because ∑lAjlbi+1(l)βi+1(l)/ci+1\sum_l A_{jl} b_{i+1}(l) \beta_{i+1}(l)/c_{i+1} conditions on the next state. The two claims about posteriors follow by Bayes' rule, since given SiS_i the observations before and after bin ii are independent. A missing bin multiplies every state by 1, which is the same as leaving it out of the product. □\square

Lemma 5. Let FjF_j, XjlX_{jl}, HjH_j and MjM_j be the posterior expected counts under λ\lambda of line L5, and define Q(λ′)Q(\lambda') as on the page with π\pi, AA, ee from λ′\lambda'. Then ℓ(λ′)−ℓ(λ)≥Q(λ′)−Q(λ)\ell(\lambda') - \ell(\lambda) \ge Q(\lambda') - Q(\lambda), where ℓ\ell is the log-likelihood.

Proof. For a path ss of states, ln⁡Pλ′(s,o)=ln⁡πs1+∑iln⁡Asi−1si+∑i:oi≠missingln⁡bi(si)\ln P_{\lambda'}(s, o) = \ln \pi_{s_1} + \sum_i \ln A_{s_{i-1} s_i} + \sum_{i : o_i \ne \text{missing}} \ln b_i(s_i), so Q(λ′)=Eλ[ln⁡Pλ′(S,o)∣o]Q(\lambda') = E_\lambda[\ln P_{\lambda'}(S, o) \mid o], with the expectation over the posterior q(s)=Pλ(s∣o)q(s) = P_\lambda(s \mid o) of Lemma 4. Then

ℓ(λ′)=ln⁡∑sPλ′(s,o)≥∑sq(s)ln⁡Pλ′(s,o)q(s)=Q(λ′)+H(q)\ell(\lambda') = \ln \sum_s P_{\lambda'}(s, o) \ge \sum_s q(s) \ln \frac{P_{\lambda'}(s, o)}{q(s)} = Q(\lambda') + \mathcal{H}(q)

by Jensen's inequality, where H(q)\mathcal{H}(q) is the entropy of qq, and equality holds at λ′=λ\lambda' = \lambda because then Pλ(s,o)/q(s)=Pλ(o)P_\lambda(s, o)/q(s) = P_\lambda(o) for every ss. Subtracting the two gives the claim. □\square

Theorem. Each iteration of lines L1 to L6 returns sizes λ′\lambda' with ℓ(λ′)≥ℓ(λ)\ell(\lambda') \ge \ell(\lambda), and the log-likelihoods that the implementation reports never decrease.

Proof. Line L6 starts from λ′=λ\lambda' = \lambda and replaces one coordinate only when the new value has a strictly larger QQ. So at the end Q(λ′)≥Q(λ)Q(\lambda') \ge Q(\lambda), and Lemma 5 gives ℓ(λ′)≥ℓ(λ)\ell(\lambda') \ge \ell(\lambda). 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. □\square

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, Θ(k2)\Theta(k^2), so a pass costs Θ(nk2)\Theta(n k^2) and stores Θ(nk)\Theta(n k) forward values.
  • Building the model. The Simpson rule with mm points per interval, and HH at k+1k + 1 breaks for each point, costs Θ(k2m)\Theta(k^2 m) per matrix.
  • The M step. Line L6 evaluates QQ about gg times for each of the kk sizes, each time with a new matrix, so it costs Θ(gk3m)\Theta(g k^3 m). It does not depend on nn.
  • Total. Θ(r(nk2+gk3m))\Theta(r(n k^2 + g k^3 m)) time for rr iterations. For a genome, nn is in the tens of millions and kk 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 1−e−ρt1 - e^{-\rho t} per bin, the chain keeps the law π\pi only up to an error of order ρ2\rho^2. The rows of the joint matrix sum to π\pi 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 θ\theta and λ\lambda in coalescent units. With a mutation rate μ\mu per base per generation and a generation time gg, N0=θ/(4μs)N_0 = \theta/(4\mu s), a break tjt_j is 2N0tjg2 N_0 t_j g years, and N(t)=N0λjN(t) = N_0 \lambda_j. Errors in μ\mu and gg move the curve along both axes.

Variants and improvements

  • The PSMC program. It also estimates θ\theta and ρ\rho, 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 O(k)O(k) time per bin instead of O(k2)O(k^2) (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 θ\theta 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 θ\theta 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 μ\mu and gg.

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.

biostoch.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example