Algorithm Search⌘K

Algorithmintro

CpG island detection

Also called CpG island HMM.

Find stretches of DNA rich in the dinucleotide CG, with a two-state HMM decoded by the Viterbi algorithm, or with a sliding window test of GC content and observed over expected CpG.

Time
Θ(n) worst · average · best
Space
Θ(n) extra
Where
n = the length of the sequence; w = the window length of the window rule
Properties
deterministicexactofflineiterative

A CpG island is a stretch of DNA, usually a few hundred to a few thousand bases long, where the dinucleotide CG (a C followed by a G on the same strand, written CpG) is much more common than in the rest of the genome. In vertebrate DNA the C of a CG pair is often methylated, and a methylated C mutates to T at a high rate, so CG pairs are rare in most of the genome. Near the promoters of many genes the C is not methylated, and the CG pairs stay. Finding these islands is a common first step in genome annotation, because they mark the 5' ends of many genes. There are two standard methods. The window rule of Gardiner-Garden and Frommer (1987) marks every window of 200 bases with a GC content above 50 percent and a ratio of observed to expected CG above 0.6. The HMM method of Durbin et al. (1998) models the sequence with a hidden Markov model with an island state and a background state, and labels each base by the most probable state path, found with the Viterbi algorithm.

In plain words

Islands look different from the rest of the DNA: they have more C and G, and the pair CG is not rare in them. The window method slides a window of 200 letters along the sequence, counts C, G and CG in it, and keeps the windows that are rich in C and G and have enough CG. Touching or overlapping windows that pass are joined into one island. The HMM method imagines a machine that is either inside an island or outside one and writes one letter at a time, with different letter odds in the two modes and a small chance to switch modes. For the given sequence it finds the most likely list of modes, letter by letter, and the runs of "inside" are the islands.

The problem

Input. A DNA sequence x=x1⋯xnx = x_1 \cdots x_n over {A,C,G,T}\{A, C, G, T\}. For the HMM method, a model with the two states ++ (island) and −- (background): start probabilities πk\pi_k, transition probabilities ajka_{jk}, and emission probabilities ek(b)e_k(b) for the first base and ek(b∣p)e_k(b \mid p) for a base bb after the base pp. For the window rule, a window length ww and two thresholds gg and rr, by default w=200w = 200, g=0.5g = 0.5 and r=0.6r = 0.6.

Output. A list of disjoint intervals of xx, the islands.

For the HMM method, the islands are the maximal runs of ++ in a state path q∗q^* that maximizes

P(x,q)=πq1eq1(x1)∏i=2naqi−1qi eqi(xi∣xi−1).P(x, q) = \pi_{q_1} e_{q_1}(x_1) \prod_{i=2}^{n} a_{q_{i-1} q_i} \, e_{q_i}(x_i \mid x_{i-1}).

An emission that depends on the previous base lets each state hold a full first-order Markov chain of bases, so that the background state can make CG rare while C and G alone are common. This two-state model is the same as the eight-state model of Durbin et al., which has the states A+,C+,G+,T+A^+, C^+, G^+, T^+ and A−,C−,G−,T−A^-, C^-, G^-, T^-, each emitting its own base.

For the window rule, a window of ww bases with CC cytosines, GG guanines and DD CG pairs is marked if (C+G)/w>g(C + G)/w > g and O/E=D w/(C G)>r\mathrm{O/E} = D \, w / (C \, G) > r. The ratio O/E\mathrm{O/E} compares the observed number of CG pairs with the number CG/wC G / w expected if the bases were independent. The islands are the maximal unions of marked windows that overlap or touch.

The algorithm

  1. VITERBI-CPG(x, model)
  2. 1for each state k in {+, -}: V[k] ← ln π_k + ln e_k(x_1)
  3. 2for i ← 2 to n do
  4. 3for each state k in {+, -} do
  5. 4ptr[i][k] ← the state j with the largest V[j] + ln a_jk
  6. 5V'[k] ← V[j] + ln a_jk + ln e_k(x_i | x_{i-1}) for j = ptr[i][k]
  7. 6V ← V'
  8. 7q_n ← the state k with the largest V[k]
  9. 8for i ← n down to 2: q_{i-1} ← ptr[i][q_i]
  10. 9return the maximal runs of + in q_1 ... q_n
  11. WINDOW-CPG(x, w, g, r)
  12. 10for each window x[i, i + w), keeping the counts C, G and D up to date in O(1) per shift do
  13. 11mark the window if (C + G) / w > g and D · w / (C · G) > r
  14. 12return the unions of marked windows that overlap or touch

The decoder works with logarithms, so a sequence of a million bases does not underflow; see the log-sum-exp trick for the same issue in the forward-backward algorithm. When the window moves one base to the right, it loses one base and one possible CG pair on the left and gains one of each on the right, so line L10 updates the three counts with a few additions instead of recounting.

Example

Take a toy model whose emissions do not depend on the previous base. The island state emits A and T with probability 0.1 each and C and G with 0.4 each. The background state emits A and T with 0.3 each and C and G with 0.2 each. Both start probabilities are 0.5, a state stays with probability 0.8 and switches with 0.2. Decode x=ATATCGCGCGTATAx = \mathrm{ATATCGCGCGTATA} (14 bases). The table gives V[+]V[+] and V[−]V[-] after each base, in natural logarithms, rounded to three places. A note "from" gives the pointer of a state when it is the other state.

ii base V[+]V[+] V[−]V[-]
1 A −2.996-2.996 −1.897-1.897
2 T −5.521-5.521 −3.324-3.324
3 A −7.236-7.236 (from −-) −4.751-4.751
4 T −8.663-8.663 (from −-) −6.178-6.178
5 C −8.704-8.704 (from −-) −8.011-8.011
6 G −9.844-9.844 −9.844-9.844
7 C −10.983-10.983 −11.676-11.676
8 G −12.123-12.123 −13.509-13.509
9 C −13.262-13.262 −15.341-15.341
10 G −14.401-14.401 −16.481-16.481 (from ++)
11 T −16.927-16.927 −17.215-17.215 (from ++)
12 A −19.453-19.453 −18.642-18.642
13 T −21.979-21.979 −20.069-20.069
14 A −23.981-23.981 (from −-) −21.496-21.496

At i=14i = 14 the larger value is V[−]=−21.496V[-] = -21.496. Following the pointers back from −- at base 14 stays in −- down to base 11, whose pointer leads to ++ at base 10, then stays in ++ down to base 5, whose pointer leads to −- at base 4. So the best path is −−−−++++++−−−−----++++++---- and the island is CGCGCG, bases 5 to 10 (the interval [4,10)[4, 10) from 0). Its log probability −21.496-21.496 beats −22.882-22.882 for the path with no island: the six C and G bases gain 6ln⁡2≈4.166 \ln 2 \approx 4.16 in the island state, more than the cost 2ln⁡4≈2.772 \ln 4 \approx 2.77 of the two switches. A shorter island of four C and G bases would gain only 2.772.77 and would tie with the switches.

The window rule, scaled down to w=6w = 6 with g=0.5g = 0.5 and r=0.6r = 0.6, on ATATATCGCGCGATATAT marks the windows that start at positions 4 to 8 (from 0). For example, ATCGCG has C=2C = 2, G=2G = 2 and D=2D = 2, so its GC fraction is 4/64/6 and its ratio is 2⋅6/4=32 \cdot 6 / 4 = 3. The window GCGATA starts at 9 and has only three C and G. The union of the marked windows is [4,14)[4, 14), which includes two A and T bases on each side of the CG run: the window rule blurs the edges of an island by up to a window length.

Correctness

For the HMM, let vi(k)v_i(k) be the largest log probability of the first ii bases over the paths that end in state kk. A best path that ends in kk at ii extends a best path that ends at i−1i - 1 in some state jj, because the added term ln⁡ajk+ln⁡ek(xi∣xi−1)\ln a_{jk} + \ln e_k(x_i \mid x_{i-1}) depends only on jj and kk. So vi(k)=max⁡j(vi−1(j)+ln⁡ajk)+ln⁡ek(xi∣xi−1)v_i(k) = \max_j (v_{i-1}(j) + \ln a_{jk}) + \ln e_k(x_i \mid x_{i-1}), which is lines L4 and L5, and line L1 is the case i=1i = 1. Line L7 takes the best end state, and the pointers of line L8 rebuild a path that reaches max⁡kvn(k)\max_k v_n(k), the largest value of ln⁡P(x,q)\ln P(x, q) over all paths. For the window rule, each shift removes exactly one base and one candidate CG pair and adds one of each, so the counts of line L11 are those of the window, and joining marked windows in order of their start gives the maximal unions. The full proof is in the proofs folder.

Proof: The Viterbi decoder and the window scan find the CpG islands they definefull

Let x=x1⋯xnx = x_1 \cdots x_n be a sequence over {A,C,G,T}\{A, C, G, T\} with n≥1n \ge 1. The model has the states Q={+,−}Q = \{+, -\}, the start probabilities πk\pi_k, the transition probabilities ajka_{jk}, the first-base emissions ek(b)e_k(b) and the conditional emissions ek(b∣p)e_k(b \mid p). For a state path q=q1⋯qnq = q_1 \cdots q_n,

ln⁡P(x,q)=ln⁡πq1+ln⁡eq1(x1)+∑i=2n(ln⁡aqi−1qi+ln⁡eqi(xi∣xi−1)),\ln P(x, q) = \ln \pi_{q_1} + \ln e_{q_1}(x_1) + \sum_{i=2}^{n} \big(\ln a_{q_{i-1} q_i} + \ln e_{q_i}(x_i \mid x_{i-1})\big),

with ln⁡0=−∞\ln 0 = -\infty. The island calls of the HMM are the maximal runs of ++ in a path q∗q^* that maximizes ln⁡P(x,q)\ln P(x, q).

The Viterbi decoder

For 1≤i≤n1 \le i \le n and k∈Qk \in Q, let vi(k)v_i(k) be the largest value of ln⁡P(x1⋯xi,q1⋯qi)\ln P(x_1 \cdots x_i, q_1 \cdots q_i) over the paths of length ii with qi=kq_i = k, where the prefix probability is the same sum stopped at ii.

Lemma 1. After line L1, V[k]=v1(k)V[k] = v_1(k). After the pass of lines L3 to L6 for position ii, V[k]=vi(k)V[k] = v_i(k), and ptr[i][k]\mathit{ptr}[i][k] is a state jj with vi−1(j)+ln⁡ajk=max⁡j′(vi−1(j′)+ln⁡aj′k)v_{i-1}(j) + \ln a_{jk} = \max_{j'} (v_{i-1}(j') + \ln a_{j'k}).

Proof. For i=1i = 1 the only path of length 1 that ends in kk is kk itself, and line L1 sets V[k]=ln⁡πk+ln⁡ek(x1)V[k] = \ln \pi_k + \ln e_k(x_1). Assume the claim for i−1i - 1. A path of length ii that ends in kk is a path of length i−1i - 1 that ends in some jj, followed by kk, and its value is the value of the shorter path plus ln⁡ajk+ln⁡ek(xi∣xi−1)\ln a_{jk} + \ln e_k(x_i \mid x_{i-1}). The added term depends only on jj and kk, so the best path that ends in kk extends a best path that ends in its state jj, and

vi(k)=max⁡j(vi−1(j)+ln⁡ajk)+ln⁡ek(xi∣xi−1).v_i(k) = \max_{j} \big(v_{i-1}(j) + \ln a_{jk}\big) + \ln e_k(x_i \mid x_{i-1}).

Line L4 picks a jj that reaches this maximum, with V[j]=vi−1(j)V[j] = v_{i-1}(j) by the induction hypothesis, and line L5 computes the right side. Line L6 replaces VV only after both states are done, so line L5 always reads the values of position i−1i - 1. □\square

Lemma 2. The path qq built by lines L7 and L8 satisfies ln⁡P(x,q)=max⁡kvn(k)=max⁡q′ln⁡P(x,q′)\ln P(x, q) = \max_k v_n(k) = \max_{q'} \ln P(x, q').

Proof. Line L7 picks qnq_n with vn(qn)=max⁡kvn(k)v_n(q_n) = \max_k v_n(k), and every path ends in some state, so this is the largest value of ln⁡P(x,q′)\ln P(x, q'). Line L8 sets qi−1=ptr[i][qi]q_{i-1} = \mathit{ptr}[i][q_i]. We show by induction on ii, from nn down to 1, that the path q1⋯qiq_1 \cdots q_i obtained by following the pointers from qiq_i has prefix value vi(qi)v_i(q_i). For i=1i = 1 this is Lemma 1. For i>1i > 1, the pointer j=qi−1j = q_{i-1} satisfies vi(qi)=vi−1(j)+ln⁡ajqi+ln⁡eqi(xi∣xi−1)v_i(q_i) = v_{i-1}(j) + \ln a_{j q_i} + \ln e_{q_i}(x_i \mid x_{i-1}) by Lemma 1, and by the induction hypothesis the prefix up to i−1i - 1 has value vi−1(j)v_{i-1}(j), so the prefix up to ii has value vi(qi)v_i(q_i). At i=ni = n this is the claim. □\square

Line L9 reads off the maximal runs of ++ of this path, so the HMM calls are the islands of a most probable path. When several paths tie, the decoder returns the one given by its tie rule (the state listed first wins); any of them is a correct answer.

The window rule

For a window x[i,i+w)x[i, i + w) (0-based, half-open), let CiC_i and GiG_i be its numbers of C and G, and DiD_i its number of positions jj with i≤j<i+w−1i \le j < i + w - 1, xj=Cx_j = C and xj+1=Gx_{j+1} = G. The window is marked when (Ci+Gi)/w>g(C_i + G_i)/w > g and Di w/(CiGi)>rD_i \, w / (C_i G_i) > r, with the ratio taken as 0 if CiGi=0C_i G_i = 0.

Lemma 3. At line L11 for window ii, the counters hold CiC_i, GiG_i and DiD_i.

Proof. For i=0i = 0 they are counted directly. Going from window i−1i - 1 to window ii removes the base xi−1x_{i-1} and adds the base xi+w−1x_{i + w - 1}, so CC and GG change by the indicator of the added base minus that of the removed one. The CG pairs of window i−1i - 1 start at j=i−1,…,i+w−3j = i - 1, \ldots, i + w - 3, and those of window ii at j=i,…,i+w−2j = i, \ldots, i + w - 2. So the pair at j=i−1j = i - 1 leaves and the pair at j=i+w−2j = i + w - 2 enters, and the code subtracts and adds exactly these two indicators. □\square

Lemma 4. The intervals returned are exactly the maximal intervals of the union of the marked windows, where two marked windows that overlap or touch are joined.

Proof. The marked windows are visited in increasing order of start. The last interval of the output is the union of a group of marked windows, and it ends at ee, the largest end in the group, which is the end of the last window added because all windows have the same length. A new marked window [i,i+w)[i, i + w) with i≤ei \le e overlaps or touches it, so the union is [start,i+w)[\text{start}, i + w), which the code stores. If i>ei > e, no later window starts before ii, so no later window can touch the old interval, and the old interval is maximal. □\square

Running time

Lines L2 to L6 run n−1n - 1 times, each with ∣Q∣2=4|Q|^2 = 4 additions and comparisons, and lines L7 and L8 take nn steps, so the decoder takes Θ(n∣Q∣2)=Θ(n)\Theta(n |Q|^2) = \Theta(n) time and Θ(n)\Theta(n) space for the pointers. The window scan spends Θ(w)\Theta(w) time on the first window and O(1)O(1) on each of the other n−wn - w windows, so Θ(n)\Theta(n) time in total and O(1)O(1) extra space besides the output.

Complexity

  • Time. The decoder does ∣Q∣2=4|Q|^2 = 4 steps for each base, so Θ(n)\Theta(n). With KK states it would be Θ(nK2)\Theta(n K^2). The window rule spends Θ(w)\Theta(w) on the first window and O(1)O(1) on each shift, so Θ(n)\Theta(n).
  • Space. The decoder keeps two pointers per base for the traceback, Θ(n)\Theta(n). The window rule needs O(1)O(1) beyond the output. If memory is short, the decoder can keep pointers only at checkpoints and recompute the rest, for O(n)O(\sqrt{n}) space and about twice the time.

Properties

  • Exact for its model. The decoder returns a path of largest probability. The quality of the islands depends on the model, not on the decoder.
  • Global decisions. The transition probabilities set how long islands and gaps tend to be. A state that stays with probability aa has runs of mean length 1/(1−a)1/(1 - a), so a++=0.999a_{++} = 0.999 gives islands of about 1000 bases.
  • The window rule is local. It looks only inside one window, so its result does not depend on what is far away. Its islands start and end at window edges and include up to w−1w - 1 bases of flanking DNA.
  • Both methods use the same signal. The GC content and the O/E ratio of CG are what the island state of the HMM models, through its emission probabilities.

Variants and improvements

  • Posterior decoding. The forward-backward algorithm gives, for each base, the probability that it is in an island. This gives a confidence for each base, and the bases with posterior above 0.5 can differ from the Viterbi path.
  • Training the model. With labeled islands, the emission and transition probabilities are frequencies of the labeled data, the maximum likelihood estimates. Without labels, Baum-Welch fits them to the sequence itself.
  • Stricter criteria. Takai and Jones (2002) asked for more than 500 bases, a GC content of 55 percent or more and an O/E ratio of 0.65. On human chromosomes 21 and 22 this removed most of the hits in Alu repeats and left a number of islands closer to the number of genes.
  • Discrimination of known regions. To decide whether a given short sequence is an island, compare its log probability under the island Markov chain with that under the background chain. This log-odds score is the first method of Durbin et al., chapter 3, before the HMM.
  • Masking repeats first. Repeats such as Alu elements are GC rich and pass the window rule. Many pipelines run repeat masking before the search.

When to use it

Use CpG island detection to annotate vertebrate genomes, to find candidate promoters, and to choose regions for studies of DNA methylation. Use the window rule when you want results that match a published definition, such as the criteria of Gardiner-Garden and Frommer or of Takai and Jones. Use the HMM when you want islands with sharp edges, posterior probabilities per base, or a model that you can train on your own genome. The method relies on the depletion of CG in the rest of the genome. Takai and Jones (2002) found strong depletion in the human genome but only slight depletion in Drosophila melanogaster and Saccharomyces cerevisiae, so in such genomes islands stand out much less.

Pitfalls

  • Expected CpG. The ratio O/E uses CG/wC G / w as the expected count of CG pairs. Other formulas for the expected count are also in use, and they give other values when C and G are unbalanced. Say which formula is used.
  • Strict and non-strict thresholds. "Above 50 percent" and "at least 50 percent" give different islands at the edges. Check the definition you need to match.
  • Probabilities without logarithms. A product of nn probabilities underflows for nn in the thousands. Work with logarithms throughout.
  • Zero probabilities. A model trained by counting can have ek(b∣p)=0e_k(b \mid p) = 0, which forbids a state at some bases forever. Add pseudocounts before taking logarithms.
  • Self-transition probabilities set the island length. With a++a_{++} too small, the decoder breaks islands into pieces; with a−−a_{--} too close to 1, it misses short islands. Fit them, or check the length distribution of the result.
  • Lower case and N. Soft-masked genomes use lower case for repeats; upper-case first, or decide to skip them. A run of N must be cut out or given its own state.

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)
cpg_island_detection.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cpg-island-detection/. The authors are listed in prov/0S3A9K.jsonl.
"""CpG island detection with a two-state HMM and with a sliding window rule.

The HMM has the states "+" (island) and "-" (background). Each state emits
the next base with a probability that may depend on the previous base, so it
is the two-state form of the eight-state CpG model of Durbin, Eddy, Krogh and
Mitchison (1998, chapter 3). A model is CpgModel(start, trans, first, cond):
- start[k] is the probability that the first base is in state k;
- trans[j][k] is the probability of the step from state j to state k;
- first[k][b] is the probability that state k emits b as the first base;
- cond[k][p][b] is the probability that state k emits b after the base p.

viterbi_cpg works in log space, so long sequences do not underflow. Ties go to
the state that comes first in STATES.

window_islands is the rule of Gardiner-Garden and Frommer (1987): every window
of w bases with GC fraction above min_gc and observed over expected CpG above
min_oe is marked, and overlapping marked windows are joined.

All intervals are 0-based and half-open.
"""

from __future__ import annotations

import math
from collections import namedtuple
from typing import Dict, List, Tuple

STATES = ("+", "-")
BASES = "ACGT"

CpgModel = namedtuple("CpgModel", ["start", "trans", "first", "cond"])


def _log(p: float) -> float:
    return math.log(p) if p > 0 else -math.inf


def composition_model(gc_plus: float = 0.65, gc_minus: float = 0.4, cg_minus: float = 0.25,
                      stay_plus: float = 0.999, stay_minus: float = 0.9999) -> CpgModel:
    """A simple model for tests and examples, not fitted to any genome.

    The island state emits C and G with probability gc_plus/2 each. The
    background state emits C and G with probability gc_minus/2 each, but after
    a C it multiplies the probability of G by cg_minus and renormalizes, which
    makes CG rare in the background, as in vertebrate DNA.
    """
    def comp(gc):
        return {"A": (1 - gc) / 2, "C": gc / 2, "G": gc / 2, "T": (1 - gc) / 2}

    plus, minus = comp(gc_plus), comp(gc_minus)
    after_c = dict(minus)
    after_c["G"] *= cg_minus
    z = sum(after_c.values())
    after_c = {b: v / z for b, v in after_c.items()}
    cond = {"+": {p: dict(plus) for p in BASES},
            "-": {p: (after_c if p == "C" else dict(minus)) for p in BASES}}
    trans = {"+": {"+": stay_plus, "-": 1 - stay_plus}, "-": {"+": 1 - stay_minus, "-": stay_minus}}
    return CpgModel({"+": 0.5, "-": 0.5}, trans, {"+": plus, "-": minus}, cond)


def path_log_prob(seq: str, path: str, model: CpgModel) -> float:
    """ln P(seq, path) under the model."""
    lp = _log(model.start[path[0]]) + _log(model.first[path[0]][seq[0]])
    for i in range(1, len(seq)):
        lp += _log(model.trans[path[i - 1]][path[i]]) + _log(model.cond[path[i]][seq[i - 1]][seq[i]])
    return lp


def viterbi_cpg(seq: str, model: CpgModel) -> Tuple[float, str]:
    """The most probable state path, as (ln P(seq, path), path string over "+-")."""
    s = seq.upper()
    if not s or any(c not in BASES for c in s):
        raise ValueError("seq must be a non-empty string over ACGT")
    lt = {j: {k: _log(model.trans[j][k]) for k in STATES} for j in STATES}
    V = {k: _log(model.start[k]) + _log(model.first[k][s[0]]) for k in STATES}  # @line L1
    ptr: List[Dict[str, str]] = [{}]
    for i in range(1, len(s)):  # @line L2
        new, back = {}, {}
        for k in STATES:  # @line L3
            best = max(STATES, key=lambda j: (V[j] + lt[j][k], -STATES.index(j)))  # @line L4
            back[k] = best
            new[k] = V[best] + lt[best][k] + _log(model.cond[k][s[i - 1]][s[i]])  # @line L5
        V = new  # @line L6
        ptr.append(back)
    q = max(STATES, key=lambda k: (V[k], -STATES.index(k)))  # @line L7
    score = V[q]
    path = [q]
    for i in range(len(s) - 1, 0, -1):  # @line L8
        q = ptr[i][q]
        path.append(q)
    path.reverse()
    return score, "".join(path)


def runs(path: str, state: str = "+") -> List[Tuple[int, int]]:
    """The maximal runs of state in path, as half-open intervals."""
    out, i = [], 0
    while i < len(path):
        if path[i] == state:
            j = i
            while j < len(path) and path[j] == state:
                j += 1
            out.append((i, j))
            i = j
        else:
            i += 1
    return out


def hmm_islands(seq: str, model: CpgModel, min_len: int = 1) -> List[Tuple[int, int]]:
    """The islands of the Viterbi path that have at least min_len bases."""
    _, path = viterbi_cpg(seq, model)
    return [r for r in runs(path) if r[1] - r[0] >= min_len]  # @line L9


def obs_exp_cpg(c: int, g: int, cg: int, n: int) -> float:
    """Observed over expected CpG, CG * n / (C * G); 0.0 if C or G is 0."""
    return cg * n / (c * g) if c and g else 0.0


def window_flags(seq: str, w: int = 200, min_gc: float = 0.5, min_oe: float = 0.6) -> List[bool]:
    """flags[i] is True if the window seq[i:i + w] passes both tests."""
    s = seq.upper()
    if w < 2 or w > len(s):
        return []
    c, g = s[:w].count("C"), s[:w].count("G")
    cg = sum(1 for j in range(w - 1) if s[j] == "C" and s[j + 1] == "G")
    flags = []
    for i in range(len(s) - w + 1):  # @line L10
        if i > 0:
            out, inn = s[i - 1], s[i + w - 1]
            c += (inn == "C") - (out == "C")
            g += (inn == "G") - (out == "G")
            cg += (s[i + w - 2] == "C" and inn == "G") - (out == "C" and s[i] == "G")
        flags.append((c + g) / w > min_gc and obs_exp_cpg(c, g, cg, w) > min_oe)  # @line L11
    return flags


def window_islands(seq: str, w: int = 200, min_gc: float = 0.5,
                   min_oe: float = 0.6) -> List[Tuple[int, int]]:
    """The unions of overlapping marked windows, as half-open intervals."""
    out: List[Tuple[int, int]] = []
    for i, ok in enumerate(window_flags(seq, w, min_gc, min_oe)):
        if ok:
            if out and i <= out[-1][1]:
                out[-1] = (out[-1][0], i + w)
            else:
                out.append((i, i + w))
    return out  # @line L12
test_cpg_island_detection.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cpg-island-detection/. The authors are listed in prov/0S3A9K.jsonl.
"""Tests of the CpG island HMM and of the window rule."""

import itertools
import math
import random
import unittest

from bioseq import random_dna
from cpg_island_detection import (BASES, STATES, CpgModel, composition_model, hmm_islands,
                                  obs_exp_cpg, path_log_prob, runs, viterbi_cpg,
                                  window_flags, window_islands)


def random_dist(rng, keys):
    v = [rng.random() + 0.05 for _ in keys]
    z = sum(v)
    return {k: x / z for k, x in zip(keys, v)}


def random_model(rng):
    return CpgModel(random_dist(rng, STATES),
                    {j: random_dist(rng, STATES) for j in STATES},
                    {k: random_dist(rng, BASES) for k in STATES},
                    {k: {p: random_dist(rng, BASES) for p in BASES} for k in STATES})


def toy_model():
    """The model of the page example: no dependence on the previous base."""
    plus = {"A": 0.1, "C": 0.4, "G": 0.4, "T": 0.1}
    minus = {"A": 0.3, "C": 0.2, "G": 0.2, "T": 0.3}
    return CpgModel({"+": 0.5, "-": 0.5},
                    {"+": {"+": 0.8, "-": 0.2}, "-": {"+": 0.2, "-": 0.8}},
                    {"+": plus, "-": minus},
                    {"+": {p: plus for p in BASES}, "-": {p: minus for p in BASES}})


def brute_window_flags(s, w, min_gc, min_oe):
    out = []
    for i in range(len(s) - w + 1):
        x = s[i:i + w]
        c, g = x.count("C"), x.count("G")
        cg = sum(1 for j in range(w - 1) if x[j:j + 2] == "CG")
        oe = cg * w / (c * g) if c and g else 0.0
        out.append((c + g) / w > min_gc and oe > min_oe)
    return out


class TestViterbi(unittest.TestCase):
    def test_against_all_paths(self):
        rng = random.Random(11)
        for _ in range(40):
            model = random_model(rng)
            n = rng.randrange(1, 9)
            seq = "".join(rng.choice(BASES) for _ in range(n))
            score, path = viterbi_cpg(seq, model)
            best = max(path_log_prob(seq, "".join(p), model)
                       for p in itertools.product(STATES, repeat=n))
            self.assertAlmostEqual(score, best, places=9)
            self.assertAlmostEqual(path_log_prob(seq, path, model), score, places=9)

    def test_page_example(self):
        score, path = viterbi_cpg("ATATCGCGCGTATA", toy_model())
        self.assertEqual(path, "----++++++----")
        self.assertEqual(runs(path), [(4, 10)])
        self.assertAlmostEqual(score, path_log_prob("ATATCGCGCGTATA", path, toy_model()), places=12)

    def test_long_sequence_does_not_underflow(self):
        rng = random.Random(12)
        seq = random_dna(rng, 20000, 0.45)
        score, path = viterbi_cpg(seq, composition_model())
        self.assertTrue(math.isfinite(score))
        self.assertEqual(len(path), 20000)

    def test_finds_planted_island(self):
        rng = random.Random(13)
        left, isl, right = random_dna(rng, 3000, 0.4), random_dna(rng, 800, 0.7), random_dna(rng, 3000, 0.4)
        seq = left + isl + right
        found = hmm_islands(seq, composition_model(), min_len=200)
        self.assertEqual(len(found), 1)
        a, b = found[0]
        overlap = min(b, 3800) - max(a, 3000)
        self.assertGreater(overlap, 0.8 * 800)
        self.assertLess((b - a) - overlap, 200)

    def test_rejects_bad_letters(self):
        with self.assertRaises(ValueError):
            viterbi_cpg("ACGN", toy_model())
        with self.assertRaises(ValueError):
            viterbi_cpg("", toy_model())


class TestRuns(unittest.TestCase):
    def test_runs(self):
        self.assertEqual(runs("++--+-++"), [(0, 2), (4, 5), (6, 8)])
        self.assertEqual(runs("----"), [])
        self.assertEqual(runs("+"), [(0, 1)])


class TestWindow(unittest.TestCase):
    def test_obs_exp(self):
        # CGCGAATT: C 2, G 2, CG 2, n 8, so 2 * 8 / (2 * 2) = 4.
        self.assertEqual(obs_exp_cpg(2, 2, 2, 8), 4.0)
        self.assertEqual(obs_exp_cpg(0, 3, 0, 8), 0.0)

    def test_sliding_counts_match_direct_counts(self):
        rng = random.Random(14)
        for _ in range(30):
            n = rng.randrange(2, 60)
            s = random_dna(rng, n, rng.random())
            w = rng.randrange(2, n + 1)
            gc, oe = rng.choice([0.3, 0.5, 0.6]), rng.choice([0.2, 0.6, 1.0])
            self.assertEqual(window_flags(s, w, gc, oe), brute_window_flags(s, w, gc, oe))

    def test_islands_are_unions_of_marked_windows(self):
        rng = random.Random(15)
        for _ in range(30):
            s = random_dna(rng, rng.randrange(10, 80), 0.55)
            w = rng.randrange(2, 10)
            flags = brute_window_flags(s, w, 0.5, 0.6)
            covered = [False] * len(s)
            for i, ok in enumerate(flags):
                if ok:
                    for j in range(i, i + w):
                        covered[j] = True
            got = window_islands(s, w, 0.5, 0.6)
            self.assertEqual(runs("".join("+" if x else "-" for x in covered)), got)

    def test_page_window_example(self):
        s = "ATATATCGCGCGATATAT"
        self.assertEqual(window_islands(s, 6, 0.5, 0.6), [(4, 14)])

    def test_planted_island_with_window_rule(self):
        rng = random.Random(16)
        seq = random_dna(rng, 3000, 0.35) + random_dna(rng, 800, 0.7) + random_dna(rng, 3000, 0.35)
        found = [r for r in window_islands(seq) if r[1] - r[0] >= 300]
        self.assertEqual(len(found), 1)
        a, b = found[0]
        self.assertTrue(a < 3200 and b > 3600)

    def test_short_input(self):
        self.assertEqual(window_flags("ACG", 200), [])
        self.assertEqual(window_islands("ACG"), [])


if __name__ == "__main__":
    unittest.main()

History

Gardiner-Garden and Frommer (1987) surveyed vertebrate sequences and gave the criteria of at least 200 bases, a GC content above 50 percent and an O/E ratio of CG above 0.6, which many tools still use. Durbin, Eddy, Krogh and Mitchison (1998) used CpG islands as the running example of chapter 3 of their textbook: first a pair of Markov chains to tell island sequences from others, then a hidden Markov model with eight states to find islands in a long sequence, decoded by the Viterbi algorithm. Takai and Jones (2002) proposed stricter criteria after a study of human chromosomes 21 and 22.

References

  1. Richard Durbin, Sean R. Eddy, Anders Krogh and Graeme Mitchison, Biological Sequence Analysis, Cambridge University Press, 1998, Chapter 3, the CpG island example (Markov chains for discrimination, and the hidden Markov model for locating islands, decoded with the Viterbi algorithm)
  2. M. Gardiner-Garden and M. Frommer, CpG islands in vertebrate genomes, Journal of Molecular Biology 196(2), 1987, pp. 261 to 282, the criteria for a CpG island (at least 200 bp, G + C above 50 percent, observed over expected CpG above 0.6)
  3. Daiya Takai and Peter A. Jones, Comprehensive analysis of CpG islands in human chromosomes 21 and 22, PNAS 99(6), 2002, pp. 3740 to 3745, the stricter criteria (more than 500 bp, G + C of 55 percent or more, observed over expected CpG of 0.65)

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
  • History with a source
  • a scene preset for the example