Algorithm Search⌘K

Algorithmcore

Nei-Gojobori method

Also called Nei-Gojobori counting method.

Estimate dN and dS by counting synonymous and nonsynonymous sites and differences between two coding sequences, with a Jukes-Cantor correction.

Time
Θ(c) worst · average · best
Space
Θ(1) extra
Where
c = the number of codons
Properties
deterministicexactonlineiterative
Origin
Masatoshi Nei, Takashi Gojobori, 1986

The Nei-Gojobori method estimates, for two aligned protein-coding sequences, the number of synonymous substitutions per synonymous site dSd_S and the number of nonsynonymous substitutions per nonsynonymous site dNd_N. A synonymous change keeps the amino acid and a nonsynonymous change replaces it, so their ratio ω=dN/dS\omega = d_N / d_S measures how strongly selection acts on the protein. The method counts sites and differences codon by codon with the genetic code, divides them, and corrects the two proportions for multiple hits with the Jukes-Cantor formula. Nei and Gojobori published it in 1986, and it is still the default counting method in many programs.

In plain words

Not every base of a gene can change the protein. At the third base of a codon for alanine, any change still gives alanine; at the middle base of almost any codon, every change gives another amino acid. So the number of synonymous differences must be divided by the number of "synonymous places", not by the length.

The method gives each base of each codon a share of synonymous and nonsynonymous: if one of the three possible changes at a base keeps the amino acid, that base counts as 1/31/3 synonymous and 2/32/3 nonsynonymous. Adding up gives the two kinds of sites. Then it counts the differences between the two sequences of each kind. When two codons differ at more than one base, it averages over all orders of the changes. Last, it divides differences by sites and corrects for changes that hit a base twice.

The problem

Input. Two aligned coding sequences XX and YY in the same reading frame, of cc codons each, with no stop codon. A genetic code, here the standard code of NCBI table 1.

Output. The numbers of synonymous and nonsynonymous sites SS and NN, of differences SdS_d and NdN_d, the proportions pS=Sd/Sp_S = S_d / S and pN=Nd/Np_N = N_d / N, and the distances

dS=−34ln⁡(1−43pS),dN=−34ln⁡(1−43pN).d_S = -\tfrac{3}{4} \ln\left(1 - \tfrac{4}{3} p_S\right), \qquad d_N = -\tfrac{3}{4} \ln\left(1 - \tfrac{4}{3} p_N\right).

Sites of a codon. For a sense codon xx and a position ii, let fi(x)f_i(x) be the fraction of the three other bases at ii that give a codon for the same amino acid. Then s(x)=f1(x)+f2(x)+f3(x)s(x) = f_1(x) + f_2(x) + f_3(x) and n(x)=3−s(x)n(x) = 3 - s(x). A change to a stop codon counts as nonsynonymous. For the pair, S=∑(s(x)+s(y))/2S = \sum (s(x) + s(y))/2 over the codon pairs and N=3c−SN = 3c - S.

Differences of a codon pair. If xx and yy differ at one position, the difference is synonymous when they code the same amino acid and nonsynonymous otherwise. If they differ at k=2k = 2 or 33 positions, there are k!k! orders of the single changes, called pathways. Each step of a pathway is synonymous or not, and sds_d and ndn_d are the averages of the counts over the pathways, all with the same weight.

The algorithm

  1. NEI-GOJOBORI(X, Y)
  2. 1S ← 0; S_d ← 0; N_d ← 0; c ← 0
  3. 2for each pair of codons (x, y) at the same place in X and Y do
  4. 3S ← S + (s(x) + s(y)) / 2
  5. 4(s_d, n_d) ← the mean synonymous and nonsynonymous steps over the pathways from x to y
  6. 5S_d ← S_d + s_d; N_d ← N_d + n_d; c ← c + 1
  7. 6N ← 3c − S; p_S ← S_d / S; p_N ← N_d / N
  8. 7d_S ← −(3/4) ln(1 − 4 p_S / 3); d_N ← −(3/4) ln(1 − 4 p_N / 3)
  9. 8return d_S, d_N and d_N / d_S

The values s(x)s(x) for the 61 sense codons and (sd,nd)(s_d, n_d) for the 61261^2 pairs depend only on the code, so a program can compute them once. The implementation uses exact fractions for sites and differences.

Pathways through stop codons. A pathway may pass through a stop codon, which would end the protein. The 1986 paper does not discuss this case. Programs commonly leave such pathways out, and the implementation does the same by default. For the standard code, every pair of sense codons has at least one pathway without a stop. Codons with a gap or an unknown base in either sequence are left out.

Example

Take ten codons:

codon 1 2 3 4 5 6 7 8 9 10
XX ATG GCT TTA CCT GAA AAA GGG TGG TTT CAT
YY ATG GCC CTA CCT GAT AAA GGA TGG GTA CAT
s(x)s(x) 0 1 2/3 1 1/3 1/3 1 0 1/3 1/3
s(y)s(y) 0 1 4/3 1 1/3 1/3 1 0 1 1/3

Two values show the rule. For TTA (Leu), TTG is Leu, so f3=1/3f_3 = 1/3; CTA is Leu, so f1=1/3f_1 = 1/3; no change at the middle base keeps Leu. So s=2/3s = 2/3. For CTA (Leu), all three changes at the third base keep Leu and TTA does at the first base, so s=4/3s = 4/3.

So S=(5+19/3)/2=17/3=5.667S = (5 + 19/3)/2 = 17/3 = 5.667 and N=30−17/3=73/3=24.333N = 30 - 17/3 = 73/3 = 24.333.

The differences: codons 2 (Ala to Ala), 3 (Leu to Leu) and 7 (Gly to Gly) are synonymous, and codon 5 (Glu to Asp) is nonsynonymous. Codon 9, TTT (Phe) to GTA (Val), differs at positions 1 and 3. The pathway TTT, GTT, GTA has one nonsynonymous step (Phe to Val) and one synonymous step (Val to Val). The pathway TTT, TTA, GTA has two nonsynonymous steps (Phe to Leu, Leu to Val). So sd=1/2s_d = 1/2 and nd=3/2n_d = 3/2. In total, Sd=3.5S_d = 3.5 and Nd=2.5N_d = 2.5.

Then pS=3.5/5.667=0.6176p_S = 3.5 / 5.667 = 0.6176 and pN=2.5/24.333=0.1027p_N = 2.5 / 24.333 = 0.1027, so dS=−0.75ln⁡(1−0.8235)=1.3010d_S = -0.75 \ln(1 - 0.8235) = 1.3010 and dN=0.1105d_N = 0.1105, and ω=0.085\omega = 0.085. The protein changes much more slowly than the synonymous sites, which is the usual sign of purifying selection. With only ten codons, pSp_S is near the limit 3/43/4 where the correction fails, and the estimate has a large error.

Correctness

Line L3 adds the mean of the site counts of the two codons, as Nei and Gojobori do, so the result does not depend on which sequence comes first. Lines L4 and L5 add the mean counts over the pathways; every pathway between codons that differ at kk positions has exactly kk steps, so sd+nd=ks_d + n_d = k and Sd+NdS_d + N_d is the number of differing bases. Line L6 gives S+N=3cS + N = 3c, the number of bases.

The site count is the right divisor in this sense: if every base mutates at the same rate to each of the three other bases, the expected number of synonymous changes at codon xx per unit of time is proportional to s(x)s(x), and that of changes to another amino acid or to a stop codon is proportional to n(x)n(x), with the same factor. So, if all these changes stayed in the sequence, pSp_S and pNp_N would have the same expected value for small divergence. Changes to stop codons do not stay in a working gene, so even without other selection pNp_N is a little lower than pSp_S. Line L7 applies the Jukes-Cantor correction to each class as if its sites were a separate sequence with equal rates among the four bases. The full proof is below.

Proof: NEI-GOJOBORI computes the counts of the definition, and the counts measure the two kinds of change on the same scalefull

Setting. XX and YY are aligned coding sequences of cc codons with no stop codon, and the genetic code maps the 64 codons to 20 amino acids and stop. For a sense codon xx, fi(x)f_i(x), s(x)s(x) and n(x)=3−s(x)n(x) = 3 - s(x) are as on the page. For sense codons xx and yy that differ at the positions in a set PP with ∣P∣=k|P| = k, a pathway is an order (i1,…,ik)(i_1, \ldots, i_k) of PP, and its codons are x=z0,z1,…,zk=yx = z_0, z_1, \ldots, z_k = y, where zjz_j is zj−1z_{j-1} with the base at iji_j changed to that of yy. Step jj is synonymous when zj−1z_{j-1} and zjz_j code the same amino acid. The kept pathways are those whose codons are all sense codons, or all pathways if none is.

Lemma 1. After the loop of lines L2 to L5, S=∑t=1c(s(xt)+s(yt))/2S = \sum_{t=1}^{c} (s(x_t) + s(y_t))/2, Sd=∑tsd(xt,yt)S_d = \sum_t s_d(x_t, y_t) and Nd=∑tnd(xt,yt)N_d = \sum_t n_d(x_t, y_t), where (xt,yt)(x_t, y_t) is the tt-th codon pair.

Proof. Line L1 sets the three sums to 0, and each pass of the loop adds the term of one codon pair to each of them, by lines L3 to L5. □\square

So lines L6 and L7 compute NN, pSp_S, pNp_N, dSd_S and dNd_N by their definitions, and line L8 returns them.

Lemma 2. For every codon pair, sd+nd=ks_d + n_d = k, the number of positions where the codons differ. Hence Sd+NdS_d + N_d is the number of bases at which XX and YY differ, and S+N=3cS + N = 3c.

Proof. Each step of a pathway changes the base at one position of PP to its final value, and no position appears twice, so every pathway has exactly kk steps, each synonymous or not. The mean over the kept pathways of (synonymous steps + nonsynonymous steps) is therefore kk. Summing over codon pairs gives the number of differing bases. Since s(x)+n(x)=3s(x) + n(x) = 3 for every codon, N=3c−SN = 3c - S is the sum of (n(xt)+n(yt))/2(n(x_t) + n(y_t))/2. □\square

Lemma 3. The result does not change when XX and YY are swapped.

Proof. The term of line L3 is symmetric. Reversing the codons of a pathway from xx to yy gives a pathway from yy to xx with the same steps in reverse order, the same synonymous steps, and the same codons, so it is kept exactly when the first one is. This is a bijection between the pathways of the two directions, so sds_d and ndn_d are the same. □\square

Lemma 4. Suppose each base mutates to each of the three other bases at rate uu, independently of the others. Then at a sense codon xx, the rate of synonymous single-base changes is 3u s(x)3u\, s(x), and the rate of changes to a codon of another amino acid or to a stop codon is 3u n(x)3u\, n(x).

Proof. There are nine single-base changes of xx, each at rate uu. By the definition of fif_i, the number of synonymous ones at position ii is 3fi(x)3 f_i(x), so in total there are 3s(x)3 s(x) synonymous changes and 9−3s(x)=3n(x)9 - 3 s(x) = 3 n(x) others. □\square

So in a short time τ\tau, the expected number of synonymous changes in the sequence is 3uτ3u\tau times its synonymous site count, and the expected number of other changes is 3uτ3u\tau times its nonsynonymous site count. Dividing by the site counts puts both kinds of change on the same scale, the expected number of changes per site. This is what pSp_S and pNp_N estimate when divergence is small.

Lemma 5. Under the Jukes-Cantor model with dd expected substitutions per site between two sequences, the probability that a site differs is p=34(1−e−4d/3)p = \frac{3}{4}(1 - e^{-4d/3}). For 0≤p<3/40 \le p < 3/4, the inverse is d=−34ln⁡(1−43p)d = -\frac{3}{4}\ln(1 - \frac{4}{3}p).

Proof. Along the path between the two sequences, a site is replaced at rate 4/34/3 per unit of dd by a base drawn uniformly from all four, since a substitution at rate 1 to one of the three other bases is the same as a uniform draw at rate 4/34/3 that keeps the base with probability 1/41/4. The site differs exactly when at least one draw happened, probability 1−e−4d/31 - e^{-4d/3}, and the last draw gives another base, probability 3/43/4. Solving for dd gives the inverse, which is defined and increasing on [0,3/4)[0, 3/4). □\square

Theorem. NEI-GOJOBORI returns the Nei-Gojobori values SS, NN, SdS_d, NdN_d, pSp_S, pNp_N, dSd_S and dNd_N of XX and YY, and these do not depend on the order of the two sequences. dSd_S and dNd_N are the Jukes-Cantor distances of the two classes of sites, each treated as a separate sequence.

Proof. Lemma 1 gives the counts, and lines L6 and L7 apply the definitions and, by Lemma 5, the Jukes-Cantor inverse. Lemma 3 gives the symmetry. □\square

The method of moments in Lemma 5 is exact only for the model it assumes. For a class of sites in a real gene, rates differ between transitions and transversions and between sites, and the class is not a fixed set of sites, since fif_i changes when a codon changes; so dSd_S and dNd_N are approximations.

Complexity

  • Time. Each codon pair costs O(1)O(1): at most nine neighbours for each site count and at most six pathways of three steps. So the time is Θ(c)\Theta(c) in every case.
  • Space. Five counters: Θ(1)\Theta(1). With precomputed tables, 61 site values and 61261^2 difference pairs, a constant for a fixed code.
  • Many sequences. All pairs of mm sequences cost Θ(m2c)\Theta(m^2 c).

Properties

  • Exact counts. The site and difference counts are rational numbers; the implementation keeps them exact.
  • Symmetric. Swapping XX and YY gives the same result.
  • Equal weights. All bases and all pathways have the same weight, so the method ignores the higher rate of transitions than transversions, the unequal use of codons, and the fact that some pathways are much more likely than others.
  • Undefined at saturation. If p≥3/4p \ge 3/4, the logarithm is not defined. Near that limit the variance is very large. The usual large-sample variance is Var⁡(d)≈p(1−p)/(L(1−4p/3)2)\operatorname{Var}(d) \approx p(1 - p) / (L (1 - 4p/3)^2), with LL the number of sites of the class.
  • No uncertainty about the order. Averaging over pathways is a choice, not an estimate of the true order of the changes.

Variants and improvements

  • Weighted pathways. Miyata and Yasunaga (1980) weighted pathways by how likely each amino acid change is, instead of giving them equal weights.
  • Modified counting with transitions. Methods such as that of Li, Wu and Luo (1985) classify sites as nondegenerate, twofold or fourfold degenerate and use the Kimura two-parameter distance, so that the transition bias is taken into account.
  • Codon frequencies and the transition ratio. Yang and Nielsen (2000) count sites with the transition to transversion ratio and the codon frequencies estimated from the data.
  • Maximum likelihood. A codon substitution model estimates ω\omega by likelihood, handles the transition bias and the codon frequencies inside one model, and extends to many sequences on a tree.

When to use it

Use it for a fast and simple estimate of dNd_N, dSd_S and ω\omega between two closely related coding sequences, for example in screens of many gene pairs, or as a check on likelihood estimates. For distant sequences, strong transition bias, strong codon bias or more than two sequences, use a codon substitution model by likelihood. For a test of adaptive evolution that uses polymorphism inside a species as well, use the McDonald-Kreitman test.

Pitfalls

  • Saturation. For distant sequences pSp_S approaches 3/43/4, dSd_S becomes very large and noisy, and ω\omega is then strongly biased. Treat estimates with dSd_S above about 1 with care.
  • Transition bias. Transitions at third positions are often synonymous, so a high transition rate inflates synonymous differences relative to sites and lowers ω\omega when the method ignores it.
  • Alignment. The sequences must be in frame. A frame shift or a misaligned codon creates many false nonsynonymous differences.
  • Stop codons. An internal stop codon means a pseudogene, a frame error or a sequencing error. Remove it before counting.
  • Reading ω\omega. A value above 1 over the whole gene is rare, because most sites are constrained. A value below 1 does not mean there was no positive selection at a few sites.

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)
nei_gojobori_method.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nei-gojobori-method/. The authors are listed in prov/10S5MW.jsonl.
"""The Nei-Gojobori (1986) method for dN and dS of two coding sequences.

Sites. For a sense codon c, s(c) is the sum over its three positions of the
fraction of the three other bases at that position that give a codon for the
same amino acid; n(c) = 3 - s(c). A change to a stop codon counts as
nonsynonymous. The site counts are exact Fractions.

Differences. For two sense codons x and y that differ at k positions, each of
the k! orders of the k changes is a pathway. A step is synonymous when the two
codons of the step code the same amino acid. The synonymous and nonsynonymous
differences of the pair are the averages over the pathways, all with the same
weight. Pathways through a stop codon are left out by default (the 1986 paper
does not discuss them; programs commonly leave them out). If every pathway
goes through a stop codon, all pathways are used, and a step into or out of a
stop counts as nonsynonymous.

Distances. p = differences / sites, and d = -(3/4) ln(1 - 4p/3), the
Jukes-Cantor correction; d is None when p >= 3/4.
"""

from __future__ import annotations

import itertools
import math
from fractions import Fraction
from typing import NamedTuple, Optional, Tuple

from bioseq import CODON_TABLE, DNA, STOPS


class Result(NamedTuple):
    syn_sites: Fraction
    nonsyn_sites: Fraction
    syn_diffs: Fraction
    nonsyn_diffs: Fraction
    p_s: float
    p_n: float
    d_s: Optional[float]
    d_n: Optional[float]
    omega: Optional[float]
    codons: int


def _check_codon(c: str) -> None:
    if c not in CODON_TABLE:
        raise ValueError(f"not a codon over ACGT: {c!r}")
    if c in STOPS:
        raise ValueError(f"stop codon {c} in a coding sequence")


def codon_sites(c: str) -> Tuple[Fraction, Fraction]:
    """(s(c), n(c)), the synonymous and nonsynonymous sites of a sense codon."""
    _check_codon(c)
    aa = CODON_TABLE[c]
    s = Fraction(0)
    for i in range(3):
        for b in DNA:
            if b != c[i] and CODON_TABLE[c[:i] + b + c[i + 1:]] == aa:
                s += Fraction(1, 3)
    return s, 3 - s


def codon_differences(x: str, y: str, skip_stop_paths: bool = True) -> Tuple[Fraction, Fraction]:
    """(s_d, n_d): synonymous and nonsynonymous differences of two sense codons,
    averaged over the pathways between them."""
    _check_codon(x)
    _check_codon(y)
    pos = [i for i in range(3) if x[i] != y[i]]
    if not pos:
        return Fraction(0), Fraction(0)
    paths = []
    for order in itertools.permutations(pos):
        cur = x
        syn = non = 0
        through_stop = False
        for i in order:
            nxt = cur[:i] + y[i] + cur[i + 1:]
            if nxt in STOPS:
                through_stop = True
            if CODON_TABLE[nxt] == CODON_TABLE[cur]:
                syn += 1
            else:
                non += 1
            cur = nxt
        paths.append((syn, non, through_stop))
    kept = [p for p in paths if not p[2]] if skip_stop_paths else paths
    if not kept:
        kept = paths
    m = len(kept)
    return Fraction(sum(p[0] for p in kept), m), Fraction(sum(p[1] for p in kept), m)


def jukes_cantor(p: float) -> Optional[float]:
    """d = -(3/4) ln(1 - 4p/3), or None when p >= 3/4."""
    if p < 0:
        raise ValueError("p must be >= 0")
    if p >= 0.75:
        return None
    return -0.75 * math.log1p(-4.0 * p / 3.0)


def nei_gojobori(seq1: str, seq2: str, skip_stop_paths: bool = True) -> Result:
    """dN, dS and dN/dS of two aligned coding sequences in the same frame.

    Codons with a letter other than A, C, G or T in either sequence (gaps,
    N) are left out. A stop codon raises ValueError. omega is None when dS is
    0 or undefined, or dN is undefined.
    """
    a = seq1.upper()
    b = seq2.upper()
    if len(a) != len(b) or len(a) % 3:
        raise ValueError("need two sequences of the same length, a multiple of 3")
    s_sites = Fraction(0)  # @line L1
    s_d = Fraction(0)
    n_d = Fraction(0)
    r = 0
    for i in range(0, len(a), 3):  # @line L2
        x, y = a[i:i + 3], b[i:i + 3]
        if x not in CODON_TABLE or y not in CODON_TABLE:
            continue
        s_sites += (codon_sites(x)[0] + codon_sites(y)[0]) / 2  # @line L3
        sd, nd = codon_differences(x, y, skip_stop_paths)  # @line L4
        s_d += sd  # @line L5
        n_d += nd
        r += 1
    n_sites = 3 * r - s_sites  # @line L6
    if s_sites == 0 or n_sites == 0:
        raise ValueError("no synonymous or no nonsynonymous sites")
    p_s = float(s_d / s_sites)
    p_n = float(n_d / n_sites)
    d_s = jukes_cantor(p_s)  # @line L7
    d_n = jukes_cantor(p_n)
    omega = d_n / d_s if d_s and d_n is not None else None
    return Result(s_sites, n_sites, s_d, n_d, p_s, p_n, d_s, d_n, omega, r)  # @line L8
test_nei_gojobori_method.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nei-gojobori-method/. The authors are listed in prov/10S5MW.jsonl.

import itertools
import math
import random
from fractions import Fraction as F

import pytest

from bioseq import CODON_TABLE, DNA, STOPS
from nei_gojobori_method import codon_differences, codon_sites, jukes_cantor, nei_gojobori

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


def test_codon_sites():
    assert codon_sites("TTA") == (F(2, 3), F(7, 3))
    assert codon_sites("GCT") == (F(1), F(2))
    assert codon_sites("CTA") == (F(4, 3), F(5, 3))
    assert codon_sites("ATG") == (F(0), F(3))
    assert codon_sites("TGG") == (F(0), F(3))
    # AGA: CGA is Arg, TGA is a stop (nonsynonymous), AGG is Arg.
    assert codon_sites("AGA") == (F(2, 3), F(7, 3))
    assert len(SENSE) == 61
    assert sum(codon_sites(c)[0] for c in SENSE) == F(134, 3)


def test_sites_match_the_neighbours():
    # 3 s(c) is the number of the nine one-base neighbours of c that code the same amino acid.
    for c in SENSE:
        same = 0
        for i in range(3):
            for b in DNA:
                if b != c[i] and CODON_TABLE[c[:i] + b + c[i + 1:]] == CODON_TABLE[c]:
                    same += 1
        assert 3 * codon_sites(c)[0] == same


def test_codon_differences():
    assert codon_differences("TTT", "GTA") == (F(1, 2), F(3, 2))
    assert codon_differences("CTT", "CTC") == (F(1), F(0))
    assert codon_differences("GAA", "GAT") == (F(0), F(1))
    assert codon_differences("AAA", "AAA") == (F(0), F(0))
    # TTT to CAA: the pathway TTT, TAT, TAA passes a stop codon.
    assert codon_differences("TTT", "CAA") == (F(1, 2), F(5, 2))
    assert codon_differences("TTT", "CAA", skip_stop_paths=False) == (F(1, 3), F(8, 3))


def brute_differences(x, y):
    pos = [i for i in range(3) if x[i] != y[i]]
    rows = []
    for order in itertools.permutations(pos):
        cur, syn, stop = x, 0, False
        for i in order:
            nxt = cur[:i] + y[i] + cur[i + 1:]
            stop |= nxt in STOPS
            syn += CODON_TABLE[nxt] == CODON_TABLE[cur]
            cur = nxt
        rows.append((syn, len(pos) - syn, stop))
    kept = [r for r in rows if not r[2]] or rows
    return F(sum(r[0] for r in kept), len(kept)), F(sum(r[1] for r in kept), len(kept)), len(pos)


def test_all_codon_pairs():
    for x in SENSE:
        for y in SENSE:
            sd, nd = codon_differences(x, y)
            bsd, bnd, k = brute_differences(x, y)
            assert (sd, nd) == (bsd, bnd)
            assert sd + nd == k
            assert codon_differences(y, x) == (sd, nd)


def test_example():
    x = "ATGGCTTTACCTGAAAAAGGGTGGTTTCAT"
    y = "ATGGCCCTACCTGATAAAGGATGGGTACAT"
    r = nei_gojobori(x, y)
    assert r.codons == 10
    assert r.syn_sites == F(17, 3) and r.nonsyn_sites == F(73, 3)
    assert r.syn_diffs == F(7, 2) and r.nonsyn_diffs == F(5, 2)
    assert r.p_s == pytest.approx(21 / 34)
    assert r.p_n == pytest.approx(15 / 146)
    assert r.d_s == pytest.approx(-0.75 * math.log(1 - 4 * 21 / 34 / 3))
    assert r.d_n == pytest.approx(0.1104935, abs=1e-6)
    assert r.omega == pytest.approx(r.d_n / r.d_s)


def test_jukes_cantor():
    assert jukes_cantor(0.0) == 0.0
    assert jukes_cantor(0.3) == pytest.approx(-0.75 * math.log(0.6))
    assert jukes_cantor(0.75) is None
    with pytest.raises(ValueError):
        jukes_cantor(-0.1)


def test_identical_and_special_cases():
    rng = random.Random(5)
    seq = "".join(rng.choice(SENSE) for _ in range(50))
    r = nei_gojobori(seq, seq)
    assert r.d_s == 0.0 and r.d_n == 0.0 and r.omega is None
    assert r.syn_sites + r.nonsyn_sites == 150
    # Gaps and N are left out; lower case is accepted.
    r2 = nei_gojobori("atgNNNtta---", "ATGAAACTAGGG")
    assert r2.codons == 2 and r2.syn_diffs == 1
    with pytest.raises(ValueError):
        nei_gojobori("ATGTAA", "ATGTTA")
    with pytest.raises(ValueError):
        nei_gojobori("ATGT", "ATGT")


def test_only_synonymous_or_only_nonsynonymous_changes():
    rng = random.Random(11)
    a, b, c = [], [], []
    syn = non = 0
    for _ in range(200):
        x = rng.choice(SENSE)
        others = [x[:i] + d + x[i + 1:] for i in range(3) for d in DNA if d != x[i]]
        same = [y for y in others if CODON_TABLE[y] == CODON_TABLE[x]]
        diff = [y for y in others if y not in STOPS and CODON_TABLE[y] != CODON_TABLE[x]]
        a.append(x)
        b.append(rng.choice(same) if same else x)
        c.append(rng.choice(diff))
        syn += bool(same)
        non += 1
    r = nei_gojobori("".join(a), "".join(b))
    assert r.nonsyn_diffs == 0 and r.syn_diffs == syn and r.d_n == 0.0
    r = nei_gojobori("".join(a), "".join(c))
    assert r.syn_diffs == 0 and r.nonsyn_diffs == non and r.d_s == 0.0

History

Nei and Gojobori published the method in 1986, after the weighted pathway method of Miyata and Yasunaga (1980) and the degeneracy classes of Li, Wu and Luo (1985). Their version gives all pathways the same weight, which makes it simple to compute by hand or by a small table. Likelihood methods based on codon models, from Goldman and Yang (1994) and Muse and Gaut (1994), came later and are now the standard for careful analyses, but the counting method stays common for its speed and simplicity.

References

  1. Masatoshi Nei and Takashi Gojobori, Simple methods for estimating the numbers of synonymous and nonsynonymous nucleotide substitutions, Molecular Biology and Evolution 3(5), 1986, pp. 418-426 (the counting of synonymous and nonsynonymous sites, the pathways for codons with two or three differences, and the Jukes-Cantor correction)
  2. Ziheng Yang, Molecular Evolution, A Statistical Approach, Oxford University Press, 2014, Chapter 2 (counting methods and likelihood methods for the estimation of dS and dN)

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