Modelintro
Wright-Fisher model
Also called Wright-Fisher process.
A population of N diploids (2N gene copies) in discrete generations: each new copy picks a parent copy uniformly at random, so the allele count is binomial each generation.
The Wright-Fisher model is the standard model of a finite population in population genetics. A population of diploid individuals carries copies of a gene, generations do not overlap, and each copy of the next generation is a copy of a parent copy chosen uniformly at random. So the number of copies of an allele is a Markov chain whose steps are binomial draws. It is the base of the theory of genetic drift, of the diffusion approximation and of the Kingman coalescent.
The machine
The state. One locus with two alleles, and . The state is , the number of copies of in generation , and is the allele frequency. Time is in generations. For a haploid population of copies, replace by everywhere on this page.
The step without selection. Each of the copies of generation picks a parent copy among the copies of generation , uniformly and independently of the other copies. So, given ,
The states 0 (loss of ) and (fixation of ) are absorbing; all other states are transient.
The step with selection. Give the genotypes , and the fitnesses , and . Selection acts first, as in an infinite population, and then the copies are drawn with the frequency after selection. With and the mean fitness ,
Kimura's genic form, with fitnesses , and , is the case , . Mutation enters the same way: change by the mutation step before the draw.
A simulation.
WRIGHT-FISHER(i0, 2N, T, s, h)- 1
X_0 ← i0 - 2
for t ← 0 to T - 1 do - 3
p ← X_t / (2N); q ← 1 - p - 4
p' ← p (p (1 + s) + q (1 + h s)) / (p² (1 + s) + 2 p q (1 + h s) + q²) - 5
X_{t+1} ← a draw from Binomial(2N, p') - 6
return X_0, ..., X_T
Each generation costs one binomial draw, which takes expected time with a good sampler, so generations take time. The implementation stops early when reaches 0 or . It also builds the exact transition matrix and solves for the absorption probabilities and times; the tests compare the simulation with these exact values for .
A trace. With seed 7, , no selection and , the implementation gives : the allele is lost in generation 5. From 5 copies the exact chance of loss is .
What it counts
- and , the count and frequency of an allele in each generation.
- The probability that an allele fixes or is lost, and the time until one of these happens.
- The expected heterozygosity , the chance that two copies drawn with replacement carry different alleles.
- The genealogy of a sample of copies, by following parents back in time.
- With mutation, the number of alleles and their frequencies at equilibrium, as in the infinite alleles model.
Relation to other models
- Moran model. One birth and one death per step, so generations overlap. Many results agree after a change of time scale: genetic drift is twice as fast per generation in the Moran model, which has effective population size in Wright-Fisher units for copies.
- Cannings models. Wright-Fisher is the exchangeable model in which the offspring numbers of the copies are multinomial. Other offspring laws with variance per copy behave like a Wright-Fisher population of size copies (Ewens 2004, Section 3.3).
- Wright-Fisher diffusion. For large , with time in units of generations and fixed, tends to a diffusion with generator plus a selection drift. The Kimura fixation probability is a result of this limit.
- Kingman coalescent. Two copies have the same parent copy with probability . With time in units of generations, the genealogy of a sample tends to the Kingman coalescent.
- Galton-Watson process. While an allele is rare, the copies of it reproduce almost independently with Poisson offspring numbers of mean for a genic advantage , so its early fate is that of a branching process.
Known results in the model
Each result is for the neutral chain () unless it says otherwise, with time in generations.
The frequency is a martingale, and an allele fixes with probability equal to its frequency. , and .
Proof. The mean of is , so is a martingale. From each transient state the chain moves to 0 in one step with probability , so it is absorbed in finite time with probability 1, and the absorption time has a geometric tail. is bounded by , so the optional stopping theorem gives . Since , .
Heterozygosity decays at the rate . , where .
Proof. Given , has mean and variance . So and . Take expectations and use induction on .
For and the ratio is . The half-life of the heterozygosity is about generations, so drift removes variation in a time of order generations.
The variance of the frequency. , which tends to , the variance of a frequency that is 0 or 1 with chances and .
Proof. and, from the previous result, . Then .
The eigenvalues of the transition matrix. They are and for .
Proof. For the falling factorial moments are . With and , the matrix maps the polynomial to plus a polynomial of lower degree. So in the basis of falling factorials of degree , which spans all functions on , the matrix is triangular with diagonal .
The two eigenvalues equal to 1 belong to the two absorbing states. The largest other one, , is the rate of the heterozygosity result above, and it sets the time scale of absorption.
The time to absorption. The exact mean comes from the linear system on the transient states. For it is generations from and from . The diffusion approximation gives generations, here and : about 6 and 10 percent too high at this small size.
The genealogy. Two copies of one generation have the same parent copy with probability , so the number of generations back to their common ancestor is geometric with mean . A sample of copies loses a lineage with probability per generation. This gives the Kingman coalescent in units of generations.
With selection. There is no closed form for the fixation probability of the discrete chain. The implementation solves the linear system exactly. For () and fitnesses , and , one new copy fixes with probability , against without selection and by Kimura's diffusion formula.
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
# 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)
wright_fisher_model.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wright-fisher-model/. The authors are listed in prov/ZKD5QR.jsonl.
"""The Wright-Fisher model of one biallelic locus: a simulator and the exact
Markov chain.
The population has N diploid individuals, so 2N gene copies, in discrete
generations. X_t is the number of copies of allele A in generation t. Each
copy of generation t + 1 picks a parent copy independently. Without
selection the parent is uniform, so X_(t+1) given X_t = i is
Binomial(2N, i / (2N)). With selection the genotypes AA, Aa and aa have
fitnesses 1 + s, 1 + h s and 1, and the copies are drawn with the frequency
after selection.
The functions take the number of copies two_n = 2N. With Fraction values of
s and h (or s = 0) and exact=True, the chain is computed in exact rational
arithmetic.
"""
from __future__ import annotations
import math
from fractions import Fraction
from typing import Dict, List, Sequence
from biostoch import binom_pmf, binomial
def selected_frequency(p, s=0, h=Fraction(1, 2)):
"""The frequency of A after selection with fitnesses 1 + s, 1 + h s, 1
for AA, Aa, aa, given the frequency p before selection."""
q = 1 - p
w_A = p * (1 + s) + q * (1 + h * s) # mean fitness of a copy of A
w_bar = p * p * (1 + s) + 2 * p * q * (1 + h * s) + q * q
return p * w_A / w_bar
def simulate(rng, i0: int, two_n: int, generations: int, s: float = 0.0,
h: float = 0.5) -> List[int]:
"""The counts X_0, ..., X_T of allele A for T = generations steps.
Each step makes one draw from Binomial(2N, p') by biostoch.binomial, where
p' is the frequency after selection. The run stops early when the
allele is lost or fixed, because the chain cannot leave these states."""
if not 0 <= i0 <= two_n or two_n < 1:
raise ValueError("need 0 <= i0 <= 2N and 2N >= 1")
xs = [i0] # @line L1
x = i0
for _ in range(generations): # @line L2
if x == 0 or x == two_n:
break
p = x / two_n # @line L3
p_sel = selected_frequency(p, s, h) # @line L4
x = binomial(rng, two_n, min(1.0, max(0.0, p_sel))) # @line L5
xs.append(x)
return xs # @line L6
def run_to_absorption(rng, i0: int, two_n: int, s: float = 0.0, h: float = 0.5,
max_generations: int = 10 ** 6):
"""Run until loss or fixation. Returns (fixed, generations)."""
x = i0
t = 0
while 0 < x < two_n:
if t >= max_generations:
raise RuntimeError("no absorption within max_generations")
x = binomial(rng, two_n, min(1.0, max(0.0, selected_frequency(x / two_n, s, h))))
t += 1
return x == two_n, t
def transition_matrix(two_n: int, s=0, h=Fraction(1, 2), exact: bool = False):
"""The (2N + 1) by (2N + 1) matrix P[i][j] = Pr(X_(t+1) = j | X_t = i)."""
rows = []
for i in range(two_n + 1):
if exact:
p = selected_frequency(Fraction(i, two_n), Fraction(s), Fraction(h))
q = 1 - p
rows.append([math.comb(two_n, j) * p ** j * q ** (two_n - j) for j in range(two_n + 1)])
else:
p = selected_frequency(i / two_n, s, h)
rows.append([binom_pmf(j, two_n, min(1.0, max(0.0, p))) for j in range(two_n + 1)])
return rows
def _solve(a: List[list], b: List[list]) -> List[list]:
"""Solve a x = b by Gaussian elimination; b has one column per right side.
Works for floats (partial pivoting) and for Fractions (exact)."""
n = len(a)
m = [row[:] + rhs[:] for row, rhs in zip(a, b)]
k = len(b[0])
for col in range(n):
piv = max(range(col, n), key=lambda r: abs(m[r][col]))
if m[piv][col] == 0:
raise ZeroDivisionError("singular system")
m[col], m[piv] = m[piv], m[col]
for r in range(n):
if r != col and m[r][col] != 0:
f = m[r][col] / m[col][col]
for c in range(col, n + k):
m[r][c] -= f * m[col][c]
return [[m[r][n + c] / m[r][r] for c in range(k)] for r in range(n)]
def absorption(two_n: int, s=0, h=Fraction(1, 2), exact: bool = False) -> Dict[str, list]:
"""Exact fixation probabilities and the first two moments of the time to
absorption (in generations), for each start i = 0, ..., 2N.
Solves (I - Q) u = r, (I - Q) t = 1 and (I - Q) m2 = 1 + 2 Q t, where Q is
the transition matrix on the interior states 1, ..., 2N - 1 and r is the
column of the jumps to 2N."""
P = transition_matrix(two_n, s, h, exact)
zero, one = (Fraction(0), Fraction(1)) if exact else (0.0, 1.0)
inner = range(1, two_n)
if two_n == 1:
return {"fix": [zero, one], "time": [zero, zero], "time2": [zero, zero]}
a = [[(one if i == j else zero) - P[i][j] for j in inner] for i in inner]
rhs = [[P[i][two_n], one] for i in inner]
sol = _solve(a, rhs)
u = [row[0] for row in sol]
t = [row[1] for row in sol]
rhs2 = [[one + 2 * sum(P[i][j] * t[j - 1] for j in inner)] for i in inner]
m2 = [row[0] for row in _solve(a, rhs2)]
return {"fix": [zero] + u + [one], "time": [zero] + t + [zero], "time2": [zero] + m2 + [zero]}
def propagate(dist: Sequence, P: List[list], steps: int) -> list:
"""The law of X_t after `steps` generations from the law dist of X_0."""
d = list(dist)
n = len(d)
for _ in range(steps):
d = [sum(d[i] * P[i][j] for i in range(n)) for j in range(n)]
return d
def heterozygosity_decay(N: int, t: int) -> float:
"""E[H_t] / H_0 = (1 - 1/(2N))^t under neutral drift, N diploids."""
return (1.0 - 1.0 / (2 * N)) ** t
test_wright_fisher_model.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wright-fisher-model/. The authors are listed in prov/ZKD5QR.jsonl.
import math
import random
from fractions import Fraction
from biostoch import binom_pmf, chi2_sf
from wright_fisher_model import (
absorption,
heterozygosity_decay,
propagate,
run_to_absorption,
selected_frequency,
simulate,
transition_matrix,
)
def chi2_against(counts, probs, reps):
"""Pearson statistic with the cells of expected count < 5 pooled into one."""
stat, df = 0.0, -1
pool_o, pool_e = 0, 0.0
for k, p in enumerate(probs):
e = reps * p
if e < 5:
pool_o += counts.get(k, 0)
pool_e += e
else:
stat += (counts.get(k, 0) - e) ** 2 / e
df += 1
if pool_e > 0:
stat += (pool_o - pool_e) ** 2 / pool_e
df += 1
return stat, df
def test_one_step_is_binomial():
rng = random.Random(1931)
two_n, i, reps = 20, 7, 4000
for s, h in ((0.0, 0.5), (0.3, 0.25)):
counts = {}
for _ in range(reps):
x = simulate(rng, i, two_n, 1, s, h)[1]
counts[x] = counts.get(x, 0) + 1
p = selected_frequency(i / two_n, s, h)
probs = [binom_pmf(k, two_n, p) for k in range(two_n + 1)]
stat, df = chi2_against(counts, probs, reps)
assert chi2_sf(stat, df) > 0.001
def test_selected_frequency():
# Genic selection: fitnesses 1 + 2s', 1 + s', 1 gives p' = p (1 + s' + s' p) / (1 + 2 s' p).
sp = Fraction(1, 10)
p = Fraction(3, 10)
assert selected_frequency(p, 2 * sp, Fraction(1, 2)) == p * (1 + sp + sp * p) / (1 + 2 * sp * p)
assert selected_frequency(p, 0) == p
assert selected_frequency(Fraction(0), Fraction(1, 2)) == 0
assert selected_frequency(Fraction(1), Fraction(1, 2)) == 1
def test_rows_sum_to_one_and_martingale():
for two_n in (1, 2, 5, 10):
P = transition_matrix(two_n, exact=True)
for i, row in enumerate(P):
assert sum(row) == 1
assert sum(j * pj for j, pj in enumerate(row)) == i
def test_neutral_fixation_is_initial_frequency():
for two_n in (2, 6, 10):
res = absorption(two_n, exact=True)
assert res["fix"] == [Fraction(i, two_n) for i in range(two_n + 1)]
res = absorption(20)
for i in range(21):
assert abs(res["fix"][i] - i / 20) < 1e-12
def test_exact_moments_by_propagation():
# E[X_t] = X_0, E[H_t] = H_0 (1 - 1/(2N))^t and Var(p_t) = p0 q0 (1 - (1 - 1/(2N))^t).
two_n, i0, t = 10, 3, 6
P = transition_matrix(two_n, exact=True)
d = propagate([Fraction(int(k == i0)) for k in range(two_n + 1)], P, t)
p0 = Fraction(i0, two_n)
lam = 1 - Fraction(1, two_n)
mean_p = sum(Fraction(k, two_n) * dk for k, dk in enumerate(d))
het = sum(2 * Fraction(k, two_n) * (1 - Fraction(k, two_n)) * dk for k, dk in enumerate(d))
var_p = sum((Fraction(k, two_n) - p0) ** 2 * dk for k, dk in enumerate(d))
assert mean_p == p0
assert het == 2 * p0 * (1 - p0) * lam ** t
assert var_p == p0 * (1 - p0) * (1 - lam ** t)
def test_heterozygosity_check_value():
assert abs(heterozygosity_decay(50, 10) - 0.904382) < 5e-7
def test_simulated_fixation_against_exact_chain():
# N = 10 diploids (2N = 20), fitnesses 1 + 2s, 1 + s, 1 with s = 0.05, one copy.
rng = random.Random(1962)
two_n, s, reps = 20, 0.05, 6000
res = absorption(two_n, 2 * s, 0.5)
u = res["fix"][1]
assert abs(u - 0.10765) < 5e-6
fixed = sum(run_to_absorption(rng, 1, two_n, 2 * s, 0.5)[0] for _ in range(reps))
z = 4
assert abs(fixed / reps - u) <= z * math.sqrt(u * (1 - u) / reps)
def test_simulated_absorption_time_against_exact_chain():
rng = random.Random(2)
two_n, i0, reps = 20, 10, 3000
res = absorption(two_n)
mu = res["time"][i0]
var = res["time2"][i0] - mu * mu
assert abs(mu - 26.229) < 5e-4
total = sum(run_to_absorption(rng, i0, two_n)[1] for _ in range(reps))
z = 4
assert abs(total / reps - mu) <= z * math.sqrt(var / reps)
def test_edges():
rng = random.Random(0)
assert simulate(rng, 0, 10, 5) == [0]
assert simulate(rng, 10, 10, 5) == [10]
assert absorption(1, exact=True)["fix"] == [0, 1]
try:
simulate(rng, 11, 10, 1)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
References
- Wright 1931, pp. 97-159 (random sampling of the gametes in a population of size N, and the loss of heterozygosity at the rate 1/(2N) per generation)
- Fisher 1930, the random survival of genes in a finite population
- Warren J. Ewens, Mathematical Population Genetics I, Theoretical Introduction, 2nd edition, Springer, 2004, Section 3.2 (the Wright-Fisher model with two alleles, p. 92), Section 3.3 (Cannings models, p. 99) and Section 4.4 (the absorption time in the diffusion approximation, p. 140)
- John H. Gillespie, Population Genetics, A Concise Guide, 2nd edition, Johns Hopkins University Press, 2004, Section 2.2 (the decay of heterozygosity) and Section 2.6 (the coalescent)
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 | W4 complete |
|
Tag ZKD5QR Edit this page History Report an error Markdown