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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
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 over . For the HMM method, a model with the two states (island) and (background): start probabilities , transition probabilities , and emission probabilities for the first base and for a base after the base . For the window rule, a window length and two thresholds and , by default , and .
Output. A list of disjoint intervals of , the islands.
For the HMM method, the islands are the maximal runs of in a state path that maximizes
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 and , each emitting its own base.
For the window rule, a window of bases with cytosines, guanines and CG pairs is marked if and . The ratio compares the observed number of CG pairs with the number expected if the bases were independent. The islands are the maximal unions of marked windows that overlap or touch.
The algorithm
VITERBI-CPG(x, model)- 1
for each state k in {+, -}: V[k] ← ln π_k + ln e_k(x_1) - 2
for i ← 2 to n do - 3
for each state k in {+, -} do - 4
ptr[i][k] ← the state j with the largest V[j] + ln a_jk - 5
V'[k] ← V[j] + ln a_jk + ln e_k(x_i | x_{i-1}) for j = ptr[i][k] - 6
V ← V' - 7
q_n ← the state k with the largest V[k] - 8
for i ← n down to 2: q_{i-1} ← ptr[i][q_i] - 9
return the maximal runs of + in q_1 ... q_n WINDOW-CPG(x, w, g, r)- 10
for each window x[i, i + w), keeping the counts C, G and D up to date in O(1) per shift do - 11
mark the window if (C + G) / w > g and D · w / (C · G) > r - 12
return 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 (14 bases). The table gives and 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.
| base | |||
|---|---|---|---|
| 1 | A | ||
| 2 | T | ||
| 3 | A | (from ) | |
| 4 | T | (from ) | |
| 5 | C | (from ) | |
| 6 | G | ||
| 7 | C | ||
| 8 | G | ||
| 9 | C | ||
| 10 | G | (from ) | |
| 11 | T | (from ) | |
| 12 | A | ||
| 13 | T | ||
| 14 | A | (from ) |
At the larger value is . 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 from 0). Its log probability beats for the path with no island: the six C and G bases gain in the island state, more than the cost of the two switches. A shorter island of four C and G bases would gain only and would tie with the switches.
The window rule, scaled down to with and , on ATATATCGCGCGATATAT marks the windows that start at positions 4 to 8 (from 0). For example, ATCGCG has , and , so its GC fraction is and its ratio is . The window GCGATA starts at 9 and has only three C and G. The union of the marked windows is , 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 be the largest log probability of the first bases over the paths that end in state . A best path that ends in at extends a best path that ends at in some state , because the added term depends only on and . So , which is lines L4 and L5, and line L1 is the case . Line L7 takes the best end state, and the pointers of line L8 rebuild a path that reaches , the largest value of 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 be a sequence over with . The model has the states , the start probabilities , the transition probabilities , the first-base emissions and the conditional emissions . For a state path ,
with . The island calls of the HMM are the maximal runs of in a path that maximizes .
The Viterbi decoder
For and , let be the largest value of over the paths of length with , where the prefix probability is the same sum stopped at .
Lemma 1. After line L1, . After the pass of lines L3 to L6 for position , , and is a state with .
Proof. For the only path of length 1 that ends in is itself, and line L1 sets . Assume the claim for . A path of length that ends in is a path of length that ends in some , followed by , and its value is the value of the shorter path plus . The added term depends only on and , so the best path that ends in extends a best path that ends in its state , and
Line L4 picks a that reaches this maximum, with by the induction hypothesis, and line L5 computes the right side. Line L6 replaces only after both states are done, so line L5 always reads the values of position .
Lemma 2. The path built by lines L7 and L8 satisfies .
Proof. Line L7 picks with , and every path ends in some state, so this is the largest value of . Line L8 sets . We show by induction on , from down to 1, that the path obtained by following the pointers from has prefix value . For this is Lemma 1. For , the pointer satisfies by Lemma 1, and by the induction hypothesis the prefix up to has value , so the prefix up to has value . At this is the claim.
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 (0-based, half-open), let and be its numbers of C and G, and its number of positions with , and . The window is marked when and , with the ratio taken as 0 if .
Lemma 3. At line L11 for window , the counters hold , and .
Proof. For they are counted directly. Going from window to window removes the base and adds the base , so and change by the indicator of the added base minus that of the removed one. The CG pairs of window start at , and those of window at . So the pair at leaves and the pair at enters, and the code subtracts and adds exactly these two indicators.
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 , 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 with overlaps or touches it, so the union is , which the code stores. If , no later window starts before , so no later window can touch the old interval, and the old interval is maximal.
Running time
Lines L2 to L6 run times, each with additions and comparisons, and lines L7 and L8 take steps, so the decoder takes time and space for the pointers. The window scan spends time on the first window and on each of the other windows, so time in total and extra space besides the output.
Complexity
- Time. The decoder does steps for each base, so . With states it would be . The window rule spends on the first window and on each shift, so .
- Space. The decoder keeps two pointers per base for the traceback, . The window rule needs beyond the output. If memory is short, the decoder can keep pointers only at checkpoints and recompute the rest, for 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 has runs of mean length , so 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 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 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 probabilities underflows for in the thousands. Work with logarithms throughout.
- Zero probabilities. A model trained by counting can have , which forbids a state at some bases forever. Add pseudocounts before taking logarithms.
- Self-transition probabilities set the island length. With too small, the decoder breaks islands into pieces; with 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.
# 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
- 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)
- 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)
- 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.
| 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 0S3A9K Edit this page History Report an error Markdown