Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative

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 x=x1⋯xnx = x_1 \cdots x_n, and a GHMM with states Q={1,…,K}Q = \{1, \ldots, K\} and, for each state qq: a start probability πq\pi_q, an end weight ϵq\epsilon_q, transition probabilities apqa_{pq} to other states, a length distribution dq(l)d_q(l) for 1≤l≤Dq1 \le l \le D_q, and a segment model fq(x[a,b))f_q(x[a, b)), the probability that state qq emits the bases x[a,b)x[a, b) as one segment of length b−ab - a.

Output. A parse (q1,b0,b1),(q2,b1,b2),…,(qm,bm−1,bm)(q_1, b_0, b_1), (q_2, b_1, b_2), \ldots, (q_m, b_{m-1}, b_m) with 0=b0<b1<⋯<bm=n0 = b_0 < b_1 < \cdots < b_m = n that maximizes

P(x,parse)=πq1(∏r=2maqr−1qr)(∏r=1mdqr(br−br−1) fqr(x[br−1,br))) ϵqm.P(x, \text{parse}) = \pi_{q_1} \Big(\prod_{r=2}^{m} a_{q_{r-1} q_r}\Big) \Big(\prod_{r=1}^{m} d_{q_r}(b_r - b_{r-1}) \, f_{q_r}(x[b_{r-1}, b_r))\Big) \, \epsilon_{q_m}.

The segment model fqf_q 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 Γb(q)\Gamma_b(q) be the best log score of a parse of x[0,b)x[0, b) whose last segment has state qq and ends at bb, and let Δb(q)=max⁡p(Γb(p)+ln⁡apq)\Delta_b(q) = \max_p (\Gamma_b(p) + \ln a_{pq}) be the best log score of such a parse followed by a step into qq. Positions are 0-based and intervals half-open.

  1. GHMM-VITERBI(x, model)
  2. 1for b ← 1 to n do
  3. 2for each state q do
  4. 3Γ[b][q] ← -∞
  5. 4for l ← 1 to min(D_q, b) do
  6. 5enter ← ln π_q if l = b, else Δ[b - l][q]
  7. 6s ← enter + ln d_q(l) + ln f_q(x[b - l, b))
  8. 7if s > Γ[b][q] then Γ[b][q] ← s; back[b][q] ← l
  9. 8for each state q: Δ[b][q] ← max over p of Γ[b][p] + ln a_pq, and keep the best p
  10. 9q ← the state with the largest Γ[n][q] + ln ε_q
  11. 10trace 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
  12. 11return 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 O(1)O(1) time. For a Markov content model this comes from prefix sums: store P[i]=∑j<iln⁡p(xj)P[i] = \sum_{j < i} \ln p(x_j) once, and the score of any segment is P[b]−P[a]P[b] - P[a]. 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 dN(l)=1/10d_N(l) = 1/10; G has a uniform length on 2 to 10, so dG(l)=1/9d_G(l) = 1/9 and dG(1)=0d_G(1) = 0. The start probabilities are 1/21/2, every state may end the sequence, and the states alternate: aNG=aGN=1a_{NG} = a_{GN} = 1 and aNN=aGG=0a_{NN} = a_{GG} = 0. Decode x=ATGCGCGCATx = \mathrm{ATGCGCGCAT}. The table gives Γb(N)\Gamma_b(N) and Γb(G)\Gamma_b(G) in natural logarithms, rounded, with the best length ll in brackets.

bb base xbx_b Γb(N)\Gamma_b(N) [ll] Γb(G)\Gamma_b(G) [ll]
1 A −3.912-3.912 [1] −∞-\infty
2 T −4.828-4.828 [2] −7.496-7.496 [2]
3 G −7.131-7.131 [3] −8.412-8.412 [3]
4 C −9.433-9.433 [4] −8.858-8.858 [2]
5 G −11.736-11.736 [5] −9.774-9.774 [3]
6 C −14.039-14.039 [6] −10.691-10.691 [4]
7 G −15.296-15.296 [1] −11.607-11.607 [5]
8 C −16.212-16.212 [1] −12.523-12.523 [6]
9 A −15.742-15.742 [1] −14.826-14.826 [7]
10 T −16.658-16.658 [2] −17.128-17.128 [8]

For example, Γ4(G)\Gamma_4(G) with l=2l = 2 enters G at position 2 from the N segment AT, Γ2(N)=ln⁡12+ln⁡110+2ln⁡0.4=−4.828\Gamma_2(N) = \ln \frac12 + \ln \frac1{10} + 2 \ln 0.4 = -4.828, and adds ln⁡19+2ln⁡0.4=−4.030\ln \frac19 + 2 \ln 0.4 = -4.030, for −8.858-8.858. At b=10b = 10 the better end is N with −16.658-16.658 and l=2l = 2, so the last segment is N on [8,10)[8, 10). It was entered from G at position 8, whose best length is 6, so the segment before is G on [2,8)[2, 8), and it was entered from N at position 2 with length 2. The parse is N [0,2)[0, 2), G [2,8)[2, 8), N [8,10)[8, 10), with log probability −16.658-16.658. A single N segment scores −20.476-20.476, and a single G segment −17.598-17.598: the two extra segments cost ln⁡110+ln⁡19\ln \frac1{10} + \ln \frac19, but placing GCGCGC in the GC-rich state gains more.

Correctness

The best partial parse that ends with a segment (q,b−l,b)(q, b - l, b) consists of a best partial parse of x[0,b−l)x[0, b - l), then a step into qq, then the segment. The terms of the last step depend only on qq, ll, bb and the previous state, so the best prefix can be chosen independently, and Γb(q)=max⁡l(Δb−l(q)+ln⁡dq(l)+ln⁡fq(x[b−l,b)))\Gamma_b(q) = \max_l (\Delta_{b-l}(q) + \ln d_q(l) + \ln f_q(x[b - l, b))), with ln⁡πq\ln \pi_q in place of Δ0(q)\Delta_0(q). Lines L3 to L7 compute this maximum, and line L8 computes Δb\Delta_b from the finished row. By induction on bb 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 Q={1,…,K}Q = \{1, \ldots, K\} and a sequence xx of length n≥1n \ge 1. All quantities are natural logarithms, with −∞-\infty for an impossible event: sqs_q (start), tpqt_{pq} (transition), eqe_q (end), dq(l)d_q(l) (length ll of a segment of qq, with dq(l)=−∞d_q(l) = -\infty for l>Dql > D_q) and fq(a,b)f_q(a, b) (state qq emits x[a,b)x[a, b)). A parse is a list of segments (q1,b0,b1),(q2,b1,b2),…,(qm,bm−1,bm)(q_1, b_0, b_1), (q_2, b_1, b_2), \ldots, (q_m, b_{m-1}, b_m) with 0=b0<b1<⋯<bm=n0 = b_0 < b_1 < \cdots < b_m = n. Its score is

σ=sq1+∑r=2mtqr−1qr+∑r=1m(dqr(br−br−1)+fqr(br−1,br))+eqm.\sigma = s_{q_1} + \sum_{r=2}^{m} t_{q_{r-1} q_r} + \sum_{r=1}^{m} \big(d_{q_r}(b_r - b_{r-1}) + f_{q_r}(b_{r-1}, b_r)\big) + e_{q_m}.

A partial parse of x[0,b)x[0, b) is the same object with bm=bb_m = b, and its score is the same sum without the end term eqme_{q_m}.

For 1≤b≤n1 \le b \le n and q∈Qq \in Q, let Γb(q)\Gamma_b(q) be the largest score of a partial parse of x[0,b)x[0, b) whose last segment has state qq, or −∞-\infty if there is none. For 1≤b<n1 \le b < n, let Δb(q)=max⁡p(Γb(p)+tpq)\Delta_b(q) = \max_{p} (\Gamma_b(p) + t_{pq}), the best score of a partial parse of x[0,b)x[0, b) followed by a step into qq.

Lemma 1 (recursion). For 1≤b≤n1 \le b \le n,

Γb(q)=max⁡1≤l≤min⁡(Dq,b)(Eb−l(q)+dq(l)+fq(b−l,b)),E0(q)=sq,Ec(q)=Δc(q) for c≥1.\Gamma_b(q) = \max_{1 \le l \le \min(D_q, b)} \big(E_{b - l}(q) + d_q(l) + f_q(b - l, b)\big), \quad E_0(q) = s_q, \quad E_c(q) = \Delta_c(q) \text{ for } c \ge 1.

Proof. Take a partial parse of x[0,b)x[0, b) that ends with a segment (q,b−l,b)(q, b - l, b). If l=bl = b, the parse is that one segment and its score is sq+dq(l)+fq(0,b)s_q + d_q(l) + f_q(0, b). If l<bl < b, removing the last segment leaves a partial parse of x[0,b−l)x[0, b - l) that ends in some state pp, and the score is the score of that shorter parse plus tpq+dq(l)+fq(b−l,b)t_{pq} + d_q(l) + f_q(b - l, b). The added terms depend only on pp, qq, ll and bb, not on the earlier segments. So for fixed ll and pp, the best choice of the shorter parse is one of score Γb−l(p)\Gamma_{b - l}(p), and the best over pp gives Δb−l(q)\Delta_{b - l}(q). Conversely, each value on the right side is the score of a partial parse built in this way. Lengths above DqD_q have dq(l)=−∞d_q(l) = -\infty and can be left out. □\square

Lemma 2 (the tables). When line L8 has run for position bb, the code holds gamma[b][q]=Γb(q)\mathit{gamma}[b][q] = \Gamma_b(q) and delta[b][q]=Δb(q)\mathit{delta}[b][q] = \Delta_b(q) for all qq, and back[b][q]\mathit{back}[b][q] is a length ll that reaches the maximum of Lemma 1, and delta_arg[b][q]\mathit{delta\_arg}[b][q] a state pp that reaches the maximum in Δb(q)\Delta_b(q).

Proof. By induction on bb. The loop over ll in lines L4 to L7 reads delta[b−l][q]\mathit{delta}[b - l][q] only for b−l<bb - l < b, which holds Δb−l(q)\Delta_{b - l}(q) by the induction hypothesis, and reads sqs_q when b−l=0b - l = 0 (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 Δb(q)\Delta_b(q) from the finished row gamma[b]\mathit{gamma}[b]. □\square

Theorem. If some parse has a finite score, the decoder returns a parse whose score max⁡q(Γn(q)+eq)\max_q (\Gamma_n(q) + e_q) is the largest score of any parse. Otherwise it returns −∞-\infty and no parse.

Proof. Every parse is a partial parse of x[0,n)x[0, n) plus the end term of its last state, so the largest parse score is max⁡q(Γn(q)+eq)\max_q (\Gamma_n(q) + e_q), and line L9 picks a state qq that reaches it; if all values are −∞-\infty, no parse is possible. Line L10 follows the stored choices: from (b,q)(b, q) it emits the segment (q,b−l,b)(q, b - l, b) with l=back[b][q]l = \mathit{back}[b][q], and moves to (b−l,p)(b - l, p) with p=delta_arg[b−l][q]p = \mathit{delta\_arg}[b - l][q]. By induction on the number of steps, the segments emitted so far, read backward, are the tail of a partial parse whose score is Γb(q)\Gamma_b(q) at the current pair: by Lemma 2 the chosen ll and pp satisfy Γb(q)=Γb−l(p)+tpq+dq(l)+fq(b−l,b)\Gamma_b(q) = \Gamma_{b - l}(p) + t_{pq} + d_q(l) + f_q(b - l, b) when b−l>0b - l > 0, and Γb(q)=sq+dq(b)+fq(0,b)\Gamma_b(q) = s_q + d_q(b) + f_q(0, b) when l=bl = b. Each step lowers bb by at least 1, so the loop ends at b=0b = 0 with a full parse whose score is Γn(q)+eq\Gamma_n(q) + e_q. Line L11 returns its segments in order. □\square

Running time. For each bb and qq, lines L4 to L7 try at most DqD_q lengths, each with one call of dqd_q and fqf_q. Line L8 costs K2K^2 per position. With D=max⁡qDqD = \max_q D_q and segment scores in O(1)O(1) time (by prefix sums, as in the toy gene model), the total is Θ(n(KD+K2))\Theta(n (K D + K^2)) in the worst case, that is O(nD)O(n D) per state. The tables take Θ(nK)\Theta(n K) space, and the traceback takes O(n)O(n) time.

Complexity

  • Time. For each of the nn positions and KK states, line L4 tries up to DD lengths, and line L8 costs K2K^2. With segment scores in O(1)O(1), the time is Θ(nKD+nK2)\Theta(n K D + n K^2), that is O(nD)O(n D) per state. With DD equal to nn, the general GHMM costs Θ(n2K)\Theta(n^2 K), which is too slow for a chromosome.
  • Space. The tables Γ\Gamma, Δ\Delta and the back pointers take Θ(nK)\Theta(n K).
  • 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 O(1)O(1) per position instead of O(D)O(D). 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 Dq=1D_q = 1, 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 dqd_q 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 Θ(n2K)\Theta(n^2 K). 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 DD. 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 −∞-\infty to +∞+\infty 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.

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)
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

  1. 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
  2. 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)
  3. 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.

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