Algorithm Search⌘K

Algorithmcore

Hardy-Weinberg exact test

Also called HWE exact test.

Test departure from Hardy-Weinberg proportions by the exact probability of heterozygote counts given allele counts, computed by a recurrence.

Time
Θ(m) worst · average · best
Space
Θ(m) extra
Where
m = the number of copies of the minor allele (m <= n); n = the number of individuals
Properties
deterministicexactofflineiterative
Origin
Janis E. Wigginton, David J. Cutler, Gonçalo R. Abecasis, 2005

The Hardy-Weinberg exact test asks whether the genotype counts at one biallelic site fit the proportions p2p^2, 2pq2pq and q2q^2 of the Hardy-Weinberg principle. It conditions on the allele counts, so the unknown allele frequency drops out, and it computes the exact null probability of every possible number of heterozygotes. The algorithm of Wigginton, Cutler and Abecasis gets all these probabilities from one start value by a ratio of neighbouring terms, in time linear in the minor allele count. Unlike the chi-square test, it stays valid for rare alleles and small samples.

In plain words

Take the gene copies of all sampled people, put them in one heap, and deal them out again in pairs at random. Under Hardy-Weinberg proportions, the real sample looks like one such random deal. So count, over all ways to deal the heap, how often each number of mixed pairs (heterozygotes) comes up. If the observed number of heterozygotes is one of the rare outcomes, the sample does not fit. The exact test adds up the chances of all outcomes that are as rare as the observed one or rarer. The trick of the algorithm is that the chance of one count follows from the chance of the next count by a short formula, so there is no need to count deals one by one.

The problem

Input. Genotype counts nAAn_{AA}, nAan_{Aa} and naan_{aa} of n=nAA+nAa+naa≥1n = n_{AA} + n_{Aa} + n_{aa} \ge 1 diploid individuals at a biallelic site.

Null hypothesis. The genotypes are independent draws with probabilities p2p^2, 2pq2pq and q2q^2 for some unknown pp.

Output. The p-value of the observed heterozygote count hobs=nAah_{\text{obs}} = n_{Aa} against its exact null law given the allele counts nA=2nAA+nAan_A = 2n_{AA} + n_{Aa} and na=2n−nAn_a = 2n - n_A.

Let m=min⁡(nA,na)m = \min(n_A, n_a) be the minor allele count. For a possible heterozygote count hh (with 0≤h≤m0 \le h \le m and h≡m(mod2)h \equiv m \pmod 2) the minor homozygotes number r=(m−h)/2r = (m - h)/2 and the common homozygotes c=n−h−rc = n - h - r. Under the null, given nAn_A (Levene 1949),

P(h)=n!  nA!  na!  2hr!  h!  c!  (2n)!.P(h) = \frac{n!\; n_A!\; n_a!\; 2^h}{r!\; h!\; c!\; (2n)!}.

The factor pnAqnap^{n_A} q^{n_a} of the multinomial law cancels against the binomial law of nAn_A, so PP does not depend on pp: the allele count is a sufficient statistic for pp, and conditioning on it gives a similar test, as in the Fisher exact test. Equivalently, PP is the law of the number of mixed pairs when the 2n2n copies are paired at random. The two-sided p-value is

π(hobs)=∑h: P(h)≤P(hobs)P(h).\pi(h_{\text{obs}}) = \sum_{h :\, P(h) \le P(h_{\text{obs}})} P(h).

The algorithm

Moving from hh to h−2h - 2 turns two heterozygotes into one homozygote of each kind, so most factors of PP cancel in the ratio:

P(h−2)P(h)=h(h−1)4 (r+1)(c+1),P(h+2)P(h)=4 r c(h+1)(h+2),\frac{P(h-2)}{P(h)} = \frac{h(h-1)}{4\,(r+1)(c+1)}, \qquad \frac{P(h+2)}{P(h)} = \frac{4\,r\,c}{(h+1)(h+2)},

with rr and cc taken at hh. The algorithm sets an unnormalized weight 1 at a value near the mode and walks down and up with these ratios.

  1. HWE-EXACT(n_AA, n_Aa, n_aa)
  2. 1n ← n_AA + n_Aa + n_aa; m ← min(2·n_AA + n_Aa, 2·n_aa + n_Aa)
  3. 2h0 ← floor(m(2n - m) / (2n)); if h0 and m differ in parity then h0 ← h0 + 1
  4. 3w[h0] ← 1
  5. 4for h ← h0, h0 - 2, ... while h ≥ 2 do w[h - 2] ← w[h] · h(h - 1) / (4 (r + 1)(c + 1))
  6. 5for h ← h0, h0 + 2, ... while h ≤ m - 2 do w[h + 2] ← w[h] · 4 r c / ((h + 1)(h + 2))
  7. 6S ← sum of all w[h]; P[h] ← w[h] / S for each h
  8. 7return the sum of P[h] over all h with P[h] ≤ P[n_Aa]

In lines L4 and L5, r=(m−h)/2r = (m - h)/2 and c=n−h−rc = n - h - r are the homozygote counts at the current hh. Line L2 starts at 2np^q^2n \hat p \hat q, the value where the ratio crosses 1. The start does not matter for the result, but there the weights are at most about 1, so floats do not overflow.

Example

Ten individuals. Counts nAA=2n_{AA} = 2, nAa=2n_{Aa} = 2 and naa=6n_{aa} = 6 give n=10n = 10, nA=6n_A = 6, na=14n_a = 14 and m=6m = 6 (a check value of the area). Line L2 gives ⌊6⋅14/20⌋=4\lfloor 6 \cdot 14 / 20 \rfloor = 4, which has the parity of mm, so h0=4h_0 = 4 with r=1r = 1 and c=5c = 5.

step hh rr cc ratio ww
L3 4 1 5 11
L4 4 to 2 4⋅3/(4⋅2⋅6)=1/44 \cdot 3 / (4 \cdot 2 \cdot 6) = 1/4 w[2]=1/4w[2] = 1/4
L4 2 to 0 2 6 2⋅1/(4⋅3⋅7)=1/422 \cdot 1 / (4 \cdot 3 \cdot 7) = 1/42 w[0]=1/168w[0] = 1/168
L5 4 to 6 1 5 4⋅1⋅5/(5⋅6)=2/34 \cdot 1 \cdot 5 / (5 \cdot 6) = 2/3 w[6]=2/3w[6] = 2/3

The sum is 1/168+1/4+1+2/3=323/1681/168 + 1/4 + 1 + 2/3 = 323/168, so line L6 gives P(0)=1/323P(0) = 1/323, P(2)=42/323P(2) = 42/323, P(4)=168/323P(4) = 168/323 and P(6)=112/323P(6) = 112/323. The observed h=2h = 2 has probability 42/32342/323. Only h=0h = 0 and h=2h = 2 have probability at most 42/32342/323, so the p-value is 43/323≈0.1331343/323 \approx 0.13313. The closed form agrees: P(2)=10! 6! 14! 22/(2! 2! 6! 20!)=42/323P(2) = 10!\, 6!\, 14!\, 2^2 / (2!\, 2!\, 6!\, 20!) = 42/323.

One hundred individuals. Counts 30, 40 and 30 give nA=na=100n_A = n_a = 100, m=100m = 100 and h0=50h_0 = 50, the mode, with P(50)≈0.15858P(50) \approx 0.15858. The observed P(40)≈0.019740P(40) \approx 0.019740. The values h≤40h \le 40 have probabilities at most this, and so do the values h≥62h \ge 62 (P(62)≈0.010207P(62) \approx 0.010207), but h=60h = 60 does not (P(60)≈0.024127P(60) \approx 0.024127). The p-value is Pr⁡(H≤40)+Pr⁡(H≥62)≈0.031537+0.015319=0.046855\Pr(H \le 40) + \Pr(H \ge 62) \approx 0.031537 + 0.015319 = 0.046855, which rounds to the check value 0.04686. The chi-squared goodness-of-fit test on the same data has expected counts 25, 50 and 25, statistic 4.04.0 on 1 degree of freedom and p-value 0.04550.0455. Here the two tests agree; they part ways for rare alleles (see Pitfalls).

Correctness

The algorithm computes P(h)/P(h0)P(h)/P(h_0) for each possible hh by induction along the walk, because each step multiplies by the exact ratio P(h∓2)/P(h)P(h \mp 2)/P(h), and the walks from h0h_0 in steps of 2 reach exactly the values from the least possible one (0 or 1) up to mm. Every ratio is positive and finite there: h(h−1)>0h(h-1) > 0 for h≥2h \ge 2, and r,c≥1r, c \ge 1 for h≤m−2h \le m - 2 because m≤nm \le n. Dividing by the sum gives PP. The p-value is valid: for every α\alpha, Pr⁡(π(H)≤α)≤α\Pr(\pi(H) \le \alpha) \le \alpha under the null, because the set of outcomes with π≤α\pi \le \alpha is contained in a set {h:P(h)≤P(h∗)}\{h : P(h) \le P(h^*)\} whose total probability is π(h∗)≤α\pi(h^*) \le \alpha. The full proofs, with the derivation of Levene's law and the unimodality of PP, are below.

Proof: The Hardy-Weinberg exact test computes the null law of the heterozygote count and gives a valid p-valuefull

A sample of n≥1n \ge 1 diploid individuals at a biallelic locus has genotype counts nAAn_{AA}, nAan_{Aa} and naan_{aa}. Let nA=2nAA+nAan_A = 2n_{AA} + n_{Aa} and na=2n−nAn_a = 2n - n_A be the allele counts, and let m=min⁡(nA,na)m = \min(n_A, n_a) be the count of the minor allele. Write hh for a possible heterozygote count. Given the allele counts, the counts of the two homozygotes are fixed by hh: r(h)=(m−h)/2r(h) = (m - h)/2 minor homozygotes and c(h)=n−h−r(h)c(h) = n - h - r(h) common homozygotes. A value hh is possible when 0≤h≤m0 \le h \le m and h≡m(mod2)h \equiv m \pmod 2; then r(h)r(h) and c(h)c(h) are integers, r(h)≥0r(h) \ge 0, and c(h)=n−(m+h)/2≥n−m≥0c(h) = n - (m + h)/2 \ge n - m \ge 0 because m≤nm \le n.

1. The null law (Levene 1949)

Lemma 1. Suppose the nn genotypes are independent draws with probabilities p2p^2, 2pq2pq and q2q^2 (Hardy-Weinberg proportions). Then, given nAn_A, the probability of hh heterozygotes is

P(h)=n!  nA!  na!  2hr!  h!  c!  (2n)!with r,c the homozygote counts of h,P(h) = \frac{n!\; n_A!\; n_a!\; 2^h}{r!\; h!\; c!\; (2n)!} \quad\text{with } r, c \text{ the homozygote counts of } h,

taken over the possible values of hh, and it does not depend on pp.

Proof. Say that AA is the minor allele, so rr counts AAAA and cc counts aaaa; the other case is the same with the names swapped. The genotype counts are multinomial, so

Pr⁡(r,h,c)=n!r! h! c! (p2)r(2pq)h(q2)c=n! 2hr! h! c! pnAqna,\Pr(r, h, c) = \frac{n!}{r!\, h!\, c!}\, (p^2)^r (2pq)^h (q^2)^c = \frac{n!\, 2^h}{r!\, h!\, c!}\, p^{n_A} q^{n_a},

because 2r+h=nA2r + h = n_A and 2c+h=na2c + h = n_a. Each of the 2n2n copies is AA with probability pp, independently, so nA∼Binomial(2n,p)n_A \sim \text{Binomial}(2n, p) and Pr⁡(nA)=(2nnA)pnAqna\Pr(n_A) = \binom{2n}{n_A} p^{n_A} q^{n_a}. Dividing, the factor pnAqnap^{n_A} q^{n_a} cancels:

Pr⁡(h∣nA)=n! 2hr! h! c!⋅nA! na!(2n)!.\Pr(h \mid n_A) = \frac{n!\, 2^h}{r!\, h!\, c!} \cdot \frac{n_A!\, n_a!}{(2n)!}.

So nAn_A is a sufficient statistic for pp, and the conditional law is free of the nuisance parameter. □\square

The same law has a counting form, which the tests use as an independent check. Put the 2n2n copies in slots 0,…,2n−10, \ldots, 2n - 1, where individual ii holds slots 2i2i and 2i+12i + 1. Under the null, given nAn_A, every set of nAn_A slots for the AA copies is equally likely, so each of the (2nnA)\binom{2n}{n_A} placements has probability 1/(2nnA)1/\binom{2n}{n_A}. A placement with hh heterozygotes is fixed by choosing which individuals are AAAA, AaAa and aaaa, in n!/(r! h! c!)n!/(r!\,h!\,c!) ways, and which slot of each heterozygote holds the AA, in 2h2^h ways. This gives the same P(h)P(h).

2. The ratios of neighbouring terms

Lemma 2. For possible values hh and h−2h - 2,

P(h−2)P(h)=h(h−1)4 (r+1)(c+1),P(h+2)P(h)=4 r c(h+1)(h+2),\frac{P(h-2)}{P(h)} = \frac{h(h-1)}{4\,(r+1)(c+1)}, \qquad \frac{P(h+2)}{P(h)} = \frac{4\,r\,c}{(h+1)(h+2)},

where r=r(h)r = r(h) and c=c(h)c = c(h), and the second form holds when h+2h + 2 is possible.

Proof. Moving from hh to h−2h - 2 turns one heterozygote pair into one more homozygote of each kind: r(h−2)=r+1r(h - 2) = r + 1 and c(h−2)=c+1c(h - 2) = c + 1. In the ratio of the two closed forms the factors n! nA! na!/(2n)!n!\, n_A!\, n_a! / (2n)! cancel, and what is left is

2h−2(r+1)! (h−2)! (c+1)!⋅r! h! c!2h=h(h−1)4(r+1)(c+1).\frac{2^{h-2}}{(r+1)!\,(h-2)!\,(c+1)!} \cdot \frac{r!\, h!\, c!}{2^h} = \frac{h(h-1)}{4 (r+1)(c+1)}.

The second ratio is the same identity read from hh to h+2h + 2, where r(h+2)=r−1r(h + 2) = r - 1 and c(h+2)=c−1c(h + 2) = c - 1. □\square

All these ratios are positive on the possible values. For h≥2h \ge 2, h(h−1)>0h(h - 1) > 0. For h≤m−2h \le m - 2, r=(m−h)/2≥1r = (m - h)/2 \ge 1 and c=n−(m+h)/2≥n−m+1≥1c = n - (m + h)/2 \ge n - m + 1 \ge 1. So no weight is zero and no denominator is zero.

3. The algorithm returns PP

Lines L1 and L2 compute nn, mm and a start value h0h_0 with h0≡m(mod2)h_0 \equiv m \pmod 2 and 0≤h0≤m0 \le h_0 \le m: the floor of m(2n−m)/(2n)m(2n - m)/(2n) lies in [0,m][0, m], and it is raised by 1 only when its parity differs from that of mm, in which case it was below mm.

Claim. After lines L3 to L5, w[h]=P(h)/P(h0)w[h] = P(h)/P(h_0) for every possible hh, and ww has no other keys.

Proof. Line L3 sets w[h0]=1=P(h0)/P(h0)w[h_0] = 1 = P(h_0)/P(h_0). The loop of line L4 visits h=h0,h0−2,…h = h_0, h_0 - 2, \ldots while h≥2h \ge 2 and sets w[h−2]=w[h]⋅P(h−2)/P(h)w[h-2] = w[h] \cdot P(h-2)/P(h) by Lemma 2, so by induction on the number of steps w[h−2]=P(h−2)/P(h0)w[h - 2] = P(h - 2)/P(h_0). It stops at the least value with the parity of mm, which is 0 or 1, the least possible value. The loop of line L5 does the same upward with the second ratio of Lemma 2 and stops at h=mh = m, the largest possible value. Both loops move in steps of 2 from a value with the parity of mm, so they visit exactly the possible values. □\square

Line L6 divides by ∑hw[h]=∑hP(h)/P(h0)=1/P(h0)\sum_h w[h] = \sum_h P(h)/P(h_0) = 1/P(h_0), because PP is a probability law on the possible values. So the returned map is PP.

4. The p-value is valid

For an observed count hh, line L7 returns

π(h)=∑h′: P(h′)≤P(h)P(h′).\pi(h) = \sum_{h' :\, P(h') \le P(h)} P(h').

Theorem. Under the null hypothesis, for every α∈[0,1]\alpha \in [0, 1], Pr⁡(π(H)≤α∣nA)≤α\Pr(\pi(H) \le \alpha \mid n_A) \le \alpha. Hence also Pr⁡(π(H)≤α)≤α\Pr(\pi(H) \le \alpha) \le \alpha without the conditioning.

Proof. If P(h1)>P(h2)P(h_1) > P(h_2), then the set summed for π(h1)\pi(h_1) contains the set for π(h2)\pi(h_2) and also h1h_1, so π(h1)≥π(h2)+P(h1)>π(h2)\pi(h_1) \ge \pi(h_2) + P(h_1) > \pi(h_2). Let S={h:π(h)≤α}S = \{h : \pi(h) \le \alpha\}. If SS is empty there is nothing to prove. Otherwise pick h∗∈Sh^* \in S with the largest P(h∗)P(h^*). Every h∈Sh \in S has P(h)≤P(h∗)P(h) \le P(h^*), so S⊆{h:P(h)≤P(h∗)}S \subseteq \{h : P(h) \le P(h^*)\} and

Pr⁡(H∈S∣nA)≤∑h: P(h)≤P(h∗)P(h)=π(h∗)≤α.\Pr(H \in S \mid n_A) \le \sum_{h :\, P(h) \le P(h^*)} P(h) = \pi(h^*) \le \alpha.

The bound holds for every value of nAn_A, so it holds after averaging over nAn_A. □\square

The one-sided p-values Pr⁡(H≤h)\Pr(H \le h) and Pr⁡(H≥h)\Pr(H \ge h) are valid by the same argument with the order of hh in place of the order of P(h)P(h). They overlap in the term P(h)P(h), so their sum is 1+P(h)1 + P(h).

5. Where the start value comes from

By Lemma 2 the ratio P(h+2)/P(h)=4rc/((h+1)(h+2))P(h+2)/P(h) = 4 r c / ((h+1)(h+2)) decreases strictly in hh: the numerator decreases because rr and cc both drop by 1, and the denominator increases. So PP rises and then falls on the possible values; it is unimodal. Setting the continuous form of the ratio to 1, (m−h)(2n−m−h)=h2(m - h)(2n - m - h) = h^2, gives h=m(2n−m)/(2n)h = m(2n - m)/(2n), the expected heterozygote count 2np^q^2n \hat p \hat q in large samples. Starting there keeps the floating weights near 1 at the mode and below 1 elsewhere, so they do not overflow; far tails may underflow to 0, which changes the p-value by less than the rounding error. The exact form of the start value does not matter for correctness, which Section 3 proves for any possible h0h_0.

6. Rounding

With floats, each weight is a product of at most m/2m/2 ratios, each computed with a few roundings, so its relative error is O(mε)O(m \varepsilon) for the unit roundoff ε\varepsilon. Two values of hh can have equal true probabilities (for n=6n = 6 and nA=4n_A = 4, both h=2h = 2 and h=4h = 4 have probability 16/3316/33), and rounding can then put one of them on the wrong side of the comparison in line L7. The implementation compares with a relative tolerance of 10−910^{-9}; with exact=True it uses fractions, and the comparison is exact.

Complexity

  • Time. There are ⌊m/2⌋+1\lfloor m/2 \rfloor + 1 possible values of hh, and each costs O(1)O(1) arithmetic operations, so the time is Θ(m)\Theta(m) on a real RAM, and Θ(1)\Theta(1) when mm is bounded. Since m≤nm \le n, it is at most linear in the sample size. Evaluating the closed form for every hh would cost a factorial or a log-gamma per term; the recurrence avoids both.
  • Space. The array ww uses Θ(m)\Theta(m) words. Two passes (one to get SS and P(hobs)/P(h0)P(h_{\text{obs}})/P(h_0), one to sum the p-value) bring it to O(1)O(1) extra words.
  • Exact arithmetic. With fractions the numbers grow to O(nlog⁡n)O(n \log n) bits, so the cost per step is no longer constant. The implementation offers this mode for checking.
  • Many sites. A genome-wide scan of MM sites costs Θ(∑mi)\Theta(\sum m_i), which is cheap; studies also tabulate the law once per pair (n,m)(n, m).

Properties

  • Exact and conditional. The p-value uses the exact law, not a large-sample approximation, and it conditions on the allele counts, so it is valid for every pp.
  • Conservative. The law is discrete, so Pr⁡(π(H)≤α)\Pr(\pi(H) \le \alpha) is usually below α\alpha. In 2000 simulated null samples with n=50n = 50 and nA=40n_A = 40, the implementation rejected at α=0.05\alpha = 0.05 in 3.35 percent of them.
  • Two-sided by probability. Outcomes are ordered by their own probability, as in the Fisher exact test. Both a deficit and an excess of heterozygotes can give a small p-value.
  • One-sided versions. Pr⁡(H≤hobs)\Pr(H \le h_{\text{obs}}) tests for a deficit (inbreeding, population structure, null alleles) and Pr⁡(H≥hobs)\Pr(H \ge h_{\text{obs}}) for an excess. In the ten-person example they are 43/32343/323 and 322/323322/323. The two one-sided values always sum to 1+P(hobs)1 + P(h_{\text{obs}}).
  • Symmetric. Swapping the names of the alleles does not change the result.
  • Deterministic. No sampling, unlike a permutation test of the same null.

Variants and improvements

  • Many alleles. For kk alleles the conditional law is over tables of genotype counts with fixed allele counts, and there are too many tables to list. Guo and Thompson (1992) estimate the p-value by a Markov chain on these tables, or by Monte Carlo over random pairings.
  • Mid p-value. Subtracting half of P(hobs)P(h_{\text{obs}}) gives a less conservative test whose size is closer to α\alpha on average, at the cost of the guarantee.
  • Chi-square and likelihood ratio tests. Fast, but they rely on large expected counts.
  • Exact test with a different ordering. Ordering outcomes by ∣h−E[h]∣|h - \mathbb E[h]| instead of by probability gives another valid exact test; the probability ordering is the one of the paper.
  • X-linked sites. Males are hemizygous and carry no heterozygote information, so the test is run on females, or with a joint law that uses both sexes.

When to use it

  • Quality control of genotype calls in a genome-wide association study, where most sites have rare alleles and a chi-square test would be wrong. A strong departure in controls often points to a genotyping error. With many sites, set the threshold with the multiple comparisons problem in mind.
  • Small samples of any kind, where the expected counts are small.
  • As a check of the random mating hypothesis before a method that assumes it, such as an estimate of allele frequency variance under binomial sampling.

Pitfalls

  • Rare alleles and the chi-square test. With n=100n = 100, one aaaa and no AaAa (na=2n_a = 2), the expected counts are 98.0198.01, 1.981.98 and 0.010.01. The chi-square statistic is about 100100, a p-value near 10−2310^{-23}. The exact law has only h=0h = 0 and h=2h = 2, with P(0)=1/199P(0) = 1/199, so the exact p-value is about 0.0050.005. The chi-square test is far too liberal here.
  • What a small p-value means. A departure can come from inbreeding, population structure (the Wahlund effect), selection, assortative mating, copy number changes or genotyping errors. The test does not say which.
  • Power. With a rare allele, few outcomes are possible, and the test has little power to see a deficit of heterozygotes.
  • Ties in floating point. Two values of hh can have equal probability. Compare with a small relative tolerance, or work in exact arithmetic, or the p-value can drop a tied term.
  • The start value. Starting the walk at h=0h = 0 or h=mh = m gives weights that can overflow a double for large nn; start near the mode.

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.

hardy_weinberg_exact.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hardy-weinberg-exact-test/. The authors are listed in prov/M4SDHR.jsonl.
"""The Hardy-Weinberg exact test of Wigginton, Cutler and Abecasis (2005).

A sample of n diploid individuals at a biallelic locus has n_AA, n_Aa and
n_aa individuals of the three genotypes. Given the allele counts, under
Hardy-Weinberg proportions the number h of heterozygotes has the law

    P(h) = n! n_A! n_a! 2^h / (n_AA! h! n_aa! (2n)!),

where n_AA = (n_A - h) / 2 and n_aa = (n_a - h) / 2 (Levene 1949). The
algorithm starts at a value of h near the mode with weight 1 and fills in the
other weights by the ratio of neighbouring terms, then normalizes. The
two-sided p-value is the total probability of the values of h whose
probability is not larger than that of the observed h.

With exact=True every weight is a fractions.Fraction, so the result is the
exact rational p-value. With exact=False the code uses floats and compares
probabilities with a small relative tolerance, as the C code of the paper
does with its plain comparison.
"""

from __future__ import annotations

import itertools
import math
from fractions import Fraction
from typing import Dict, Tuple, Union

Number = Union[float, Fraction]


def _check_counts(n_AA: int, n_Aa: int, n_aa: int) -> None:
    for c in (n_AA, n_Aa, n_aa):
        if not isinstance(c, int) or isinstance(c, bool) or c < 0:
            raise ValueError("genotype counts must be integers >= 0")
    if n_AA + n_Aa + n_aa == 0:
        raise ValueError("the sample is empty")


def het_distribution(n_AA: int, n_Aa: int, n_aa: int, exact: bool = False) -> Dict[int, Number]:
    """The null law of the heterozygote count given the allele counts.

    Returns a dict that maps each possible heterozygote count h (same parity
    as the minor allele count m, 0 <= h <= m) to P(h).
    """
    _check_counts(n_AA, n_Aa, n_aa)
    n = n_AA + n_Aa + n_aa  # @line L1
    m = min(2 * n_AA + n_Aa, 2 * n_aa + n_Aa)  # @line L1
    one = Fraction(1) if exact else 1.0
    mid = (m * (2 * n - m)) // (2 * n)  # @line L2
    if (m - mid) % 2 == 1:  # @line L2
        mid += 1  # @line L2
    w: Dict[int, Number] = {mid: one}  # @line L3
    h = mid
    while h >= 2:  # @line L4
        r = (m - h) // 2  # minor homozygotes at h
        c = n - h - r  # common homozygotes at h
        w[h - 2] = w[h] * (h * (h - 1)) / (4 * (r + 1) * (c + 1))  # @line L4
        h -= 2
    h = mid
    while h <= m - 2:  # @line L5
        r = (m - h) // 2
        c = n - h - r
        w[h + 2] = w[h] * (4 * r * c) / ((h + 1) * (h + 2))  # @line L5
        h += 2
    total = sum(w.values())  # @line L6
    return {k: w[k] / total for k in sorted(w)}  # @line L6


def hwe_exact_test(n_AA: int, n_Aa: int, n_aa: int, exact: bool = False,
                   alternative: str = "two-sided", rel_tol: float = 1e-9) -> Number:
    """The exact Hardy-Weinberg p-value of the genotype counts.

    alternative is "two-sided" (the test of the paper), "deficit" (too few
    heterozygotes: P(H <= h)) or "excess" (too many: P(H >= h)).
    """
    if alternative not in ("two-sided", "deficit", "excess"):
        raise ValueError("alternative must be two-sided, deficit or excess")
    dist = het_distribution(n_AA, n_Aa, n_aa, exact)
    h_obs = n_Aa
    if alternative == "deficit":
        p = sum(v for h, v in dist.items() if h <= h_obs)
    elif alternative == "excess":
        p = sum(v for h, v in dist.items() if h >= h_obs)
    else:
        bound = dist[h_obs]
        if not exact:
            bound = bound * (1.0 + rel_tol)
        p = sum(v for v in dist.values() if v <= bound)  # @line L7
    if exact:
        return min(p, Fraction(1))
    return min(p, 1.0)


def direct_probability(n: int, n_A: int, h: int) -> Fraction:
    """P(h heterozygotes | n individuals, n_A copies of A) by the closed form."""
    n_a = 2 * n - n_A
    if h < 0 or h > min(n_A, n_a) or (n_A - h) % 2:
        return Fraction(0)
    f = math.factorial
    num = f(n) * f(n_A) * f(n_a) * 2 ** h
    den = f((n_A - h) // 2) * f(h) * f((n_a - h) // 2) * f(2 * n)
    return Fraction(num, den)


def brute_force_distribution(n: int, n_A: int) -> Dict[int, Fraction]:
    """The law of h by listing every placement of the n_A copies of A among
    the 2n slots; individual i holds slots 2i and 2i + 1. All C(2n, n_A)
    placements are equally likely under random union of the copies."""
    counts: Dict[int, int] = {}
    total = 0
    for chosen in itertools.combinations(range(2 * n), n_A):
        s = set(chosen)
        h = sum(1 for i in range(n) if (2 * i in s) != (2 * i + 1 in s))
        counts[h] = counts.get(h, 0) + 1
        total += 1
    return {h: Fraction(c, total) for h, c in sorted(counts.items())}


def chi_square_test(n_AA: int, n_Aa: int, n_aa: int) -> Tuple[float, float]:
    """Pearson's chi-square statistic against Hardy-Weinberg proportions with
    p estimated from the sample, and its p-value on 1 degree of freedom."""
    _check_counts(n_AA, n_Aa, n_aa)
    n = n_AA + n_Aa + n_aa
    p = (2 * n_AA + n_Aa) / (2 * n)
    q = 1.0 - p
    expected = (n * p * p, 2 * n * p * q, n * q * q)
    if min(expected) == 0.0:
        return 0.0, 1.0
    stat = sum((o - e) ** 2 / e for o, e in zip((n_AA, n_Aa, n_aa), expected))
    return stat, math.erfc(math.sqrt(stat / 2.0))


def simulate_null_counts(rng, n: int, n_A: int) -> Tuple[int, int, int]:
    """Genotype counts from a random pairing of n_A copies of A and 2n - n_A
    copies of a (one rng.shuffle call), the null law of the test."""
    pool = [1] * n_A + [0] * (2 * n - n_A)
    rng.shuffle(pool)
    g = [pool[2 * i] + pool[2 * i + 1] for i in range(n)]
    return g.count(2), g.count(1), g.count(0)
hardy_weinberg_exact_test.py 22 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hardy-weinberg-exact-test/. The authors are listed in prov/M4SDHR.jsonl.
"""Entry point named after the slug. The code is in hardy_weinberg_exact.py,
because the tools treat a file whose name ends in _test as a test file."""

from hardy_weinberg_exact import (
    brute_force_distribution,
    chi_square_test,
    direct_probability,
    het_distribution,
    hwe_exact_test,
    simulate_null_counts,
)

__all__ = [
    "brute_force_distribution",
    "chi_square_test",
    "direct_probability",
    "het_distribution",
    "hwe_exact_test",
    "simulate_null_counts",
]
test_hardy_weinberg_exact_test.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hardy-weinberg-exact-test/. The authors are listed in prov/M4SDHR.jsonl.

import math
import random
from fractions import Fraction

import pytest

from hardy_weinberg_exact_test import (
    brute_force_distribution,
    chi_square_test,
    direct_probability,
    het_distribution,
    hwe_exact_test,
    simulate_null_counts,
)


def counts_with(n, n_A, h):
    """Genotype counts (n_AA, n_Aa, n_aa) with n_A copies of A and h heterozygotes."""
    return (n_A - h) // 2, h, (2 * n - n_A - h) // 2


def test_check_values_small_sample():
    # 10 individuals, 6 copies of the minor allele, 2 heterozygotes.
    dist = het_distribution(2, 2, 6, exact=True)
    assert dist == {0: Fraction(1, 323), 2: Fraction(42, 323), 4: Fraction(168, 323), 6: Fraction(112, 323)}
    assert hwe_exact_test(2, 2, 6, exact=True) == Fraction(43, 323)
    assert abs(hwe_exact_test(2, 2, 6) - 43 / 323) < 1e-12


def test_check_values_30_40_30():
    p = hwe_exact_test(30, 40, 30)
    assert abs(p - 0.04686) < 5e-6
    assert abs(p - float(hwe_exact_test(30, 40, 30, exact=True))) < 1e-12
    stat, p_chi = chi_square_test(30, 40, 30)
    assert abs(stat - 4.0) < 1e-12
    assert abs(p_chi - 0.0455003) < 1e-6


def test_recurrence_matches_closed_form():
    for n in range(1, 21):
        for n_A in range(0, 2 * n + 1):
            m = min(n_A, 2 * n - n_A)
            dist = het_distribution(*counts_with(n, n_A, m), exact=True)
            assert sum(dist.values()) == 1
            for h in range(0, m + 1):
                assert dist.get(h, Fraction(0)) == direct_probability(n, n_A, h)


def test_closed_form_matches_random_pairing():
    for n in range(1, 7):
        for n_A in range(0, 2 * n + 1):
            brute = brute_force_distribution(n, n_A)
            m = min(n_A, 2 * n - n_A)
            dist = het_distribution(*counts_with(n, n_A, m), exact=True)
            assert dist == brute


def test_float_matches_exact():
    rng = random.Random(2005)
    for _ in range(50):
        n = rng.randint(1, 200)
        n_A = rng.randint(0, 2 * n)
        m = min(n_A, 2 * n - n_A)
        h = rng.randrange(m % 2, m + 1, 2)
        g = counts_with(n, n_A, h)
        for alt in ("two-sided", "deficit", "excess"):
            pf = hwe_exact_test(*g, alternative=alt)
            pe = hwe_exact_test(*g, exact=True, alternative=alt)
            assert abs(pf - float(pe)) <= 1e-9


def test_p_value_is_valid_in_exact_arithmetic():
    # Under the null, P(p-value <= alpha) <= alpha for every alpha.
    n = 12
    alphas = [Fraction(k, 100) for k in range(1, 100)]
    for n_A in range(0, 2 * n + 1):
        m = min(n_A, 2 * n - n_A)
        law = het_distribution(*counts_with(n, n_A, m), exact=True)
        pv = {h: hwe_exact_test(*counts_with(n, n_A, h), exact=True) for h in law}
        for alpha in alphas:
            assert sum(law[h] for h in law if pv[h] <= alpha) <= alpha


def test_symmetry_and_one_sided_identity():
    rng = random.Random(7)
    for _ in range(30):
        n = rng.randint(1, 40)
        n_A = rng.randint(0, 2 * n)
        m = min(n_A, 2 * n - n_A)
        h = rng.randrange(m % 2, m + 1, 2)
        a, b, c = counts_with(n, n_A, h)
        assert hwe_exact_test(a, b, c, exact=True) == hwe_exact_test(c, b, a, exact=True)
        lo = hwe_exact_test(a, b, c, exact=True, alternative="deficit")
        hi = hwe_exact_test(a, b, c, exact=True, alternative="excess")
        assert lo + hi - het_distribution(a, b, c, exact=True)[b] == 1


def test_edge_cases():
    assert hwe_exact_test(5, 0, 0) == 1.0
    assert hwe_exact_test(0, 0, 7, exact=True) == 1
    assert hwe_exact_test(0, 1, 0, exact=True) == 1
    assert het_distribution(0, 1, 0, exact=True) == {1: 1}
    # A tie: h = 2 and h = 4 both have probability 16/33 when n = 6 and n_A = 4.
    assert het_distribution(1, 2, 3, exact=True) == {0: Fraction(1, 33), 2: Fraction(16, 33), 4: Fraction(16, 33)}
    assert hwe_exact_test(1, 2, 3, exact=True) == 1
    assert abs(hwe_exact_test(1, 2, 3) - 1.0) < 1e-12
    assert abs(hwe_exact_test(0, 4, 2) - 1.0) < 1e-12
    # All heterozygotes is the most extreme excess.
    assert hwe_exact_test(0, 10, 0, exact=True, alternative="excess") == direct_probability(10, 10, 10)


def test_invalid_input():
    with pytest.raises(ValueError):
        hwe_exact_test(0, 0, 0)
    with pytest.raises(ValueError):
        hwe_exact_test(-1, 2, 3)
    with pytest.raises(ValueError):
        hwe_exact_test(1, 2, 3, alternative="less")


def test_null_simulation():
    rng = random.Random(1949)
    n, n_A, reps, alpha = 50, 40, 2000, 0.05
    law = het_distribution(*counts_with(n, n_A, 0), exact=False)
    mu = sum(h * p for h, p in law.items())
    var = sum((h - mu) ** 2 * p for h, p in law.items())
    # Levene's mean of the heterozygote count.
    assert abs(mu - n_A * (2 * n - n_A) / (2 * n - 1)) < 1e-9
    total_h = 0
    rejections = 0
    for _ in range(reps):
        a, b, c = simulate_null_counts(rng, n, n_A)
        total_h += b
        rejections += hwe_exact_test(a, b, c) <= alpha
    z = 4
    assert abs(total_h / reps - mu) <= z * math.sqrt(var / reps)
    assert rejections / reps <= alpha + z * math.sqrt(alpha * (1 - alpha) / reps)

History

Levene (1949) found the exact law of the number of heterozygotes given the allele counts, as a matching problem: the copies are paired at random. Exact tests based on this law were used for small samples for a long time, often with the full formula for each table. Guo and Thompson (1992) made the test practical for many alleles with Markov chain Monte Carlo. Wigginton, Cutler and Abecasis (2005) gave the linear-time recurrence for two alleles and showed by simulation that the chi-square test has an inflated error rate for rare alleles. Their test became the standard quality filter for genotyping arrays.

References

  1. Janis E. Wigginton, David J. Cutler and Gonçalo R. Abecasis, A note on exact tests of Hardy-Weinberg equilibrium, American Journal of Human Genetics 76(5), 2005, pp. 887-893 (the recurrence for the heterozygote probabilities, the start near the mode, the two-sided p-value and the comparison with the chi-square test)
  2. Levene 1949, the exact distribution of the number of heterozygotes given the allele counts under random union
  3. Guo and Thompson 1992, the exact test for many alleles by a Markov chain over tables with fixed allele counts
  4. Bruce S. Weir, Genetic Data Analysis II, Methods for Discrete Population Genetic Data, Sinauer, 1996, Chapter 3 (disequilibrium, and the tests for Hardy-Weinberg proportions)

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