Techniqueadvanced
Wright-Fisher diffusion
Also called diffusion approximation in population genetics, Kimura diffusion.
Approximate allele frequency dynamics in a large population by a diffusion process, and solve its Kolmogorov equations for fixation and sojourn times.
The Wright-Fisher diffusion replaces the discrete allele count of a large population by a continuous frequency that moves like a diffusion process. The mean and variance of the change in one generation fix the drift and diffusion coefficients, and questions about the population become ordinary or partial differential equations: the backward equation gives fixation probabilities and mean times, and the forward equation gives the density of the frequency. Kimura made this the main tool of theoretical population genetics. It is an approximation, good when the population is large and selection and mutation are weak, and this page shows where it breaks.
In plain words
In a big population, the share of a gene variant changes only a little in each generation, partly by chance and partly by selection. Over many generations these small steps look like the path of a particle that is pushed by a weak wind (selection) and shaken at random (chance). The shaking is strongest when the variant is at middle frequency and dies out when the variant is lost or fixed. Physicists have tools for such particles: the answer to "where does it end up?" or "how long does it take?" is the solution of one equation. The technique replaces the real, step-by-step population by this particle, solves the equation, and so gives simple formulas. The price is a small error, which grows when the population is small or selection is strong.
When it applies
- A large population. diploid individuals ( copies), with large. The change of frequency per generation is then small, of order .
- Weak forces on the scale of drift. The selection coefficient and mutation rate are of order , so that and stay fixed as grows. Then selection, mutation and drift all act on the same time scale of generations.
- Finite offspring variance. The model is Wright-Fisher, Moran or another exchangeable model in which no individual has a large share of the next generation. Then only the mean and variance of the change matter in the limit.
- Questions on long time scales. Fixation probabilities, mean times to absorption, sojourn times and stationary densities. The diffusion does not describe the first few generations of a single copy under strong selection; a branching process does that better.
The template
Write for the frequency of , with fitnesses , and for , and .
DIFFUSION-APPROXIMATION(chain, question)- 1
compute M(x) = E[Δx | x] and V(x) = Var(Δx | x) for one generation, to first order in s and 1/N - 2
measure time in units of 2N generations, so the coefficients 2N M(x) and x(1 - x)/2 stay of order one as N grows with Ns fixed - 3
write the backward equation (V/2) f'' + M f' = -g for the question, with its boundary values at 0 and 1 - 4
solve it with the scale density ψ(y) = exp(- ∫_0^y 2M/V): the fixation probability is u(p) = ∫_0^p ψ / ∫_0^1 ψ - 5
for mean times and sojourn densities, integrate the Green function G(p, y) of the equation over y - 6
check the result against the exact chain for a small N
Line L1. For the Wright-Fisher chain, given , the next frequency is a binomial frequency with mean (the frequency after selection) and variance . To first order,
Line L2. In units of generations the generator is
With time in units of or generations, the factor becomes or . With Kimura's fitnesses , , , the drift is in units of generations, and the scaled selection coefficient is in the formulas.
Lines L3 and L4. A quantity that depends only on where the path ends satisfies . For fixation the boundary values are and . Writing the equation as shows that , which gives the formula of line L4.
Line L5. The mean time to absorption, in generations, solves with . With ,
is the mean number of generations that the frequency spends in before absorption.
Line L6. The implementation solves the exact Wright-Fisher chain by Gaussian elimination for and compares it with the diffusion, in a regime where the error is small and in one where it is large.
Classic examples
Neutral fixation and absorption time. With , , so , which is also exact for the chain. The Green function is for and for , and the integral is
| start | exact chain | diffusion | |
|---|---|---|---|
| 20 | 26.229 | 27.726 | |
| 100 | 136.602 | 138.629 | |
| 20 | one copy | 7.231 | 7.941 |
| 100 | one copy | 10.537 | 11.200 |
The relative error falls from about 6 percent to 1.5 percent as grows from 20 to 100.
Fixation with genic selection. With and Kimura's form (), and . This is the Kimura fixation probability. For and , one new copy fixes with probability in the diffusion and in the exact chain, an error of percent.
Dominance. With general , has no closed integral, but a numerical integral is easy. For , and one copy, the diffusion gives for a recessive allele (), against in the chain, and for a dominant one (), against . A new recessive allele is almost invisible to selection while it is rare, so it fixes nearly as rarely as a neutral one would at this (), while the dominant allele does much better.
Sojourn times and the frequency spectrum. For a new neutral mutant, , the Green function for is . So a new mutation spends on average generations at frequencies in . With new mutations arriving at rate per generation, the expected number of sites at frequency is , the continuous form of the neutral site frequency spectrum.
The stationary density with mutation. With mutation from to at rate and back at rate per generation, . The forward equation has the stationary density , which is
a beta density (Ewens 2004, Section 4.5). For it is U-shaped (drift wins and most loci are near loss or fixation); for it is flat; for larger values it peaks near .
Variations
- Other population models. The Moran model of haploid individuals has the same limit with time in units of steps, which is generations. A Cannings model with offspring variance uses . In all cases one can write in place of in , with the effective population size.
- The forward equation. The density of the frequency solves . Kimura (1955) solved it for neutral drift as a series of eigenfunctions; the eigenvalues (in units of generations) match the eigenvalues of the discrete chain to first order. For constant coefficients the forward equation is the heat equation.
- Many alleles. For alleles the frequencies move on a simplex, with covariance between different alleles.
- Stochastic differential equation. The frequency solves (time in generations), a stochastic differential equation. The Euler-Maruyama method simulates it, with care at the boundaries.
- Changing population size. With , the variance term carries , and time can be rescaled so that it becomes constant.
Pitfalls
- The time unit. The generator belongs to time in units of generations. Per generation the diffusion term is . Mixing units gives answers that are off by a factor 2 or 4.
- The definition of s. Kimura's genic form gives in the exponent; the form gives . Check the fitnesses before you use a formula from a paper.
- Strong selection. The diffusion keeps only first order terms in . For and Kimura's , it gives for one copy, but the exact chain gives : 12 percent too high. Use the exact chain, or a branching process for a rare allele, when is not small.
- Small populations. For the neutral absorption time from is 6 percent too high. The error is of order .
- Heavy-tailed offspring numbers. If one parent can have a fraction of the next generation that does not vanish as grows, the limit is not this diffusion, and the genealogy is a coalescent with multiple mergers.
- Numerical work at the boundaries. vanishes at 0 and 1, so explicit schemes can step outside . Keep the frequency in range, or work with the backward equation, which has smooth solutions here.
Code
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
# Part of https://algorithm.tamnd.com/wright-fisher-diffusion/. The authors are listed in prov/ET1T47.jsonl.
"""The diffusion approximation of the Wright-Fisher model, and the exact
chain to compare it with.
A diploid population of N individuals (2N copies). The genotypes AA, Aa and
aa have fitnesses 1 + s, 1 + h s and 1. Kimura's genic form 1 + 2 s_K,
1 + s_K, 1 is s = 2 s_K, h = 1/2.
Per generation, the change of the frequency x of A has, to first order in s
and 1/N, the mean M(x) = s x (1 - x) (h + (1 - 2h) x) and the variance
V(x) = x (1 - x) / (2N). Time is in generations in this module unless a
function says otherwise; the generator in units of 2N generations is
(1/2) x (1 - x) d^2/dx^2 + 2N M(x) d/dx.
"""
from __future__ import annotations
import math
from typing import List, Tuple
def moments(x: float, N: int, s: float = 0.0, h: float = 0.5) -> Tuple[float, float]:
"""(M(x), V(x)): the mean and variance of the change of x per generation."""
m = s * x * (1 - x) * (h + (1 - 2 * h) * x) # @line L1
v = x * (1 - x) / (2 * N) # @line L1
return m, v
def generator_coefficients(x: float, N: int, s: float = 0.0, h: float = 0.5) -> Tuple[float, float]:
"""The drift and half the variance in units of 2N generations:
(2N M(x), x (1 - x) / 2). They stay of order one when N s is fixed."""
m, v = moments(x, N, s, h)
return 2 * N * m, 2 * N * v / 2 # @line L2
def scale_density(y: float, N: int, s: float = 0.0, h: float = 0.5) -> float:
"""psi(y) = exp(-integral from 0 to y of 2 M / V) = exp(-4 N s (h y + (1 - 2h) y^2 / 2))."""
return math.exp(-4 * N * s * (h * y + (1 - 2 * h) * y * y / 2)) # @line L4
def _grid(n: int) -> List[float]:
return [i / n for i in range(n + 1)]
def _cumulative(f: List[float], n: int) -> List[float]:
"""Trapezoid integrals of f on [0, i/n], i = 0..n."""
out = [0.0]
for i in range(n):
out.append(out[-1] + (f[i] + f[i + 1]) / (2 * n))
return out
def fixation_probability(p: float, N: int, s: float = 0.0, h: float = 0.5, n: int = 4000) -> float:
"""u(p) solving (V/2) u'' + M u' = 0 with u(0) = 0 and u(1) = 1, so
u(p) = int_0^p psi / int_0^1 psi, by the trapezoid rule with n cells
(and Simpson's rule on the last partial cell)."""
if not 0.0 <= p <= 1.0:
raise ValueError("need 0 <= p <= 1")
# Boundary values u(0) = 0 and u(1) = 1 of the backward equation. # @line L3
if s == 0:
return p # @line L3
xs = _grid(n)
psi = [scale_density(x, N, s, h) for x in xs]
total = _cumulative(psi, n)[-1] # @line L4
k = int(p * n)
part = _cumulative(psi[: k + 1], k)[-1] * (k / n) if k > 0 else 0.0
a = k / n
mid = scale_density((a + p) / 2, N, s, h)
part += (p - a) / 6 * (scale_density(a, N, s, h) + 4 * mid + scale_density(p, N, s, h))
return part / total # @line L4
def kimura_genic(p: float, N: int, s_k: float) -> float:
"""Kimura's formula (1 - exp(-4 N s_K p)) / (1 - exp(-4 N s_K)) for the
fitnesses 1 + 2 s_K, 1 + s_K, 1; p when s_K = 0."""
if s_k == 0:
return p
return -math.expm1(-4 * N * s_k * p) / -math.expm1(-4 * N * s_k)
def absorption_time(p: float, N: int, s: float = 0.0, h: float = 0.5, n: int = 4000) -> float:
"""The mean time to loss or fixation, in generations:
t(p) = int_0^1 G(p, y) dy with the Green function
G(p, y) = 2 (1 - u(p)) S(y) / (V(y) psi(y)) for y <= p,
G(p, y) = 2 u(p) (S(1) - S(y)) / (V(y) psi(y)) for y > p,
where S(y) = int_0^y psi. Midpoint rule on n cells."""
if p <= 0.0 or p >= 1.0:
return 0.0
xs = _grid(n)
psi = [scale_density(x, N, s, h) for x in xs]
S = _cumulative(psi, n)
u = fixation_probability(p, N, s, h, n)
total = 0.0
for i in range(n):
y = (i + 0.5) / n
Sy = (S[i] + S[i + 1]) / 2
_, v = moments(y, N, s, h)
ps = scale_density(y, N, s, h)
if y <= p:
g = 2 * (1 - u) * Sy / (v * ps) # @line L5
else:
g = 2 * u * (S[n] - Sy) / (v * ps) # @line L5
total += g / n
return total # @line L5
def neutral_absorption_time(p: float, N: int) -> float:
"""-4N (p ln p + q ln q) generations."""
q = 1 - p
return -4 * N * ((p * math.log(p) if p > 0 else 0.0) + (q * math.log(q) if q > 0 else 0.0))
def exact_chain(two_n: int, s: float = 0.0, h: float = 0.5) -> Tuple[List[float], List[float]]:
"""Fixation probabilities and mean absorption times (generations) of the
discrete Wright-Fisher chain with 2N copies, for each start 0..2N, by
Gaussian elimination on (I - Q) [u t] = [r 1]."""
size = two_n - 1
rows = []
for i in range(1, two_n):
x = i / two_n
q = 1 - x
w_bar = x * x * (1 + s) + 2 * x * q * (1 + h * s) + q * q
ps = x * (x * (1 + s) + q * (1 + h * s)) / w_bar
pr = [math.comb(two_n, j) * ps ** j * (1 - ps) ** (two_n - j) for j in range(two_n + 1)]
row = [(1.0 if i == j else 0.0) - pr[j] for j in range(1, two_n)]
rows.append(row + [pr[two_n], 1.0]) # @line L6
for c in range(size):
piv = max(range(c, size), key=lambda r: abs(rows[r][c]))
rows[c], rows[piv] = rows[piv], rows[c]
for r in range(size):
if r != c and rows[r][c] != 0.0:
f = rows[r][c] / rows[c][c]
for k in range(c, size + 2):
rows[r][k] -= f * rows[c][k]
u = [0.0] + [rows[r][size] / rows[r][r] for r in range(size)] + [1.0]
t = [0.0] + [rows[r][size + 1] / rows[r][r] for r in range(size)] + [0.0]
return u, t # @line L6
test_wright_fisher_diffusion.py 87 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wright-fisher-diffusion/. The authors are listed in prov/ET1T47.jsonl.
import math
from wright_fisher_diffusion import (
absorption_time,
exact_chain,
fixation_probability,
generator_coefficients,
kimura_genic,
moments,
neutral_absorption_time,
scale_density,
)
def test_moments_and_generator():
m, v = moments(0.3, 50, 0.02, 0.5)
assert abs(m - 0.01 * 0.3 * 0.7) < 1e-15
assert abs(v - 0.21 / 100) < 1e-15
a, b = generator_coefficients(0.3, 50, 0.02, 0.5)
assert abs(a - 100 * m) < 1e-12 and abs(b - 0.105) < 1e-12
assert scale_density(0.0, 50, 0.1, 0.3) == 1.0
def test_numeric_integral_matches_kimura_formula():
for N, s_k in ((10, 0.05), (100, 0.01), (100, -0.01), (20, 0.2), (500, 0.001)):
for p in (1 / (2 * N), 0.1, 0.5, 0.9):
assert abs(fixation_probability(p, N, 2 * s_k, 0.5) - kimura_genic(p, N, s_k)) < 1e-9
def test_check_value_and_limits():
assert abs(kimura_genic(1 / 200, 100, 0.01) - 0.020171) < 5e-7
assert kimura_genic(0.3, 100, 0.0) == 0.3
assert fixation_probability(0.3, 100, 0.0) == 0.3
# Small s gives p; large positive N s gives about 2 s for one copy.
assert abs(kimura_genic(0.01, 50, 1e-9) - 0.01) < 1e-8
assert abs(kimura_genic(1 / 20000, 10000, 0.01) / (1 - math.exp(-0.02)) - 1) < 1e-12
def test_neutral_time_green_function():
for N, p in ((10, 0.5), (50, 0.01), (50, 0.3)):
assert abs(absorption_time(p, N) / neutral_absorption_time(p, N) - 1) < 1e-4
def test_diffusion_close_to_chain_when_s_small():
# N = 50 and s_K = 0.01 (N s_K = 0.5): the relative error is under 1 percent.
u, _ = exact_chain(100, 0.02, 0.5)
assert abs(u[1] - 0.022793) < 5e-7
assert abs(kimura_genic(0.01, 50, 0.01) / u[1] - 1) < 0.01
# Recessive (h = 0) and dominant (h = 1) alleles, s = 0.1, N = 50.
for h, tol in ((0.0, 0.02), (1.0, 0.05)):
u, _ = exact_chain(100, 0.1, h)
assert abs(fixation_probability(0.01, 50, 0.1, h) / u[1] - 1) < tol
# Neutral fixation is exact in both: u(p) = p.
u, _ = exact_chain(20)
assert all(abs(u[i] - i / 20) < 1e-12 for i in range(21))
def test_diffusion_fails_when_s_large():
# N = 10 and s_K = 0.5: the diffusion is about 12 percent too high.
u, _ = exact_chain(20, 1.0, 0.5)
assert abs(u[1] - 0.56423) < 5e-6
err = kimura_genic(0.05, 10, 0.5) / u[1] - 1
assert 0.10 < err < 0.14
def test_absorption_time_against_chain():
u, t = exact_chain(20)
assert abs(t[10] - 26.229) < 5e-4
# The diffusion is about 6 percent too high at 2N = 20 and 1.5 percent at 2N = 100.
assert 0.04 < neutral_absorption_time(0.5, 10) / t[10] - 1 < 0.08
u, t = exact_chain(100)
assert 0.005 < neutral_absorption_time(0.5, 50) / t[50] - 1 < 0.025
u, t = exact_chain(100, 0.04, 0.5)
assert abs(absorption_time(0.01, 50, 0.04, 0.5) / t[1] - 1) < 0.06
def test_invalid():
try:
fixation_probability(1.5, 10, 0.1)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
assert absorption_time(0.0, 10) == 0.0
Exercises
- Derive and for the fitnesses , and , and show that when .
- Compute the neutral Green function and integrate it to get . Show that generations.
- Expand Kimura's formula for small and show that .
- Find the stationary density for and for , and say which one is U-shaped.
- Show that the Moran model with haploid individuals has per generation, and find its effective size on the Wright-Fisher scale.
References
- Motoo Kimura, On the probability of fixation of mutant genes in a population, Genetics 47(6), 1962, pp. 713-719 (the backward equation for the fixation probability and its solution with the scale function)
- Kimura 1955, the solution of the forward equation for neutral drift
- Kimura 1964, a survey of the diffusion method for gene frequencies
- Warren J. Ewens, Mathematical Population Genetics I, Theoretical Introduction, 2nd edition, Springer, 2004, Section 4.2 (the Kolmogorov equations, p. 137), Section 4.3 (fixation probabilities, p. 139), Section 4.4 (absorption time, p. 140), Section 4.5 (the stationary distribution, p. 145) and Section 5.7 (diffusion approximations and boundary conditions, p. 176)
Where this leads
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ET1T47 Edit this page History Report an error Markdown