Algorithm Search⌘K

Algorithmcore

McDonald-Kreitman test

Also called MK test.

Compare the ratio of nonsynonymous to synonymous changes within species and between species in a 2 x 2 table to detect adaptive evolution.

Time
Θ(n c + m) worst · average · best
Space
Θ(n + m) extra
Where
c = the number of codons; m = the number of counted changes; n = the number of sequences
Properties
deterministicexactofflineiterative
Origin
John H. McDonald, Martin Kreitman, 1991

The McDonald-Kreitman test asks whether the amino acid changes in a gene fixed between two species more often than neutral theory allows. It counts four kinds of changes in an alignment of coding sequences from two species: nonsynonymous and synonymous fixed differences between the species, DnD_n and DsD_s, and nonsynonymous and synonymous polymorphisms within the species, PnP_n and PsP_s. Under neutrality, a change is nonsynonymous with the same probability whether it ends up fixed or polymorphic, so Dn/DsD_n / D_s and Pn/PsP_n / P_s have the same expected value. A 2 x 2 test of independence, usually Fisher's exact test, tests this. An excess of nonsynonymous fixed differences points to adaptive evolution. McDonald and Kreitman introduced the test in 1991.

In plain words

Take a gene from a few individuals of two related species. Some differences are inside a species: some individuals have one base, some another. Others are between the species: all individuals of one species have one base, all of the other species have another. Each difference is also either silent (the protein stays the same) or a change of amino acid.

If all these changes were neutral, the share of amino acid changes would be the same in both groups, because a mutation does not know if it will become fixed. If selection favoured new amino acids, those changes would spread fast to fixation and would be rare as polymorphisms, so the share of amino acid changes would be higher among the fixed differences. The test checks whether the two shares differ by more than chance.

The problem

Input. Aligned, in-frame coding sequences of nA≥1n_A \ge 1 individuals of species A and nB≥1n_B \ge 1 of species B, with cc codons each and no stop codons. For a test with power, at least one species needs several sequences.

Output. The table

nonsynonymous synonymous
fixed DnD_n DsD_s
polymorphic PnP_n PsP_s

the p-value of a test of independence of rows and columns, the neutrality index NI=(Pn/Ps)/(Dn/Ds)\mathrm{NI} = (P_n / P_s)/(D_n / D_s), and α=1−NI=1−DsPnDnPs\alpha = 1 - \mathrm{NI} = 1 - \frac{D_s P_n}{D_n P_s}, an estimate of the fraction of amino acid substitutions that were adaptive.

The counting rule of the implementation. A codon is used when all sequences have a codon there and exactly one of its positions varies over all sequences. The change is synonymous if all the codons seen at that place code the same amino acid. It is polymorphic if the site varies inside A or inside B, and fixed if each species has one base and the two differ. Codons with two or more varying positions are skipped and reported, because the order of the changes is unknown. Programs differ in how they handle such codons, for example by the pathways of the Nei-Gojobori method.

The algorithm

  1. MK-TEST(A, B)
  2. 1D_n ← D_s ← P_n ← P_s ← 0
  3. 2for each codon where exactly one position varies over all sequences do
  4. 3syn ← all the codons at this place code the same amino acid
  5. 4if the site varies within A or within B then add 1 to P_n (not syn) or P_s (syn)
  6. 5else add 1 to D_n (not syn) or D_s (syn)
  7. 6p ← the two-sided Fisher exact p-value of [[D_n, D_s], [P_n, P_s]]
  8. 7NI ← (P_n / P_s) / (D_n / D_s); α ← 1 − NI
  9. 8return the table, p, NI and α

Line L6 enumerates the tables with the same margins. With r1=Dn+Dsr_1 = D_n + D_s, r2=Pn+Psr_2 = P_n + P_s and c1=Dn+Pnc_1 = D_n + P_n, a table with kk in the top left cell has weight (r1k)(r2c1−k)\binom{r_1}{k}\binom{r_2}{c_1 - k}, and the p-value is the total weight of the tables with weight at most that of the observed one, over (r1+r2c1)\binom{r_1 + r_2}{c_1}. The implementation does this in exact integers, so ties are exact. Line L7 is undefined when DnD_n, DsD_s or PsP_s is 0.

Example

A small alignment. Species A has three sequences and species B has two, of six codons:

1 2 3 4 5 6
A1 ATG GCT TTA CCT GAA AAA
A2 ATG GCC TTA CCT GAA AAA
A3 ATG GCT TTA CCT GAA AGA
B1 ATG GCT CTA CCT GAT AAA
B2 ATG GCT CTA CCT GAT AAA

Codon 2 varies inside A, GCT and GCC both code Ala: a synonymous polymorphism. Codon 6 varies inside A, AAA (Lys) and AGA (Arg): a nonsynonymous polymorphism. Codon 3 is TTA in all of A and CTA in all of B, both Leu: a synonymous fixed difference. Codon 5 is GAA (Glu) in A and GAT (Asp) in B: a nonsynonymous fixed difference. So Dn=Ds=Pn=Ps=1D_n = D_s = P_n = P_s = 1, NI=1\mathrm{NI} = 1, α=0\alpha = 0 and p=1p = 1.

The Adh data. McDonald and Kreitman counted, for the alcohol dehydrogenase gene of Drosophila melanogaster, D. simulans and D. yakuba, Dn=7D_n = 7, Ds=17D_s = 17, Pn=2P_n = 2 and Ps=42P_s = 42. Among fixed differences, 7/24=29%7/24 = 29\% change the amino acid; among polymorphisms only 2/44=4.5%2/44 = 4.5\% do. The margins are r1=24r_1 = 24, r2=44r_2 = 44 and c1=9c_1 = 9, and the two-sided Fisher p-value is 8206423/1120001480=0.00738206423/1120001480 = 0.0073. The neutrality index is 2/427/17=0.116\frac{2/42}{7/17} = 0.116, and α=0.884\alpha = 0.884: by this estimate, most of the amino acid substitutions between the species were adaptive.

Correctness

Lines L2 to L5 put every counted change in exactly one of the four cells, by the counting rule. Line L6 is Fisher's exact test, so the p-value is exact for the null hypothesis that, given the margins, the table has the hypergeometric law.

The test is valid under its null model because of one fact. Suppose the region does not recombine, every mutation is at a new site, and every nonsynonymous mutation is either neutral or so harmful that it never appears in the sample. Then mutations fall on the genealogy of the sample as a Poisson process, and the kind of a mutation (nonsynonymous with probability ff, the same everywhere) is independent of where on the genealogy it falls. Where it falls decides whether it is fixed or polymorphic. So, given the numbers of fixed and polymorphic changes, DnD_n and PnP_n are independent binomials with the same ff, and given also Dn+PnD_n + P_n, DnD_n is hypergeometric: exactly the null law of Fisher's test. The full proof is below.

Proof: MK-TEST puts each counted change in one cell, and its p-value is exact under the neutral modelfull

Setting. Species A has sequences a1,…,anAa_1, \ldots, a_{n_A} and species B has b1,…,bnBb_1, \ldots, b_{n_B}, with nA,nB≥1n_A, n_B \ge 1, all aligned and in frame, of cc codons over A, C, G and T, with no stop codon. At codon tt, the column is the list of the nA+nBn_A + n_B codons there. A position j∈{1,2,3}j \in \{1, 2, 3\} varies at codon tt when the column has two or more bases at jj. Codon tt is counted when exactly one position jj varies. Then the change is synonymous when all codons of the column code the same amino acid, polymorphic when the codons of A, or those of B, have two or more bases at jj, and fixed otherwise.

Lemma 1 (one cell). Each counted codon adds 1 to exactly one of DnD_n, DsD_s, PnP_n and PsP_s, and no other codon changes them. After line L5, Dn+Ds+Pn+PsD_n + D_s + P_n + P_s is the number of counted codons.

Proof. Line L1 sets the counters to 0. Line L2 visits each counted codon once and skips the others. For a counted codon, line L3 sets syn to true or false, and lines L4 and L5 are the two branches of one test, so the codon goes to the polymorphic row or to the fixed row and, inside the row, to one column by syn. □\square

Lemma 2 (fixed means a difference). If a counted codon is fixed, then the bases of A at jj are all equal to some xx, the bases of B are all equal to some yy, and x≠yx \ne y.

Proof. A fixed codon is not polymorphic, so A has one base xx and B has one base yy at jj. Position jj varies over the whole column, so x≠yx \ne y. □\square

Lemma 3 (Fisher's p-value). Let r1=Dn+Dsr_1 = D_n + D_s, r2=Pn+Psr_2 = P_n + P_s, c1=Dn+Pnc_1 = D_n + P_n and N=r1+r2N = r_1 + r_2. Suppose that, given r1r_1, r2r_2 and c1c_1, the law of DnD_n is hypergeometric: Pr⁡(Dn=k)=w(k)/(Nc1)\Pr(D_n = k) = w(k) / \binom{N}{c_1} with w(k)=(r1k)(r2c1−k)w(k) = \binom{r_1}{k}\binom{r_2}{c_1 - k} for max⁡(0,c1−r2)≤k≤min⁡(r1,c1)\max(0, c_1 - r_2) \le k \le \min(r_1, c_1). Then line L6 returns p=Pr⁡(w(Dn)≤w(d))p = \Pr(w(D_n) \le w(d)) for the observed value dd of DnD_n, and Pr⁡(p≤u)≤u\Pr(p \le u) \le u for every u∈[0,1]u \in [0, 1].

Proof. The loop of line L6 runs over exactly the values kk with w(k)>0w(k) > 0 and adds w(k)w(k) when w(k)≤w(d)w(k) \le w(d), so it returns ∑k:w(k)≤w(d)w(k)/(Nc1)\sum_{k : w(k) \le w(d)} w(k) / \binom{N}{c_1}, which is Pr⁡(w(Dn)≤w(d))\Pr(w(D_n) \le w(d)). The sums are of integers, so the comparison is exact. Write G(v)=Pr⁡(w(Dn)≤v)G(v) = \Pr(w(D_n) \le v), so that p=G(w(Dn))p = G(w(D_n)). For u∈[0,1]u \in [0, 1], let v∗v^* be the largest value of ww with G(v∗)≤uG(v^*) \le u. If there is none, Pr⁡(p≤u)=0\Pr(p \le u) = 0. Otherwise p≤up \le u holds exactly when w(Dn)≤v∗w(D_n) \le v^*, because GG does not decrease, and so Pr⁡(p≤u)=G(v∗)≤u\Pr(p \le u) = G(v^*) \le u. □\square

Lemma 4 (the neutral model gives the hypergeometric law). Suppose that, given the genealogy of the sample and the fixed or polymorphic status of every counted change, the kinds of the counted changes are independent, each nonsynonymous with the same probability f∈(0,1)f \in (0, 1). Then, given r1r_1, r2r_2 and c1c_1, DnD_n has the hypergeometric law of Lemma 3.

Proof. Given the statuses, r1r_1 and r2r_2 are fixed numbers, DnD_n is the number of nonsynonymous changes among r1r_1 and PnP_n among r2r_2. So DnD_n and PnP_n are independent with laws Bin(r1,f)\mathrm{Bin}(r_1, f) and Bin(r2,f)\mathrm{Bin}(r_2, f). For Dn+Pn=c1D_n + P_n = c_1,

Pr⁡(Dn=k∣Dn+Pn=c1)=(r1k)fk(1−f)r1−k(r2c1−k)fc1−k(1−f)r2−c1+k∑i(r1i)fi(1−f)r1−i(r2c1−i)fc1−i(1−f)r2−c1+i.\Pr(D_n = k \mid D_n + P_n = c_1) = \frac{\binom{r_1}{k} f^k (1-f)^{r_1 - k} \binom{r_2}{c_1 - k} f^{c_1 - k} (1-f)^{r_2 - c_1 + k}}{\sum_i \binom{r_1}{i} f^i (1-f)^{r_1 - i} \binom{r_2}{c_1 - i} f^{c_1 - i} (1-f)^{r_2 - c_1 + i}}.

Every term has the factor fc1(1−f)N−c1f^{c_1} (1-f)^{N - c_1}, which cancels, and ∑i(r1i)(r2c1−i)=(Nc1)\sum_i \binom{r_1}{i}\binom{r_2}{c_1 - i} = \binom{N}{c_1} by Vandermonde's identity. So the law is w(k)/(Nc1)w(k)/\binom{N}{c_1}, which does not depend on ff or on the statuses. □\square

When the hypothesis of Lemma 4 holds. Take a region without recombination, so the sample has one genealogy, and infinite sites, so each change is one mutation on one branch. Mutations fall on the branches as a Poisson process, independent of their positions in the gene. A mutation on a branch whose descendants in the sample include all of A and none of B, or all of B and none of A, gives a fixed difference; any other branch gives a polymorphism. So the status of a mutation is a function of its branch only. If synonymous mutations are neutral and each nonsynonymous mutation is either neutral or never seen in the sample, then the kind of a seen mutation depends only on its position, and the positions are independent of the branches. So the kinds are independent of the statuses with one probability ff, as Lemma 4 needs. Selection that favours amino acid changes breaks this: such changes go to fixation fast, so a fixed change is more often nonsynonymous than a polymorphic one.

Theorem. MK-TEST returns the four counts of the counting rule, with every counted codon in exactly one cell. Under the hypothesis of Lemma 4, its p-value satisfies Pr⁡(p≤u)≤u\Pr(p \le u) \le u for every uu, so a test that rejects when p≤up \le u has level at most uu. When DnD_n, DsD_s and PsP_s are positive, it returns NI=PnDsPsDn\mathrm{NI} = \frac{P_n D_s}{P_s D_n} and α=1−NI\alpha = 1 - \mathrm{NI}.

Proof. The counts follow from Lemma 1, and Lemma 2 shows that the fixed row counts real differences between the species. The level follows from Lemmas 4 and 3, applied given the margins; since the bound holds given every value of the margins, it also holds without the condition. Line L7 computes NI and α\alpha by their formulas, and returns no value when a denominator is 0. □\square

Complexity

  • Counting. Lines L2 to L5 read every base once and use sets of at most four bases and 21 amino acid codes per codon: Θ(nc)\Theta(n c) for n=nA+nBn = n_A + n_B sequences.
  • The test. Line L6 has at most m+1m + 1 tables, where m=Dn+Ds+Pn+Psm = D_n + D_s + P_n + P_s, each with a product of two binomial coefficients. With the weights updated from one table to the next by a ratio, it costs Θ(m)\Theta(m) arithmetic operations on integers of O(m)O(m) bits. The implementation calls comb for each table, which is simpler and a little slower.
  • Space. The counters and the codons of one column: Θ(n)\Theta(n); the enumeration needs O(m)O(m) for its integers.

Properties

  • Robust to the genealogy. The test does not need the tree, the population size or the demographic history, because these act on both kinds of mutations in the same way. This makes it more robust to demography than tests on the frequency spectrum, such as Tajima's D.
  • A direction. NI<1\mathrm{NI} < 1 (an excess of nonsynonymous fixed differences) points to adaptive evolution. NI>1\mathrm{NI} > 1 (an excess of nonsynonymous polymorphism) points to slightly deleterious variants that segregate but rarely fix.
  • Conservative. Fisher's test conditions on both margins and is conservative for two independent binomials; the tests show a rejection rate below the nominal level under the null.
  • Little power for one gene. Counts are often small; power comes from genes with many changes or from pooling over genes.
  • Biased alpha. The ratio estimate α\alpha is biased when counts are small, because it is a ratio of random counts.

Variants and improvements

  • G test and chi-squared test. The same table can be tested with a G test or a chi-squared test of independence. With large counts they agree with Fisher's test.
  • Removing rare polymorphisms. Slightly deleterious nonsynonymous variants are mostly at low frequency. Leaving out polymorphisms below a frequency cutoff, such as 5%, reduces the downward bias of α\alpha.
  • Asymptotic MK. Messer and Petrov (2013) compute α\alpha as a function of the frequency cutoff and extrapolate to frequency 1.
  • Pooling over genes. Estimators of α\alpha over many genes, such as that of Smith and Eyre-Walker (2002), combine the counts with weights to reduce the small-count bias.
  • Distribution of fitness effects. Methods such as DFE-alpha (Eyre-Walker and Keightley) fit a model of the effects of new mutations to the polymorphism frequencies and use it to predict the neutral expectation of DnD_n.

When to use it

Use it to test a gene, or a set of genes, for adaptive amino acid evolution between two closely related species, when there are polymorphism data for at least one of them. It is the standard first test of positive selection that combines polymorphism and divergence. For divergence only, use dN/dS with a codon substitution model; for recent selection within a population, use haplotype statistics such as extended haplotype homozygosity.

Pitfalls

  • Slightly deleterious mutations. They raise PnP_n more than DnD_n and push α\alpha down, even to negative values; with a recent increase in population size, they can also fix more in the past than now and give a false signal of adaptation.
  • Demography is not fully harmless. Changes of population size between the time of divergence and today change how many weakly selected mutations fix and how many segregate. The test is robust only when all nonsynonymous mutations are neutral or strongly deleterious.
  • Distant species. Multiple hits at the same site, especially at synonymous sites, make the fixed counts too low. Use closely related species.
  • Recombination. With recombination, sites in different parts of the gene have different genealogies. The null law then also needs synonymous and nonsynonymous sites to be mixed evenly along the gene, which is usually close to true inside one gene.
  • Codon usage selection. Selection on synonymous codons breaks the assumption that synonymous changes are neutral.
  • Pooling across genes. A simple sum of tables over genes with different ratios of polymorphism to divergence can give a false result (a Simpson's paradox); use stratified methods.

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.

bioseq.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small DNA utilities shared by the biology pages.

Conventions:
- DNA is a str over "ACGT", written 5' to 3'. Positions are 0-based.
- Random draws use a random.Random object that the caller passes in, and the
  order of the draws is fixed and written in each docstring, so that a seed
  gives the same output on every run.
- Alignment scores are added: pass match as a positive number and mismatch and
  gap as negative numbers. A CIGAR string uses M (a column with a base of both
  strings, equal or not), I (a base of a, the query, against a gap) and D (a
  base of b, the reference, against a gap).

This module holds no algorithm of a page: no ORF finder, no motif finder and
no caller. The functions are building blocks for the page code and its tests.
"""

from __future__ import annotations

import math
import random
from collections import namedtuple
from typing import Dict, List, Sequence, Tuple, Union

DNA = "ACGT"

_COMPLEMENT = {"A": "T", "C": "G", "G": "C", "T": "A", "N": "N",
               "a": "t", "c": "g", "g": "c", "t": "a", "n": "n"}


def revcomp(seq: str) -> str:
    """The reverse complement of seq. N maps to N; other letters raise KeyError."""
    return "".join(_COMPLEMENT[c] for c in reversed(seq))


# NCBI genetic code table 1 (the standard code), in the TCAG order of the NCBI
# listing: the first base changes slowest and the third base fastest.
_AAS = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
_ORDER = "TCAG"
CODON_TABLE: Dict[str, str] = {
    a + b + c: _AAS[16 * i + 4 * j + k]
    for i, a in enumerate(_ORDER)
    for j, b in enumerate(_ORDER)
    for k, c in enumerate(_ORDER)
}
STOPS = frozenset(c for c, aa in CODON_TABLE.items() if aa == "*")


def translate(seq: str, frame: int = 0) -> str:
    """Translate seq[frame:] codon by codon with CODON_TABLE.

    frame is 0, 1 or 2. A stop codon gives "*", a codon with a letter other than
    A, C, G or T gives "X", and a last part shorter than three bases is dropped.
    The function does not look for start or stop codons.
    """
    if frame not in (0, 1, 2):
        raise ValueError("frame must be 0, 1 or 2")
    s = seq.upper()
    out = []
    for i in range(frame, len(s) - 2, 3):
        out.append(CODON_TABLE.get(s[i:i + 3], "X"))
    return "".join(out)


def random_dna(rng: random.Random, n: int, gc: float = 0.5) -> str:
    """n random bases, independent, with P(G) = P(C) = gc/2 and P(A) = P(T) = (1 - gc)/2.

    Draw order: one rng.random() per base, from left to right.
    """
    if not 0.0 <= gc <= 1.0:
        raise ValueError("gc must be in [0, 1]")
    half_gc, cut = gc / 2.0, gc + (1.0 - gc) / 2.0
    out = []
    for _ in range(n):
        u = rng.random()
        if u < half_gc:
            out.append("C")
        elif u < gc:
            out.append("G")
        elif u < cut:
            out.append("A")
        else:
            out.append("T")
    return "".join(out)


def _other_base(rng: random.Random, base: str) -> str:
    """A base other than base, uniform among the other three (one rng.choice)."""
    return rng.choice([b for b in DNA if b != base])


def mutate(rng: random.Random, seq: str, rate: float) -> str:
    """Substitute each base with probability rate, uniformly by one of the other three.

    Draw order: for each position from left to right, one rng.random(); if it is
    below rate, one rng.choice for the new base. Letters other than A, C, G and T
    are kept and use no draw. No insertions or deletions.
    """
    out = []
    for c in seq:
        if c in DNA and rng.random() < rate:
            out.append(_other_base(rng, c))
        else:
            out.append(c)
    return "".join(out)


SimRead = namedtuple("SimRead", ["read", "pos", "strand", "true_seq"])


def simulate_reads(rng: random.Random, genome: str, n: int, length: int,
                   error_rate: float) -> List[SimRead]:
    """n single-end reads of the given length from both strands of genome.

    Each item is SimRead(read, pos, strand, true_seq): pos is the 0-based start
    of the read on the forward strand of genome, strand is "+" or "-", true_seq
    is the error-free read (genome[pos:pos + length], or its reverse complement
    for "-"), and read is true_seq with substitution errors at rate error_rate.

    Draw order for each read: rng.randrange(len(genome) - length + 1) for pos,
    then rng.random() < 0.5 for the "+" strand, then the draws of mutate on
    true_seq.
    """
    if length > len(genome) or length <= 0:
        raise ValueError("need 0 < length <= len(genome)")
    reads = []
    for _ in range(n):
        pos = rng.randrange(len(genome) - length + 1)
        strand = "+" if rng.random() < 0.5 else "-"
        frag = genome[pos:pos + length]
        true_seq = frag if strand == "+" else revcomp(frag)
        reads.append(SimRead(mutate(rng, true_seq, error_rate), pos, strand, true_seq))
    return reads


def phred_to_prob(q: float) -> float:
    """Error probability of the Phred score q: p = 10^(-q/10)."""
    return 10.0 ** (-q / 10.0)


def prob_to_phred(p: float) -> float:
    """Phred score of the error probability p in (0, 1]: Q = -10 log10(p)."""
    if not 0.0 < p <= 1.0:
        raise ValueError("p must be in (0, 1]")
    return -10.0 * math.log10(p)


def hamming(a: Sequence, b: Sequence) -> int:
    """The number of positions where a and b differ; they must have the same length."""
    if len(a) != len(b):
        raise ValueError("hamming needs sequences of equal length")
    return sum(1 for x, y in zip(a, b) if x != y)


def kmers(seq: str, k: int) -> List[str]:
    """All len(seq) - k + 1 substrings of length k, from left to right (with repeats)."""
    if k <= 0:
        raise ValueError("k must be positive")
    return [seq[i:i + k] for i in range(len(seq) - k + 1)]


def gc_content(seq: str) -> float:
    """The fraction of G and C letters in seq (upper or lower case); 0.0 for an empty seq."""
    if not seq:
        return 0.0
    s = seq.upper()
    return (s.count("G") + s.count("C")) / len(s)


Number = Union[int, float]


def _cigar(ops: List[str]) -> str:
    """Run-length code a list of single-letter operations, for example MMMID to 3M1I1D."""
    out = []
    i = 0
    while i < len(ops):
        j = i
        while j < len(ops) and ops[j] == ops[i]:
            j += 1
        out.append(f"{j - i}{ops[i]}")
        i = j
    return "".join(out)


def _fill(a: str, b: str, match: Number, mismatch: Number, gap: Number, free_b_ends: bool):
    """The dynamic programming table of a linear gap alignment of a and b."""
    n, m = len(a), len(b)
    S = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        S[i][0] = i * gap
    for j in range(1, m + 1):
        S[0][j] = 0 if free_b_ends else j * gap
    for i in range(1, n + 1):
        ai = a[i - 1]
        row, up = S[i], S[i - 1]
        for j in range(1, m + 1):
            diag = up[j - 1] + (match if ai == b[j - 1] else mismatch)
            row[j] = max(diag, up[j] + gap, row[j - 1] + gap)
    return S


def _trace(S, a: str, b: str, i: int, j: int, match: Number, mismatch: Number,
           gap: Number, free_b_ends: bool) -> Tuple[List[str], int]:
    """Trace back from cell (i, j); prefer M, then I, then D. Returns the ops and the start in b."""
    ops: List[str] = []
    while i > 0 or (j > 0 and not free_b_ends):
        if i > 0 and j > 0 and S[i][j] == S[i - 1][j - 1] + (match if a[i - 1] == b[j - 1] else mismatch):
            ops.append("M")
            i, j = i - 1, j - 1
        elif i > 0 and S[i][j] == S[i - 1][j] + gap:
            ops.append("I")
            i -= 1
        else:
            ops.append("D")
            j -= 1
    ops.reverse()
    return ops, j


def global_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                 gap: Number = -1) -> Tuple[Number, str]:
    """Needleman-Wunsch alignment of all of a with all of b, with linear gaps.

    Returns (score, cigar). The cigar uses M, I (a base of a only) and D (a base of
    b only); an empty alignment gives "".
    """
    S = _fill(a, b, match, mismatch, gap, False)
    ops, _ = _trace(S, a, b, len(a), len(b), match, mismatch, gap, False)
    return S[len(a)][len(b)], _cigar(ops)


def semiglobal_align(a: str, b: str, match: Number = 1, mismatch: Number = -1,
                     gap: Number = -1, with_start: bool = False):
    """Align all of a (the query) to a substring of b (the reference), with linear gaps.

    Bases of b before and after the aligned part cost nothing and are not in the
    cigar, as in SAM. Returns (score, cigar), or (score, cigar, start) with
    with_start=True, where start is the 0-based position in b of the first
    reference base of the alignment. Among best end columns the leftmost wins.
    """
    S = _fill(a, b, match, mismatch, gap, True)
    n = len(a)
    best_j = max(range(len(b) + 1), key=lambda j: (S[n][j], -j))
    ops, start = _trace(S, a, b, n, best_j, match, mismatch, gap, True)
    if with_start:
        return S[n][best_j], _cigar(ops), start
    return S[n][best_j], _cigar(ops)
mcdonald_kreitman.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mcdonald-kreitman-test/. The authors are listed in prov/4QSXZX.jsonl.
"""The McDonald-Kreitman test (McDonald and Kreitman 1991).

Input: aligned coding sequences of two species, in frame, with no stop codon.

Counting rule. A codon is used only when every sequence has a codon over
ACGT there and at most one of its three positions varies over all the
sequences of both species. A codon with two or more varying positions is
skipped and counted in `skipped`, because the order of the changes is not
known. At the one varying position:
- the change is synonymous when all the codons seen at that place code the
  same amino acid, and nonsynonymous otherwise;
- it is a polymorphism when the site varies within species A or within
  species B, and a fixed difference when each species has one base and the
  two bases differ.

Test. Fisher's exact test of the 2 x 2 table [[Dn, Ds], [Pn, Ps]], two-sided
by the minimum-likelihood rule, in exact integer arithmetic. Summaries: the
neutrality index NI = (Pn / Ps) / (Dn / Ds) and alpha = 1 - NI, the
estimated fraction of adaptive amino acid substitutions.
"""

from __future__ import annotations

from fractions import Fraction
from math import comb
from typing import NamedTuple, Optional, Sequence

from bioseq import CODON_TABLE, STOPS


class MKResult(NamedTuple):
    dn: int
    ds: int
    pn: int
    ps: int
    p_value: float
    neutrality_index: Optional[float]
    alpha: Optional[float]
    skipped: int


def fisher_exact(table, exact: bool = False):
    """Two-sided p-value of Fisher's exact test for [[a, b], [c, d]].

    The tables with the same margins are weighted by C(r1, k) C(r2, c1 - k);
    the p-value is the total weight of the tables with weight <= that of the
    observed one, over C(n, c1). All weights are integers, so ties are exact.
    """
    (a, b), (c, d) = table
    if min(a, b, c, d) < 0:
        raise ValueError("counts must be >= 0")
    r1, r2, c1 = a + b, c + d, a + c
    n = r1 + r2
    lo, hi = max(0, c1 - r2), min(r1, c1)
    w_obs = comb(r1, a) * comb(r2, c)
    total = 0
    for k in range(lo, hi + 1):
        w = comb(r1, k) * comb(r2, c1 - k)
        if w <= w_obs:
            total += w
    p = Fraction(total, comb(n, c1))
    return p if exact else float(p)


def classify_codons(species_a: Sequence[str], species_b: Sequence[str]):
    """The counts (dn, ds, pn, ps, skipped) of the counting rule."""
    seqs = [s.upper() for s in list(species_a) + list(species_b)]
    if not species_a or not species_b:
        raise ValueError("need at least one sequence of each species")
    length = len(seqs[0])
    if length % 3 or any(len(s) != length for s in seqs):
        raise ValueError("sequences must have the same length, a multiple of 3")
    na = len(species_a)
    dn = ds = pn = ps = skipped = 0  # @line L1
    for i in range(0, length, 3):  # @line L2
        codons = [s[i:i + 3] for s in seqs]
        if any(c not in CODON_TABLE for c in codons):
            skipped += 1
            continue
        if any(c in STOPS for c in codons):
            raise ValueError(f"stop codon at codon {i // 3}")
        varying = [j for j in range(3) if len({c[j] for c in codons}) > 1]
        if not varying:
            continue
        if len(varying) > 1:
            skipped += 1
            continue
        j = varying[0]
        syn = len({CODON_TABLE[c] for c in codons}) == 1  # @line L3
        in_a = {c[j] for c in codons[:na]}
        in_b = {c[j] for c in codons[na:]}
        if len(in_a) > 1 or len(in_b) > 1:  # @line L4
            if syn:
                ps += 1
            else:
                pn += 1
        else:  # @line L5
            if syn:
                ds += 1
            else:
                dn += 1
    return dn, ds, pn, ps, skipped


def mk_summary(dn: int, ds: int, pn: int, ps: int):
    """(NI, alpha), or (None, None) when Dn, Ps or Ds is 0."""
    if dn == 0 or ps == 0 or ds == 0:
        return None, None
    ni = (pn * ds) / (ps * dn)
    return ni, 1.0 - ni


def mk_test_from_counts(dn: int, ds: int, pn: int, ps: int, skipped: int = 0) -> MKResult:
    p = fisher_exact([[dn, ds], [pn, ps]])  # @line L6
    ni, alpha = mk_summary(dn, ds, pn, ps)  # @line L7
    return MKResult(dn, ds, pn, ps, p, ni, alpha, skipped)  # @line L8


def mk_test(species_a: Sequence[str], species_b: Sequence[str]) -> MKResult:
    """Count fixed and polymorphic changes of the two kinds, then test."""
    dn, ds, pn, ps, skipped = classify_codons(species_a, species_b)
    return mk_test_from_counts(dn, ds, pn, ps, skipped)
mcdonald_kreitman_test.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mcdonald-kreitman-test/. The authors are listed in prov/4QSXZX.jsonl.

"""Entry point named after the slug. The code lives in mcdonald_kreitman.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from mcdonald_kreitman import MKResult, classify_codons, fisher_exact, mk_summary, mk_test, mk_test_from_counts

__all__ = ["MKResult", "classify_codons", "fisher_exact", "mk_summary", "mk_test", "mk_test_from_counts"]
test_mcdonald_kreitman_test.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mcdonald-kreitman-test/. The authors are listed in prov/4QSXZX.jsonl.

import math
import random
from fractions import Fraction

import pytest

from bioseq import CODON_TABLE, STOPS
from mcdonald_kreitman_test import classify_codons, fisher_exact, mk_summary, mk_test, mk_test_from_counts

SENSE = sorted(c for c in CODON_TABLE if c not in STOPS)


def brute_fisher(table):
    (a, b), (c, d) = table
    r1, r2, c1 = a + b, c + d, a + c
    n = r1 + r2

    def prob(k):
        return Fraction(math.comb(r1, k) * math.comb(r2, c1 - k), math.comb(n, c1))

    obs = prob(a)
    return sum(prob(k) for k in range(0, c1 + 1) if k <= r1 and c1 - k <= r2 and prob(k) <= obs)


def test_fisher_known_values():
    assert fisher_exact([[4, 0], [0, 4]], exact=True) == Fraction(1, 35)
    assert fisher_exact([[7, 2], [3, 8]], exact=True) == Fraction(293, 4199)
    assert fisher_exact([[12, 5], [7, 16]]) == pytest.approx(0.02384, abs=1e-5)
    assert fisher_exact([[0, 0], [0, 0]]) == 1.0
    with pytest.raises(ValueError):
        fisher_exact([[1, -1], [0, 0]])


def test_fisher_against_brute_force():
    rng = random.Random(3)
    for _ in range(300):
        t = [[rng.randrange(12) for _ in range(2)] for _ in range(2)]
        assert fisher_exact(t, exact=True) == brute_fisher(t)
        # The test does not depend on the orientation of the table.
        assert fisher_exact([[t[0][1], t[0][0]], [t[1][1], t[1][0]]], exact=True) == brute_fisher(t)
        assert fisher_exact([t[1], t[0]], exact=True) == brute_fisher(t)


def test_adh_table():
    r = mk_test_from_counts(7, 17, 2, 42)
    assert r.p_value == pytest.approx(8206423 / 1120001480)
    assert r.neutrality_index == pytest.approx(34 / 294)
    assert r.alpha == pytest.approx(1 - 34 / 294)
    assert mk_summary(0, 5, 3, 4) == (None, None)


def test_small_alignment():
    a = ["ATGGCTTTACCTGAAAAA", "ATGGCCTTACCTGAAAAA", "ATGGCTTTACCTGAAAGA"]
    b = ["ATGGCTCTACCTGATAAA", "ATGGCTCTACCTGATAAA"]
    # Codon 2 GCT/GCC: polymorphic, synonymous. Codon 6 AAA/AGA: polymorphic,
    # nonsynonymous. Codon 3 TTA/CTA: fixed, synonymous. Codon 5 GAA/GAT: fixed,
    # nonsynonymous.
    assert classify_codons(a, b) == (1, 1, 1, 1, 0)
    r = mk_test(a, b)
    assert r.p_value == 1.0 and r.neutrality_index == 1.0 and r.alpha == 0.0


def test_skips_and_errors():
    # Two varying positions in one codon, and a gap.
    a = ["TTTGCT", "TTTGCT"]
    b = ["GTAGC-", "GTAGC-"]
    assert classify_codons(a, b) == (0, 0, 0, 0, 2)
    # A site polymorphic in B and different from A counts as a polymorphism.
    assert classify_codons(["CTT"], ["CTC", "CTA"]) == (0, 0, 0, 1, 0)
    with pytest.raises(ValueError):
        classify_codons(["TAA"], ["TAT"])
    with pytest.raises(ValueError):
        classify_codons(["ATGA"], ["ATGA"])
    with pytest.raises(ValueError):
        classify_codons([], ["ATG"])


def test_counts_cover_all_codons():
    rng = random.Random(8)
    for _ in range(50):
        anc = [rng.choice(SENSE) for _ in range(40)]
        seqs = []
        for _ in range(6):
            s = []
            for c in anc:
                if rng.random() < 0.2:
                    i = rng.randrange(3)
                    d = c[:i] + rng.choice([x for x in "ACGT" if x != c[i]]) + c[i + 1:]
                    c = d if d not in STOPS else c
                s.append(c)
            seqs.append("".join(s))
        dn, ds, pn, ps, skipped = classify_codons(seqs[:3], seqs[3:])
        invariant = sum(1 for k in range(40) if len({s[3 * k:3 * k + 3] for s in seqs}) == 1)
        assert dn + ds + pn + ps + skipped + invariant == 40


def rejection_rate(rng, reps, f_fixed, f_poly, d=20, p=30):
    hits = 0
    for _ in range(reps):
        dn = sum(rng.random() < f_fixed for _ in range(d))
        pn = sum(rng.random() < f_poly for _ in range(p))
        if fisher_exact([[dn, d - dn], [pn, p - pn]]) <= 0.05:
            hits += 1
    return hits / reps


def test_level_under_the_null_and_power():
    rng = random.Random(1991)
    reps = 2000
    rate = rejection_rate(rng, reps, 0.7, 0.7)
    # Fisher's test is conservative: the rate is at most the level, up to noise.
    assert rate <= 0.05 + 4 * math.sqrt(0.05 * 0.95 / reps)
    power = rejection_rate(rng, 500, 0.95, 0.5)
    assert power > 0.5

History

McDonald and Kreitman published the test in Nature in 1991, with the Adh data from three Drosophila species, and it became one of the main tests of adaptive protein evolution. Later work moved from single genes to genome-wide estimates of α\alpha, with methods that correct for slightly deleterious mutations.

References

  1. John H. McDonald and Martin Kreitman, Adaptive protein evolution at the Adh locus in Drosophila, Nature 351(6328), 1991, pp. 652-654 (the 2 x 2 table of fixed and polymorphic, replacement and synonymous changes, and the Adh data)
  2. Ziheng Yang, Molecular Evolution, A Statistical Approach, Oxford University Press, 2014, Chapter 11 (neutral and adaptive protein evolution)

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
  • at least three sources
  • a scene preset for the example