Algorithmcore
Codon adaptation index
Also called CAI.
Give each codon a weight from its usage in highly expressed genes, then score a gene by the geometric mean of the weights of its codons. The score is in (0, 1].
- Time
- Θ(M + N) worst · average · best
- Space
- Θ(1) extra
- Where
- M = the number of codons in the reference set; N = the number of codons in the gene
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
The codon adaptation index (CAI) measures how strongly a gene uses the codons that a set of highly expressed genes prefers. Most amino acids are coded by two to six synonymous codons, and in many organisms the genes that are expressed at high levels use some of these codons much more than others. Sharp and Li (1987) give each codon a weight between 0 and 1: its count in a reference set of highly expressed genes, divided by the count of the most used codon of the same amino acid. The CAI of a gene is the geometric mean of the weights of its codons. A value near 1 means the gene uses the preferred codons almost everywhere, and a low value means it does not. The index predicts expression level from sequence alone, helps to choose codons for a gene that is to be expressed in another host, and is one of the codon statistics that separate real genes from chance ORFs.
In plain words
Take a set of genes that the cell makes in large amounts. For each amino acid, count how often each of its codons occurs there. The codon used most gets the weight 1, and every other codon gets its count divided by that count, so a codon used half as often gets 1/2. To score a new gene, look up the weight of each of its codons and take the geometric mean: multiply the weights and take the L-th root, where L is the number of codons. In practice, add the logarithms and divide by L. A gene made only of preferred codons scores 1. Skip codons that carry no choice, such as ATG for methionine, and the stop codons.
The problem
Input. A reference set of protein-coding sequences, read in frame from the start codon, with codons in total; a gene with codons in the same frame; and a genetic code, by default NCBI table 1.
Output. A table of weights , one for each sense codon , and the index of the gene.
Let be the number of times codon occurs in the reference set. For a codon of amino acid , the relative synonymous codon usage is , where the sum is over the codons of . It is 1 when all codons of are used equally. The relative adaptiveness is , where is the largest count among the codons of . Let be the codons of the gene that belong to amino acids with at least two codons; stop codons are left out, and so are ATG and TGG in the standard code. Then
A codon that the reference set never uses would get and make the index of any gene that uses it 0. Sharp and Li give such a codon the count instead.
The algorithm
CAI-WEIGHTS(reference)- 1
X[c] ← the number of times sense codon c occurs in the reference genes, in frame - 2
replace every X[c] = 0 by 1/2 - 3
for each amino acid a: Xmax[a] ← the largest X[c] over the codons c of a - 4
for each sense codon c of amino acid a: w[c] ← X[c] / Xmax[a] CAI(g, w)- 5
S ← 0; L ← 0 - 6
for each codon c of g, in frame, do - 7
if c is a sense codon of an amino acid with two or more codons then - 8
S ← S + ln w[c]; L ← L + 1 - 9
return exp(S / L)
The weights are computed once for an organism and then used for any number of genes. Line L2 comes before line L3, so that an amino acid that never occurs in the reference set gets weight 1 for all its codons instead of a division by zero. Line L8 works in log space: the product of a few hundred weights below 1 underflows a double, but the sum of their logarithms does not.
Example
Take a reference set of two short genes, written as codons:
- GCT GCT GCT GCT AAA AAA GCC
- GCT GCT GCC GCC GCA AAA AAA AAG
Line L1 counts, for alanine, GCT 6, GCC 3, GCA 1 and GCG 0, and for lysine, AAA 4 and AAG 1. Line L2 sets the count of GCG to 1/2. The weights are:
| codon | amino acid | count | ||
|---|---|---|---|---|
| GCT | Ala | 6 | 6 | 1 |
| GCC | Ala | 3 | 6 | 1/2 |
| GCA | Ala | 1 | 6 | 1/6 |
| GCG | Ala | 1/2 | 6 | 1/12 |
| AAA | Lys | 4 | 4 | 1 |
| AAG | Lys | 1 | 4 | 1/4 |
All other amino acids are absent, so all their codons have the count 1/2 and the weight 1. Now score the gene ATG GCC AAG GCT AAA GCG TGG TAA. Line L7 skips ATG and TGG, which have no synonyms, and the stop TAA. The other codons have the weights , whose product is . So
The RSCU form gives the same number. For alanine the mean count is , so and the largest RSCU is , and their ratio is again .
Sharp and Li give a real case. In their Table 1 for E. coli, the first five codons of the ribosomal protein gene rpsU after the start, CCG GTA ATT AAA GTA, have the weights 1.00, 0.495, 0.185, 1.000 and 0.495. The geometric mean of these five is about 0.5386. Over all 70 codons of the gene, without the start codon, the CAI is 0.726. In their Table 2 the ribosomal protein genes of E. coli have CAI values from 0.467 to 0.813, the highest value is 0.849 for lpp, and the lowest is 0.218 for hsdS.
Correctness
After lines L1 and L2, every count is positive. The mean count is the same for all codons of one amino acid, so it cancels in , and line L4 computes as defined, with . The loop of lines L6 to L8 keeps equal to the sum of over the counted codons seen so far, and equal to their number. So line L9 returns , which is also , the ratio of the geometric means of the observed RSCU values and of their largest possible values. Every factor is in , so the CAI is in , and it is 1 exactly when every counted codon has weight 1. The full proof is in the proofs folder.
Proof: The two loops compute the codon adaptation index of Sharp and Lifull
Fix a genetic code. For an amino acid , let be the set of its codons and . Only amino acids with count; in the standard code these are the 18 amino acids other than Met (ATG) and Trp (TGG). Write for the amino acid of a sense codon .
Definitions (Sharp and Li 1987). Let be the number of times codon occurs in the reference set, with replaced by when it is 0. The relative synonymous codon usage is , and the relative adaptiveness is . For a gene whose counted codons are (sense codons of amino acids with ), the index is , where and .
Lemma 1. After lines L1 to L4, for every sense codon , and , with for at least one codon of each amino acid.
Proof. Line L1 counts each codon, and line L2 sets the zero counts to , so after L2 the table holds as defined. Line L3 computes , and line L4 sets . The denominator of RSCU is the same for all codons of one amino acid, so it cancels: . All are positive, so , and the codon where the maximum is reached has .
Lemma 2. When line L9 is reached, is the number of counted codons of the gene and .
Proof. Line L5 sets and . Line L6 visits the codons of the gene in order, and line L7 lets through exactly the counted codons: sense codons of an amino acid with at least two codons. Line L8 adds to and 1 to for each of them, and by Lemma 1 . By induction on the number of visited codons, and are the sum and the count over the counted codons visited so far.
Theorem. If , line L9 returns , and this equals . Moreover , with if and only if every counted codon has .
Proof. By Lemma 2, , since and are inverse and the weights are positive. By Lemma 1, , so the product of the is the product of the RSCU values divided by the product of the maxima, and taking the -th root of both gives . Each factor lies in , so the geometric mean lies in . It is 1 if and only if , and each term is at most 0, so this happens if and only if every term is 0.
Corollary (codon usage form). Let be the number of times the counted codon occurs in the gene. Then with , the sum taken over the codons of the 18 amino acids. So the index depends only on the codon counts of the gene, and it does not change when the codons of the gene are put in another order.
Proof. Group the terms of by codon: the codon contributes once for each of its occurrences.
Running time. Line L1 reads each of the codons of the reference set once, with one table look-up each, in time. Lines L2 to L4 handle the 61 sense codons, a constant. Lines L6 to L8 read the codons of the gene once, with one look-up, one logarithm and one addition each, in time on the real RAM. The tables have a constant number of entries, so the extra space is .
Complexity
- Time. Line L1 reads each of the reference codons once, with one table look-up each, so it takes time. Lines L2 to L4 touch the 61 sense codons, a constant. Lines L6 to L8 read the codons of the gene once, with a look-up, a logarithm and an addition each, so the score takes time. The weights are computed once, and then each further gene costs .
- Space. Two tables of 64 entries, so extra space beyond the input.
- Faster scoring. The logarithms can be stored once in the table. The score of every ORF of a genome then comes from a prefix sum of per frame, one subtraction per ORF.
Properties
- Range. . It is 1 only for a gene that uses an optimal codon at every counted position.
- Depends only on the codon counts. The index is , where is the count of codon in the gene. This is equation [8] of Sharp and Li, a sum over the codons of 18 amino acids. The order of the codons does not matter.
- Normalized for amino acid composition. Each weight compares a codon only with its synonyms, so a gene rich in an amino acid with a strongly preferred codon is not scored higher for that reason alone. Sharp and Li write that gene length has no intrinsic effect on CAI, but that the values of short genes may vary more.
- Relative to the reference set. The weights come from one reference set of one organism. A CAI computed with the weights of E. coli says how well a gene fits E. coli, not how well it fits its own genome.
- Deterministic. There is no randomness and no fitting step: the weights are ratios of counts.
Variants and improvements
- RSCU. The relative synonymous codon usage of each codon, without the geometric mean, is the table that Sharp and Li compute first. It is a descriptive summary of codon usage in a set of genes.
- Effective number of codons. Wright (1990) measures how far the codon usage of a gene is from equal use of synonyms, from 20 (one codon per amino acid) to 61 (all synonyms used equally). It needs no reference set, so it measures bias of any cause, not adaptation to a set of highly expressed genes.
- tRNA adaptation index. dos Reis, Savva and Wernisch (2004) compute the weights from the copy numbers of the tRNA genes of the genome and the wobble rules, and then take the same geometric mean. It needs no list of highly expressed genes.
- Reference sets chosen from the genome. When no list of highly expressed genes is known, a method can start from all genes, compute weights, take the genes with the highest CAI as a new reference set, and repeat until the set does not change.
- Codon models for gene finding. A gene finder replaces the weights by the full probability of each codon in coding DNA, as in the three-periodic Markov chain, and compares it with a model of non-coding DNA. CAI is the simpler score for one gene; the Markov models decide whether a region codes at all.
- Codon optimization. To express a gene in another host, choose for each amino acid the codon with weight 1 in the host. This gives CAI 1. Many design tools also keep some variety of codons and check other features of the sequence, so a CAI of 1 is not the only goal.
When to use it
Use the CAI to compare the expected expression level of the genes of one organism, to find highly expressed genes in a new genome, to check a gene designed for expression in a host, and to find genes that came recently from another genome, whose codon usage does not fit. Compute the weights with a reference set of the same organism, such as the ribosomal protein genes and the elongation factors. Do not compare CAI values computed with different reference sets, and do not use CAI as the only evidence that an ORF is a gene; for that, use gene prediction models.
Pitfalls
- The arithmetic mean. The index is a geometric mean. An arithmetic mean of the weights gives a different and larger number.
- Zero weights. Without the count 1/2 for unused codons, a single rare codon makes the index 0. Some tools use another small count, so their values can differ slightly.
- Underflow. The direct product of the weights of a long gene underflows to 0 in floating point. Add logarithms, as in line L8.
- Codons with no choice. ATG and TGG, and the stop codon, must not count, or a gene with many methionines scores higher. In other genetic codes the set of single-codon amino acids changes; vertebrate mitochondria code TGA as tryptophan.
- Initiation codon. A bacterial gene that starts with GTG or TTG would count that codon as valine or leucine. Remove the start codon before scoring, as Sharp and Li do.
- Frame and length. The gene must be in frame from its first codon, and its length should be a multiple of 3. A frameshift turns the rest of the gene into nonsense codons with low weights.
- Mutation bias. In a genome with a strong GC or AT bias, all genes share the same codon bias for reasons that have nothing to do with expression. The CAI then mixes the two effects.
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.
# 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)
codon_adaptation_index.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/codon-adaptation-index/. The authors are listed in prov/QCTP6D.jsonl.
"""The codon adaptation index (CAI) of Sharp and Li (1987).
The index has two steps:
- relative_adaptiveness(reference) counts the codons of a reference set of
highly expressed genes and gives each sense codon its weight
w = X / X_max, where X is the count of the codon and X_max the count of the
most used codon of the same amino acid. A codon that the reference set
never uses gets the count 1/2, as in the paper. The weights are Fractions.
- cai(gene, w) is the geometric mean of the weights of the codons of the gene.
Codons of amino acids with a single codon (ATG for Met and TGG for Trp in the
standard code), stop codons and codons with a letter other than A, C, G or T
are skipped, because their weight carries no information.
Genes are read in frame 0, three bases at a time; a last part shorter than
three bases is dropped. The caller removes an initiation codon other than ATG
(for example GTG) if it must not count.
"""
from __future__ import annotations
import math
from fractions import Fraction
from typing import Dict, Iterable, Mapping
from bioseq import CODON_TABLE
ZERO_COUNT = Fraction(1, 2)
def _codons(seq: str):
"""The codons of seq in frame 0, in upper case."""
s = seq.upper()
return (s[i:i + 3] for i in range(0, len(s) - 2, 3))
def synonym_families(code: Mapping[str, str] = CODON_TABLE) -> Dict[str, list]:
"""For each amino acid, the list of its codons (stops are left out)."""
fam: Dict[str, list] = {}
for c in sorted(code):
if code[c] != "*":
fam.setdefault(code[c], []).append(c)
return fam
def codon_counts(genes: Iterable[str], code: Mapping[str, str] = CODON_TABLE) -> Dict[str, int]:
"""The number of times each sense codon occurs in the genes, in frame 0."""
X = {c: 0 for c in code if code[c] != "*"}
for g in genes:
for c in _codons(g):
if c in X:
X[c] += 1
return X
def relative_adaptiveness(genes: Iterable[str], code: Mapping[str, str] = CODON_TABLE,
zero_count: Fraction = ZERO_COUNT) -> Dict[str, Fraction]:
"""The weight w of each sense codon, from a reference set of genes."""
X = codon_counts(genes, code) # @line L1
Xf = {c: (Fraction(x) if x > 0 else zero_count) for c, x in X.items()} # @line L2
w: Dict[str, Fraction] = {}
for aa, cods in synonym_families(code).items():
x_max = max(Xf[c] for c in cods) # @line L3
for c in cods:
w[c] = Xf[c] / x_max # @line L4
return w
def counted_codons(gene: str, w: Mapping[str, Fraction], code: Mapping[str, str] = CODON_TABLE):
"""The codons of the gene that enter the index, in order."""
fam = synonym_families(code)
single = {cods[0] for cods in fam.values() if len(cods) == 1}
return [c for c in _codons(gene) if c in w and c not in single]
def cai(gene: str, w: Mapping[str, Fraction], code: Mapping[str, str] = CODON_TABLE) -> float:
"""The codon adaptation index of the gene under the weights w.
Raises ValueError if the gene has no codon that counts.
"""
fam = synonym_families(code)
single = {cods[0] for cods in fam.values() if len(cods) == 1}
S, L = 0.0, 0 # @line L5
for c in _codons(gene): # @line L6
if c in w and c not in single: # @line L7
S += math.log(w[c]) # @line L8
L += 1
if L == 0:
raise ValueError("the gene has no codon that counts")
return math.exp(S / L) # @line L9
test_codon_adaptation_index.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/codon-adaptation-index/. The authors are listed in prov/QCTP6D.jsonl.
"""Tests of the codon adaptation index."""
import math
import random
import unittest
from fractions import Fraction
from bioseq import CODON_TABLE, STOPS
from codon_adaptation_index import (ZERO_COUNT, cai, codon_counts, counted_codons,
relative_adaptiveness, synonym_families)
FAM = synonym_families()
SENSE = sorted(c for c in CODON_TABLE if c not in STOPS)
def random_gene(rng, n, prefer=None, bias=0.0):
"""n random sense codons. With probability bias a codon is the preferred
codon of its amino acid (prefer maps an amino acid to a codon)."""
out = []
for _ in range(n):
c = rng.choice(SENSE)
if prefer is not None and rng.random() < bias:
c = prefer[CODON_TABLE[c]]
out.append(c)
return "".join(out)
def cai_rscu(gene, reference):
"""Sharp and Li eqs [1] and [3] to [5]: CAI_obs / CAI_max from RSCU values."""
X = codon_counts(reference)
Xf = {c: (Fraction(x) if x else ZERO_COUNT) for c, x in X.items()}
rscu, rscu_max = {}, {}
for aa, cods in FAM.items():
mean = sum(Xf[c] for c in cods) / len(cods)
for c in cods:
rscu[c] = Xf[c] / mean
for c in cods:
rscu_max[c] = max(rscu[d] for d in cods)
cods = [c for c in counted_codons(gene, rscu)]
L = len(cods)
obs = math.exp(sum(math.log(rscu[c]) for c in cods) / L)
best = math.exp(sum(math.log(rscu_max[c]) for c in cods) / L)
return obs / best
def cai_usage_table(gene, w):
"""Sharp and Li eq [8]: the sum over the codon usage table of the gene."""
f = {}
for c in counted_codons(gene, w):
f[c] = f.get(c, 0) + 1
L = sum(f.values())
return math.exp(sum(n * math.log(w[c]) for c, n in f.items()) / L)
class TestWeights(unittest.TestCase):
REF = ["GCT" * 4 + "AAA" * 2 + "GCC", "GCT" * 2 + "GCC" * 2 + "GCA" + "AAA" * 2 + "AAG"]
def test_toy_table(self):
w = relative_adaptiveness(self.REF)
self.assertEqual(w["GCT"], 1)
self.assertEqual(w["GCC"], Fraction(1, 2))
self.assertEqual(w["GCA"], Fraction(1, 6))
self.assertEqual(w["GCG"], Fraction(1, 12))
self.assertEqual(w["AAA"], 1)
self.assertEqual(w["AAG"], Fraction(1, 4))
def test_unused_amino_acid_gets_weight_one(self):
w = relative_adaptiveness(self.REF)
for c in FAM["L"] + FAM["M"] + FAM["W"]:
self.assertEqual(w[c], 1)
def test_weights_in_unit_interval_with_a_one_per_family(self):
rng = random.Random(1)
ref = [random_gene(rng, 200) for _ in range(5)]
w = relative_adaptiveness(ref)
self.assertEqual(set(w), set(SENSE))
for aa, cods in FAM.items():
self.assertTrue(all(0 < w[c] <= 1 for c in cods))
self.assertEqual(max(w[c] for c in cods), 1)
def test_stops_and_unknown_codons_are_not_counted(self):
X = codon_counts(["ATGTAANNNGCTTGAGC"])
self.assertEqual(sum(X.values()), 2)
self.assertEqual(X["ATG"], 1)
self.assertEqual(X["GCT"], 1)
class TestIndex(unittest.TestCase):
def test_page_example(self):
w = relative_adaptiveness(TestWeights.REF)
gene = "ATGGCCAAGGCTAAAGCGTGGTAA"
self.assertEqual(counted_codons(gene, w), ["GCC", "AAG", "GCT", "AAA", "GCG"])
self.assertAlmostEqual(cai(gene, w), 96 ** (-1 / 5), places=12)
self.assertAlmostEqual(cai(gene, w), 0.40137, places=5)
def test_rpsU_start_with_table1_weights(self):
# The first five codons of E. coli rpsU after the start, with the w values of
# Sharp and Li (1987), Table 1: CCG 1.00, GTA 0.495, ATT 0.185, AAA 1.000.
w = {c: Fraction(1) for c in SENSE}
w["GTA"], w["ATT"] = Fraction("0.495"), Fraction("0.185")
got = cai("CCGGTAATTAAAGTA", w)
self.assertAlmostEqual(got, (0.495 * 0.185 * 0.495) ** 0.2, places=12)
self.assertAlmostEqual(got, 0.5386, places=4)
def test_power_equals_exact_product(self):
rng = random.Random(2)
ref = [random_gene(rng, 150) for _ in range(4)]
w = relative_adaptiveness(ref)
for _ in range(20):
gene = random_gene(rng, rng.randrange(1, 40))
cods = counted_codons(gene, w)
if not cods:
continue
prod = Fraction(1)
for c in cods:
prod *= w[c]
self.assertTrue(math.isclose(cai(gene, w) ** len(cods), float(prod), rel_tol=1e-9))
def test_three_formulas_agree(self):
rng = random.Random(3)
for _ in range(10):
ref = [random_gene(rng, rng.randrange(20, 120)) for _ in range(3)]
w = relative_adaptiveness(ref)
gene = random_gene(rng, 60)
a = cai(gene, w)
self.assertAlmostEqual(a, cai_rscu(gene, ref), places=12)
self.assertAlmostEqual(a, cai_usage_table(gene, w), places=12)
def test_range_and_optimal_gene(self):
rng = random.Random(4)
w = relative_adaptiveness([random_gene(rng, 300) for _ in range(3)])
best = {aa: max(cods, key=lambda c: (w[c], c)) for aa, cods in FAM.items()}
optimal = "".join(best[CODON_TABLE[c]] for c in _codons_of(random_gene(rng, 50)))
self.assertAlmostEqual(cai(optimal, w), 1.0, places=12)
for _ in range(20):
v = cai(random_gene(rng, 30), w)
self.assertTrue(0 < v <= 1)
def test_order_of_codons_does_not_matter(self):
rng = random.Random(5)
w = relative_adaptiveness([random_gene(rng, 200)])
cods = _codons_of(random_gene(rng, 40))
a = cai("".join(cods), w)
rng.shuffle(cods)
self.assertAlmostEqual(a, cai("".join(cods), w), places=12)
def test_single_codon_amino_acids_and_stops_skipped(self):
w = relative_adaptiveness(TestWeights.REF)
self.assertAlmostEqual(cai("GCC", w), 0.5, places=12)
self.assertAlmostEqual(cai("ATGGCCTGGTGGTAGNNN", w), 0.5, places=12)
with self.assertRaises(ValueError):
cai("ATGTGGTAA", w)
def test_biased_genes_score_higher(self):
rng = random.Random(6)
prefer = {aa: rng.choice(cods) for aa, cods in FAM.items()}
ref = [random_gene(rng, 300, prefer, 0.8) for _ in range(5)]
w = relative_adaptiveness(ref)
high = [cai(random_gene(rng, 200, prefer, 0.8), w) for _ in range(10)]
low = [cai(random_gene(rng, 200), w) for _ in range(10)]
self.assertGreater(min(high), max(low))
def _codons_of(seq):
return [seq[i:i + 3] for i in range(0, len(seq) - 2, 3)]
if __name__ == "__main__":
unittest.main()
History
Sharp and Li (1987) defined the index and gave the reference sets and the weights for E. coli (27 very highly expressed genes, among them 17 ribosomal protein genes, the elongation factors, recA and dnaK) and for yeast (24 genes). They showed that CAI values are correlated with the expression levels of genes in both organisms. Wright (1990) added the effective number of codons, a measure that needs no reference set, and dos Reis, Savva and Wernisch (2004) took the same geometric mean over weights derived from tRNA gene copy numbers.
References
- Paul M. Sharp and Wen-Hsiung Li, The codon adaptation index, a measure of directional synonymous codon usage bias, and its potential applications, Nucleic Acids Research 15(3), 1987, pp. 1281 to 1295; equations [1] to [8], the count 0.5 for codons absent from the reference set, Table 1 (p. 1284) with RSCU and w for E. coli and yeast, and Table 2 with CAI values of genes
- Frank Wright, The 'effective number of codons' used in a gene, Gene 87(1), 1990, pp. 23 to 29, the definition of the effective number of codons, from 20 to 61
- Mario dos Reis, Renos Savva and Lorenz Wernisch, Solving the riddle of codon usage preferences, a test for translational selection, Nucleic Acids Research 32(17), 2004, pp. 5036 to 5044, the tRNA adaptation index, a geometric mean of relative adaptiveness values computed from tRNA gene copy numbers
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QCTP6D Edit this page History Report an error Markdown