Algorithmadvanced
Generalized HMM gene finding
Also called GHMM gene finder, GENSCAN model.
Parse a genome into exons, introns and intergenic regions with a generalized HMM, whose states emit whole segments with explicit length distributions, decoded by a segment Viterbi recursion.
- Time
- Θ(n K D + n K^2) worst · average · best
- Space
- Θ(n K) extra
- Where
- D = the largest segment length of a state; K = the number of states; n = the length of the sequence
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
A generalized hidden Markov model (GHMM) is a hidden Markov model in which a state emits a whole segment of the sequence at once, not one letter. Each state has its own length distribution and its own model of the letters of a segment. For gene finding, the states are the parts of a gene: intergenic DNA, exons, introns, and the signals between them. A path through the states that covers the sequence is a parse, a complete gene structure such as "intergenic, exon from 1001 to 1210, intron to 1874, exon to 2050, intergenic". The decoder finds the parse of largest probability with a segment form of the Viterbi algorithm: for each end position and state, it tries every segment length. Kulp, Haussler, Reese and Eeckman (1996) used a GHMM for the Genie gene finder, and Burge and Karlin (1997) built GENSCAN on the same idea. The model is the hidden semi-Markov model of speech recognition, with segment models suited to DNA.
In plain words
A gene has parts of different kinds and lengths. Exons have a typical length that is not well described by a coin that decides at each letter whether to stop, and introns must start with GT and end with AG. A GHMM lets each kind of part choose its length from a table and then write all of its letters at once, in its own style. To read a DNA sequence, the decoder walks from left to right. At each position and for each kind of part, it asks: if a part of this kind ends here, what is the best length for it, and what was the best explanation of everything before it? It writes down the answer, and at the end it follows the answers back to recover the best list of parts.
The problem
Input. A sequence , and a GHMM with states and, for each state : a start probability , an end weight , transition probabilities to other states, a length distribution for , and a segment model , the probability that state emits the bases as one segment of length .
Output. A parse with that maximizes
The segment model can be anything that scores a whole segment. In a gene finder, the segment model of an exon is a content sensor, such as a three-periodic Markov chain whose phase follows the reading frame, times signal sensors at its ends, such as a splice site model for the donor and acceptor, or a model of the start or stop codon. A segment that breaks a hard rule, such as an exon with an in-frame stop codon or an intron that does not start with GT, gets probability 0. The finding of the best parse is the gene prediction problem for this model.
The algorithm
Let be the best log score of a parse of whose last segment has state and ends at , and let be the best log score of such a parse followed by a step into . Positions are 0-based and intervals half-open.
GHMM-VITERBI(x, model)- 1
for b ← 1 to n do - 2
for each state q do - 3
Γ[b][q] ← -∞ - 4
for l ← 1 to min(D_q, b) do - 5
enter ← ln π_q if l = b, else Δ[b - l][q] - 6
s ← enter + ln d_q(l) + ln f_q(x[b - l, b)) - 7
if s > Γ[b][q] then Γ[b][q] ← s; back[b][q] ← l - 8
for each state q: Δ[b][q] ← max over p of Γ[b][p] + ln a_pq, and keep the best p - 9
q ← the state with the largest Γ[n][q] + ln ε_q - 10
trace back from (n, q): emit the segment (q, n - l, n) with l = back[n][q], move to (n - l, the best p of Δ[n - l][q]), and repeat until position 0 - 11
return the segments in order
Line L8 precomputes the best way to enter each state at each position, so the loop over lengths does not loop over the previous state too. The segment score of line L6 must take time. For a Markov content model this comes from prefix sums: store once, and the score of any segment is . A three-periodic model needs three prefix arrays, one for each phase of the segment start.
Example
Take a GHMM with two states, N (AT-rich) and G (GC-rich). N emits A and T with probability 0.4 each and C and G with 0.1 each; G does the opposite. N has a uniform length on 1 to 10, so ; G has a uniform length on 2 to 10, so and . The start probabilities are , every state may end the sequence, and the states alternate: and . Decode . The table gives and in natural logarithms, rounded, with the best length in brackets.
| base | [] | [] | |
|---|---|---|---|
| 1 | A | [1] | |
| 2 | T | [2] | [2] |
| 3 | G | [3] | [3] |
| 4 | C | [4] | [2] |
| 5 | G | [5] | [3] |
| 6 | C | [6] | [4] |
| 7 | G | [1] | [5] |
| 8 | C | [1] | [6] |
| 9 | A | [1] | [7] |
| 10 | T | [2] | [8] |
For example, with enters G at position 2 from the N segment AT, , and adds , for . At the better end is N with and , so the last segment is N on . It was entered from G at position 8, whose best length is 6, so the segment before is G on , and it was entered from N at position 2 with length 2. The parse is N , G , N , with log probability . A single N segment scores , and a single G segment : the two extra segments cost , but placing GCGCGC in the GC-rich state gains more.
Correctness
The best partial parse that ends with a segment consists of a best partial parse of , then a step into , then the segment. The terms of the last step depend only on , , and the previous state, so the best prefix can be chosen independently, and , with in place of . Lines L3 to L7 compute this maximum, and line L8 computes from the finished row. By induction on the tables are right, line L9 picks the best end, and the stored choices of line L10 rebuild a parse with exactly that score. The full proof is in the proofs folder, and the test file checks the decoder against the enumeration of all parses of short sequences.
Proof: The segment Viterbi recursion returns a parse of largest scorefull
Fix a GHMM with states and a sequence of length . All quantities are natural logarithms, with for an impossible event: (start), (transition), (end), (length of a segment of , with for ) and (state emits ). A parse is a list of segments with . Its score is
A partial parse of is the same object with , and its score is the same sum without the end term .
For and , let be the largest score of a partial parse of whose last segment has state , or if there is none. For , let , the best score of a partial parse of followed by a step into .
Lemma 1 (recursion). For ,
Proof. Take a partial parse of that ends with a segment . If , the parse is that one segment and its score is . If , removing the last segment leaves a partial parse of that ends in some state , and the score is the score of that shorter parse plus . The added terms depend only on , , and , not on the earlier segments. So for fixed and , the best choice of the shorter parse is one of score , and the best over gives . Conversely, each value on the right side is the score of a partial parse built in this way. Lengths above have and can be left out.
Lemma 2 (the tables). When line L8 has run for position , the code holds and for all , and is a length that reaches the maximum of Lemma 1, and a state that reaches the maximum in .
Proof. By induction on . The loop over in lines L4 to L7 reads only for , which holds by the induction hypothesis, and reads when (line L5). Skipping a term with an impossible entry changes no maximum. So lines L3 to L7 compute the maximum of Lemma 1, and keep a length that reaches it. Line L8 then computes from the finished row .
Theorem. If some parse has a finite score, the decoder returns a parse whose score is the largest score of any parse. Otherwise it returns and no parse.
Proof. Every parse is a partial parse of plus the end term of its last state, so the largest parse score is , and line L9 picks a state that reaches it; if all values are , no parse is possible. Line L10 follows the stored choices: from it emits the segment with , and moves to with . By induction on the number of steps, the segments emitted so far, read backward, are the tail of a partial parse whose score is at the current pair: by Lemma 2 the chosen and satisfy when , and when . Each step lowers by at least 1, so the loop ends at with a full parse whose score is . Line L11 returns its segments in order.
Running time. For each and , lines L4 to L7 try at most lengths, each with one call of and . Line L8 costs per position. With and segment scores in time (by prefix sums, as in the toy gene model), the total is in the worst case, that is per state. The tables take space, and the traceback takes time.
Complexity
- Time. For each of the positions and states, line L4 tries up to lengths, and line L8 costs . With segment scores in , the time is , that is per state. With equal to , the general GHMM costs , which is too slow for a chromosome.
- Space. The tables , and the back pointers take .
- How gene finders stay linear. Burge and Karlin give introns and intergenic regions geometric length distributions. A state with a geometric length is an ordinary HMM state with a self-loop, so it costs per position instead of . Only exons have general length distributions, and an exon cannot contain an in-frame stop codon, so its candidate starts at each end position are limited to the current open reading frame. With a list of candidate signals (splice sites, start and stop codons), the loop of line L4 runs only over the candidates.
Properties
- Exact for its model. The decoder returns a parse of largest probability. The quality of the gene structure depends on the model.
- An HMM is a special case. If every , a GHMM is an HMM, and the recursion is the ordinary Viterbi algorithm. The test file checks this case.
- Explicit lengths. An HMM state has a geometric length distribution, whose most likely length is 1. Exons have a peaked length distribution, which only an explicit can model well.
- Modular. Each state can use its own segment model: a Markov chain, a position weight matrix, a maximal dependence decomposition tree, or a whole sub-model. The decoder needs only the segment scores.
- Hard constraints. Rules such as GT at the start of an intron, no in-frame stop codon in an exon, and a total coding length that is a multiple of 3 are written as zero probabilities. The phase rule needs one intron state for each of the three phases, as in GENSCAN, so that the frame of the next exon follows from the frame of the previous one.
Variants and improvements
- Posterior probabilities. The segment forms of the forward and backward recursions (see forward-backward) give the probability of each exon given the sequence. GENSCAN reports such a probability for each predicted exon.
- Both strands. A full gene finder has a mirror copy of every gene state for the reverse strand, with reverse-complemented models.
- Training. The parameters come from a set of annotated genes: length tables from the observed lengths, segment models from counts. With labeled data these are maximum likelihood estimates and need no iteration; the Baum-Welch form of EM is used when the labels are missing.
- Comparative and discriminative models. A pair GHMM or a phylogenetic GHMM scores two or more genomes at once (comparative gene finding). A semi-Markov conditional random field uses the same decoder with weights trained to separate correct from wrong parses.
- External evidence. Alignments of proteins or transcripts can be added as extra factors in the segment scores, which turns the GHMM into a combiner of evidence.
When to use it
Use a GHMM to predict complete gene structures in eukaryotic genomes, where genes are split into exons and introns and the signals at their ends are weak. It is the core of ab initio gene prediction. For bacterial genomes, where most genes are single open reading frames, a simpler model, such as an interpolated Markov model on each ORF, is usually enough. When transcripts or close genomes are available, combine the GHMM with that evidence.
Pitfalls
- Quadratic time. A general length distribution on every state makes the decoder . Bound the lengths, or make the long states geometric.
- Segment scores must be fast. Scoring a segment by a loop over its bases adds a factor . Use prefix sums.
- Phase errors. Without separate intron states for the three phases, the decoder can join exons whose frames do not fit, and the predicted protein is wrong after the first intron.
- Underflow and minus infinity. Work in log space and skip impossible terms; adding to by mistake gives NaN.
- Probabilities that are not comparable. The segment scores of different states must be probabilities of the same bases. A state whose model ignores part of its segment gets an unfair advantage.
- Ties. Equal scores are common with integer-valued toy models. Fix a rule, such as the shortest length and the smallest state index, so that the output is the same on every run.
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)
generalized_hmm_gene_finder.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-hmm-gene-finder/. The authors are listed in prov/FHW813.jsonl.
"""Viterbi decoding of a generalized HMM (GHMM), and a small gene model for it.
A GHMM explains x[0:n] as a parse: a list of segments (q, a, b) that cover
0..n in order, where state q emits the whole segment x[a:b]. A model is a
Ghmm with these fields (all probabilities are given as natural logarithms,
and -math.inf means "impossible"):
- states: the names of the states, indexed 0..K-1;
- log_start[q]: ln of the probability that the first segment has state q;
- log_trans[p][q]: ln of the probability that a segment of state p is
followed by a segment of state q;
- log_end[q]: ln of the weight of a parse whose last segment has state q
(use 0.0 for every state to let any state end the sequence);
- max_dur[q]: the largest segment length of state q;
- log_dur(q, l): ln of the probability that a segment of state q has length l;
- log_seg(q, a, b): ln of the probability that state q emits x[a:b] as a
segment of length b - a.
The score of a parse is log_start of its first state, plus log_trans of each
step, plus log_dur and log_seg of each segment, plus log_end of its last
state. ghmm_viterbi returns a parse of largest score. Ties go to the smaller
length, then to the smaller state index.
toy_gene_model(x) builds a GHMM with the states N (intergenic), E (exon,
three-periodic composition) and I (intron, GT at the start and AG at the
end) whose log_seg takes O(1) time by prefix sums.
"""
from __future__ import annotations
import math
from collections import namedtuple
from typing import Callable, Dict, List, Optional, Sequence, Tuple
NEG = -math.inf
Ghmm = namedtuple("Ghmm", ["states", "log_start", "log_trans", "log_end",
"max_dur", "log_dur", "log_seg"])
Segment = Tuple[str, int, int]
def parse_score(model: Ghmm, parse: Sequence[Segment]) -> float:
"""The score of a parse given as (state name, a, b) segments."""
idx = {s: i for i, s in enumerate(model.states)}
total, prev = 0.0, None
for name, a, b in parse:
q = idx[name]
if b - a < 1 or b - a > model.max_dur[q]:
return NEG
total += model.log_start[q] if prev is None else model.log_trans[prev][q]
total += model.log_dur(q, b - a) + model.log_seg(q, a, b)
prev = q
return total + model.log_end[prev]
def ghmm_viterbi(model: Ghmm, n: int) -> Tuple[float, Optional[List[Segment]]]:
"""A parse of x[0:n] of largest score, as (score, segments), or (-inf, None)."""
K = len(model.states)
gamma = [[NEG] * K for _ in range(n + 1)] # best parse of x[0:b] whose last segment is q
back_len = [[0] * K for _ in range(n + 1)]
delta = [[NEG] * K for _ in range(n + 1)] # best way to start a segment of q at b
delta_arg = [[-1] * K for _ in range(n + 1)]
for b in range(1, n + 1): # @line L1
for q in range(K): # @line L2
best, best_l = NEG, 0 # @line L3
for l in range(1, min(model.max_dur[q], b) + 1): # @line L4
enter = model.log_start[q] if l == b else delta[b - l][q] # @line L5
if enter == NEG:
continue
s = enter + model.log_dur(q, l) + model.log_seg(q, b - l, b) # @line L6
if s > best: # @line L7
best, best_l = s, l
gamma[b][q], back_len[b][q] = best, best_l
for q in range(K): # @line L8
bp, bv = -1, NEG
for p in range(K):
v = gamma[b][p] + model.log_trans[p][q]
if v > bv:
bp, bv = p, v
delta[b][q], delta_arg[b][q] = bv, bp
end_q, end_v = -1, NEG
for q in range(K): # @line L9
v = gamma[n][q] + model.log_end[q]
if v > end_v:
end_q, end_v = q, v
if end_q < 0:
return NEG, None
parse: List[Segment] = []
b, q = n, end_q
while b > 0: # @line L10
l = back_len[b][q]
parse.append((model.states[q], b - l, b))
b, q = b - l, (delta_arg[b - l][q] if b - l > 0 else -1)
parse.reverse()
return end_v, parse # @line L11
# ---------------------------------------------------------------- a toy gene model
def _logs(dist: Dict[str, float]) -> Dict[str, float]:
return {k: (math.log(v) if v > 0 else NEG) for k, v in dist.items()}
def _prefix(x: str, logp: Callable[[int, str], float]) -> List[float]:
out = [0.0]
for i, c in enumerate(x):
out.append(out[-1] + logp(i, c))
return out
def toy_gene_model(x: str, intergenic: Dict[str, float], intron: Dict[str, float],
exon_phases: Sequence[Dict[str, float]], max_dur: int = 200,
min_exon: int = 3, min_intron: int = 4,
p_exon_to_intron: float = 0.5) -> Ghmm:
"""A forward-strand gene model with the states N, E and I.
- N emits bases independently with the probabilities intergenic.
- E emits base j of the segment with exon_phases[j % 3] (three-periodic,
the phase restarts at each exon), and has length at least min_exon.
- I emits bases with intron, must start with GT and end with AG, and has
length at least min_intron.
Every state has a uniform length distribution on its allowed lengths up to
max_dur. A parse starts and ends in N, and goes N -> E -> (I -> E)* -> N.
"""
s = x.upper()
ln_n, ln_i = _logs(intergenic), _logs(intron)
ln_e = [_logs(d) for d in exon_phases]
pre_n = _prefix(s, lambda i, c: ln_n[c])
pre_i = _prefix(s, lambda i, c: ln_i[c])
# pre_e[r][i] sums the exon log probabilities of x[0:i] for an exon that starts at a position = r mod 3.
pre_e = [_prefix(s, lambda i, c, r=r: ln_e[(i - r) % 3][c]) for r in range(3)]
lo = [1, min_exon, min_intron]
def log_seg(q: int, a: int, b: int) -> float:
if q == 0:
return pre_n[b] - pre_n[a]
if q == 1:
return pre_e[a % 3][b] - pre_e[a % 3][a]
if s[a:a + 2] != "GT" or s[b - 2:b] != "AG":
return NEG
return pre_i[b] - pre_i[a]
def log_dur(q: int, l: int) -> float:
if l < lo[q]:
return NEG
return -math.log(max_dur - lo[q] + 1)
ln = lambda p: math.log(p) if p > 0 else NEG
trans = [[NEG, 0.0, NEG],
[ln(1 - p_exon_to_intron), NEG, ln(p_exon_to_intron)],
[NEG, 0.0, NEG]]
return Ghmm(("N", "E", "I"), [0.0, NEG, NEG], trans, [0.0, NEG, NEG],
[max_dur] * 3, log_dur, log_seg)
test_generalized_hmm_gene_finder.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-hmm-gene-finder/. The authors are listed in prov/FHW813.jsonl.
"""Tests of the GHMM decoder, against enumeration of all parses."""
import math
import random
import unittest
from bioseq import DNA
from generalized_hmm_gene_finder import NEG, Ghmm, ghmm_viterbi, parse_score, toy_gene_model
def all_parses(n, K, max_dur):
"""Every parse of 0..n as a list of (state index, a, b)."""
def rec(a):
if a == n:
yield []
return
for q in range(K):
for l in range(1, min(max_dur[q], n - a) + 1):
for rest in rec(a + l):
yield [(q, a, a + l)] + rest
return rec(0)
def random_model(rng, x, K):
"""A GHMM with random tables; some entries are impossible."""
def maybe(v):
return NEG if rng.random() < 0.15 else v
names = tuple("S%d" % q for q in range(K))
start = [maybe(math.log(rng.random() + 0.01)) for _ in range(K)]
trans = [[maybe(math.log(rng.random() + 0.01)) for _ in range(K)] for _ in range(K)]
end = [maybe(math.log(rng.random() + 0.01)) for _ in range(K)]
max_dur = [rng.randrange(1, 5) for _ in range(K)]
dur = {(q, l): maybe(math.log(rng.random() + 0.01)) for q in range(K) for l in range(1, 6)}
emit = [{c: math.log(rng.random() + 0.05) for c in DNA} for _ in range(K)]
bonus = [rng.uniform(-1, 1) for _ in range(K)]
def log_seg(q, a, b):
# A score that depends on the segment as a whole, not only on its bases.
return sum(emit[q][c] for c in x[a:b]) + bonus[q] * (x[a] == x[b - 1])
return Ghmm(names, start, trans, end, max_dur, lambda q, l: dur[(q, l)], log_seg)
class TestDecoder(unittest.TestCase):
def test_against_enumeration(self):
rng = random.Random(21)
for trial in range(60):
K = rng.randrange(1, 4)
n = rng.randrange(1, 8)
x = "".join(rng.choice(DNA) for _ in range(n))
m = random_model(rng, x, K)
best = NEG
for p in all_parses(n, K, m.max_dur):
best = max(best, parse_score(m, [(m.states[q], a, b) for q, a, b in p]))
score, parse = ghmm_viterbi(m, n)
if best == NEG:
self.assertEqual(score, NEG)
self.assertIsNone(parse)
continue
self.assertAlmostEqual(score, best, places=9)
self.assertAlmostEqual(parse_score(m, parse), score, places=9)
self.assertEqual(parse[0][1], 0)
self.assertEqual(parse[-1][2], n)
for (_, a1, b1), (_, a2, b2) in zip(parse, parse[1:]):
self.assertEqual(b1, a2)
def test_hmm_is_a_special_case(self):
# With max_dur 1 a GHMM is an HMM, and the decoder is the Viterbi algorithm.
rng = random.Random(22)
x = "".join(rng.choice(DNA) for _ in range(30))
m = random_model(rng, x, 2)
m = m._replace(max_dur=[1, 1], log_dur=lambda q, l: 0.0, log_start=[0.0, 0.0],
log_trans=[[math.log(0.9), math.log(0.1)], [math.log(0.2), math.log(0.8)]],
log_end=[0.0, 0.0])
score, parse = ghmm_viterbi(m, len(x))
V = [m.log_seg(q, 0, 1) for q in range(2)]
for i in range(1, len(x)):
V = [max(V[p] + m.log_trans[p][q] for p in range(2)) + m.log_seg(q, i, i + 1) for q in range(2)]
self.assertAlmostEqual(score, max(V), places=9)
self.assertEqual(len(parse), len(x))
class TestToyGeneModel(unittest.TestCase):
N = {"A": 0.3, "C": 0.2, "G": 0.2, "T": 0.3}
I = {"A": 0.2, "C": 0.15, "G": 0.15, "T": 0.5}
E = [{"A": 0.1, "C": 0.1, "G": 0.7, "T": 0.1},
{"A": 0.7, "C": 0.1, "G": 0.1, "T": 0.1},
{"A": 0.1, "C": 0.7, "G": 0.1, "T": 0.1}]
def draw(self, rng, dist, n):
keys = sorted(dist)
return "".join(rng.choices(keys, [dist[k] for k in keys], k=n))
def draw_exon(self, rng, n):
return "".join(self.draw(rng, self.E[j % 3], 1) for j in range(n))
def test_prefix_sums_match_direct_sums(self):
rng = random.Random(23)
x = "".join(rng.choice(DNA) for _ in range(40)) + "GTAAAAG"
m = toy_gene_model(x, self.N, self.I, self.E, max_dur=50)
for _ in range(100):
a = rng.randrange(0, len(x))
b = rng.randrange(a + 1, len(x) + 1)
direct_n = sum(math.log(self.N[c]) for c in x[a:b])
direct_e = sum(math.log(self.E[(i - a) % 3][x[i]]) for i in range(a, b))
self.assertAlmostEqual(m.log_seg(0, a, b), direct_n, places=9)
self.assertAlmostEqual(m.log_seg(1, a, b), direct_e, places=9)
ok = x[a:a + 2] == "GT" and x[b - 2:b] == "AG"
self.assertEqual(m.log_seg(2, a, b) > NEG, ok)
def test_planted_gene(self):
rng = random.Random(24)
parts = [("N", self.draw(rng, self.N, 120)), ("E", self.draw_exon(rng, 90)),
("I", "GT" + self.draw(rng, self.I, 60) + "AG"), ("E", self.draw_exon(rng, 60)),
("N", self.draw(rng, self.N, 120))]
x = "".join(p for _, p in parts)
truth = "".join(s * len(p) for s, p in parts)
m = toy_gene_model(x, self.N, self.I, self.E, max_dur=150)
score, parse = ghmm_viterbi(m, len(x))
self.assertGreater(score, NEG)
self.assertEqual([s for s, _, _ in parse], ["N", "E", "I", "E", "N"])
called = "".join(s * (b - a) for s, a, b in parse)
agree = sum(1 for u, v in zip(truth, called) if u == v)
self.assertGreater(agree / len(x), 0.95)
intron = parse[2]
self.assertEqual(x[intron[1]:intron[1] + 2], "GT")
self.assertEqual(x[intron[2] - 2:intron[2]], "AG")
def test_no_parse(self):
# A sequence longer than any intergenic segment, and with no GT...AG and no
# room for a gene, has no parse.
m = toy_gene_model("A" * 12, self.N, self.I, self.E, max_dur=5, min_exon=20)
self.assertEqual(ghmm_viterbi(m, 12), (NEG, None))
if __name__ == "__main__":
unittest.main()
History
Kulp, Haussler, Reese and Eeckman (1996) described a GHMM for human genes, in which each state models a whole gene part with its own length and content model. Burge and Karlin (1997) published GENSCAN, a GHMM with exon, intron and intergenic states on both strands, introns in three phases, geometric lengths for introns and intergenic regions, and signal models for the splice sites and the start and stop codons. The model is the explicit duration HMM, which Ferguson introduced for speech in 1980 and which Yu (2010) surveys as the hidden semi-Markov model.
References
- Chris Burge and Samuel Karlin, Prediction of complete gene structures in human genomic DNA, Journal of Molecular Biology 268(1), 1997, pp. 78 to 94; the GENSCAN state diagram (exon, intron and intergenic states on both strands, introns in three phases), the length distributions, and the signal models for splice sites and start and stop codons
- David Kulp, David Haussler, Martin G. Reese and Frank H. Eeckman, A generalized hidden Markov model for the recognition of human genes in DNA, Proceedings of ISMB 4, 1996, pp. 134 to 142, the GHMM that describes the legal parses of a DNA sequence into gene parts (the Genie gene finder)
- Shun-Zheng Yu, Hidden semi-Markov models, Artificial Intelligence 174(2), 2010, pp. 215 to 243, Section 3.1, the explicit duration model and the cost of its recursions
Where this leads
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 FHW813 Edit this page History Report an error Markdown